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

时间:2016-02-29 04:35:34

标签: javascript jquery html ajax

我试图让这个表单通过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");
});

AJAX:

$(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);
?>

2 个答案:

答案 0 :(得分:0)

您需要为表单字段指定name=

$().serialize();

将根据name

创建一串参数

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

答案 1 :(得分:0)

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

data:{hotkey:hotkey},

在php中你可以使用:

获取数据
$hotkey=$_POST['hotkey'];