Note that there are some explanatory texts on larger screens.

plurals
  1. POJQuery with PHP, using $.ajax
    text
    copied!<p>I've been struggling for the entire day, I can't seem to get it right to send through a JSON object to a PHP file using the $.ajax function. I eventually got it right to send it through but now it refuses to decode.</p> <p>//JQuery File</p> <pre><code> var user = { "email" : document.getElementById('email1').value, "password" : document.getElementById('pwd1').value, "fname" : document.getElementById('firstname').value, "lname" : document.getElementById('lastname').value, "gender" : Validator.getGender(), "dob" : document.getElementById('dob').value }; JSON.stringify(user); user = {json:user}; $.ajax({ type: "POST", url: "register.php", dataType: 'json', data: user, success: function(result) { alert("It worked :D"); alert(result); }, failure: function() { alert('whoops'); } }); </code></pre> <p>//PHP File</p> <pre><code>&lt;?php $json = $_REQUEST['json']; $json = stripslashes($json); $jsonobj = json_decode($json); $fname = $jsonobj-&gt;fname; $lname = $jsonobj-&gt;lname; $password = $jsonobj-&gt;password; $email = $jsonobj-&gt;email; $gender = $jsonobj-&gt;gender; $dob = $jsonobj-&gt;dob; echo $gender; </code></pre> <p>?></p> <p>Am I doing something completely silly ? I'm just echoing the gender variable back for now but am actually going to use this to enter it into a database.</p> <p>Thanks in advance :)</p> <p>EDIT:</p> <p>How would it would it work if my php file looked like this:</p> <pre><code> session_start(); $db = mysql_connect("localhost", "root"); if(!$db) { die("DB connection failed: " . mysql_error()); } $db_select = mysql_select_db("tinyspace", $db); if(!$db_select) { die("DB connection failed: " . mysql_error()); } $json_string = $_REQUEST["json"]; $jsonobj = json_decode($_REQUEST["json"]); $fname = $jsonobj -&gt; fname; $lname = $jsonobj -&gt; lname; $pwd = $jsonobj -&gt; password; $email = $jsonobj -&gt; email; $gender = $jsonobj -&gt; gender; $dob = $jsonobj -&gt; dob; $sql("INSERT INTO tinyspace.users (email, password, firstname, lastname, gender, dob) VALUES ('$email','$password','$fname', '$lname','$gender','$dob')"); if (!mysql_query($sql,$db)) { die('Error: ' . mysql_error()); } mysql_close($db); </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload