POST form with JQuery using $.post()

时间:2015-10-30 23:32:38

标签: php jquery html forms web

I have the following form <form id="colorTest" method="POST"> <input type="text" id='responseText' name="responseText" value=""> <input type="button" id='confirm' name="confirm" value="confirm"> <input type='text' id="idNum" name="idNum"> <input type='text' id='correct' id="correct"> </form> Only the value for #responseText is actually typed in, #idNum is passed from another page, while the other fields are filled by this function: <script type="text/javascript"> var arr = [2,5,6,7,10,16,29,42,57]; x = 0 /* idNum is passed from another page to this one */ $(document).ready(function() { document.getElementById('idNum').value = localStorage.memberID; /* when something is typed in the form */ $('#responseText').on('input', function() { /* the value is stored */ var response = document.getElementById('responseText').value; /* and compared with the vector arr that contains the correct answers*/ if( response == arr[x]){ $("#correct").attr('value', 'yes'); }else{ $("#correct").attr('value', 'no'); }; }); /* confirm is the button to send the asnwer */ $('#confirm').click(function(){ $.post("testColor.php", $("#colorTest").serialize()); x = x + 1; }); }); </script> And here is my php: <?php // Create connection $conn = new mysqli($servername, $username, $password, $dbname); // Check connection if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } $response = $_POST["responseText"]; $memberID = $_POST["idNum"]; $timeStmp = time(); $correct = $_POST["correct"]; $sql = "INSERT INTO colorBlind (memberID, response, correct, timeStmp) VALUES ('$memberID', '$response' ,'".$correct."','".$timeStmp."')"; if ($conn->query($sql) === TRUE) { echo "New record created successfully"; } else { echo "Error: " . $sql . "<br>" . $conn->error; } $conn -> close(); ?> Now, I am sure the php is called correctly when the click event occurs on #confirm, because the timestamp invoked in the php is recorded in my db. Nevertheless, none of the value in the fields is passed in the php. Namely if do somethin like: echo $_POST["idNum"]; I get back an empty field. Anybody has any idea what I am doing wrong or any suggestions on how to debug it? I have been spending days on this without any progress.

1 个答案:

答案 0 :(得分:0)

我注意到的第一件事就是你的

<input type='text' id='correct' id="correct"> 

包含id="correct"两次。我确定您要添加name="correct"

当您使用$("#colorTest").serialize()时,将返回

responseText=foo&idNum=bar&correct=foobar

我可以看到这将如何用于GET请求。但是当您使用$ .post()时,您会想要为POST数据传递键/值对的对象。

例如,这应该有效:

var params = {
    responseText: 'foo',
    idNum: 'bar',
    correct: 'foobar'
};
$.post("testColor.php", params);