php - POST form with JQuery using $.post() -
i have 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 value #responsetext typed in, #idnum passed page, while other fields filled function:
<script type="text/javascript"> var arr = [2,5,6,7,10,16,29,42,57]; x = 0 /* idnum passed page 1 */ $(document).ready(function() { document.getelementbyid('idnum').value = localstorage.memberid; /* when typed in form */ $('#responsetext').on('input', function() { /* value stored */ var response = document.getelementbyid('responsetext').value; /* , compared vector arr contains correct answers*/ if( response == arr[x]){ $("#correct").attr('value', 'yes'); }else{ $("#correct").attr('value', 'no'); }; }); /* confirm button send asnwer */ $('#confirm').click(function(){ $.post("testcolor.php", $("#colortest").serialize()); x = x + 1; }); }); </script>
and here 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 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, sure php called correctly when click event occurs on #confirm, because timestamp invoked in php recorded in db. nevertheless, none of value in fields passed in php. namely if somethin like:
echo $_post["idnum"];
i empty field.
anybody has idea doing wrong or suggestions on how debug it? have been spending days on without progress.
the first thing noticed
<input type='text' id='correct' id="correct">
contains id="correct"
twice. i'm sure meant add name="correct"
.
when use $("#colortest").serialize()
, return
responsetext=foo&idnum=bar&correct=foobar
i can see how used request. seeing you're using $.post(), you'll want pass in object of key/value pairs post data.
for example, should work:
var params = { responsetext: 'foo', idnum: 'bar', correct: 'foobar' }; $.post("testcolor.php", params);
Comments
Post a Comment