尝试使用 ajax 和 jquery 序列化表单

Trying to serialize form with ajax and jquery

本文关键字:jquery 序列化 表单 ajax      更新时间:2023-09-26

我正在尝试让这个表单通过 ajax 从 jquery 中的模态提交用户输入,但 ajax 调用没有获取用户输入。正在对服务器进行 ajax 调用,但是当我检查服务器是否已注册用户输入时,它是空白的。

HTML:
<body>
  <div id="home">
    <p>Home</p>
  </div>
  <div id="welcome">
    <span>Welcome  <?php echo $_SESSION['user']; ?></span>
  </div>
  <form id="form">
    <p1>Please enter in your hotkey below</p1>
    <input type="text" id="hotkey" placeholder="Hotkey">
    <input id="submit" type="button" value="Submit">
  </form>
  <div id="keyshortcut">
    <input type="text" id="keyshortcut" placeholder="hotkey">
  </div>
  <div id="select_button">
    <button id="select-hotkey">Select Your Hotkey</button>
  </div>
  <div id="hotkeyselection">
    <span>This is the hotkey you have selected:</span>
  </div>
  <div id="logout">
    <a href="logout.php?logout">Log-Out</a>
  </div>
  <br>
</body>

Jquery:

$(function() {
   dialog = $("#form").dialog({
     autoOpen: false,
     height: 250,
     width: 350,
     modal: true,
     buttons: {
       Cancel: function() {
         dialog.dialog("close");
       }
     },
     close: function() {
       form[0].reset();
     }
});
$("#select-hotkey").button().on("click", function() {
  dialog.dialog("open");
});

阿贾克斯:

$(document).ready(function() {
  $("#submit").click(function() {
    var hotkey = $("#hotkey").val();
    var dataString = 'hotkey=' + hotkey;
    alert(dataString);
    $.ajax({
      type: "POST",
      url: "submithotkey.php",
      data: $("#form").serialize(),
      success: function(result) {
        alert(result);
      }
    });
  });
});

.PHP

<?php
$con='';
$con= mysqli_connect("localhost","***","****","***");
$curr_user=$_SESSION['user'];
$data=$_POST['serialize'];
$hotkey=$data['hotkey'];
$query = "insert into users(Hotkey) values ('$hotkey',) where username='$curr_user'";
$run_query = mysqli_query($con, $query);
?>
您需要

为表单字段提供一个name=

$().serialize();

将按其name创建一串参数

示例:http://jsbin.com/sowutafuju/edit?html,js,console,output

尝试在 ajax 中使用此数据结构

data:{hotkey:hotkey},

在 PHP 中,您可以使用以下方法获取数据:

$hotkey=$_POST['hotkey'];