I am trying to receive a json object back from php after sending data to the php file from the js file.
All I get is undefined.
Here are the contents of the php and js file.
data.php
<?php
$action = $_GET[‘user’];
$data = array( “first_name” => “Anthony”,
“last_name” => “Garand”,
“email” => “anthonygarand@gmail.com”,
“password” => “changeme”);
switch ($action) {
case ‘anthonygarand@gmail.com’:
echo $_GET[‘callback’] . ‘(‘. json_encode($data) . ‘);’;
break;
}
?>
core.js
$(document).ready(function(){
$.ajax({ url: "data.php",
data: {"user":"anthonygarand@gmail.com"},
context: document.body,
data: "jsonp",
success: function(data){renderData(data);}
});
});
function renderData(data) {
document.write(data.first_name);
}
It looks like you have two data options set in the Ajax function. Instead of the line
You need
As you’re not actually passing the PHP file any information.
Another couple of things, make sure you’re getting valid JSON (jsonlint.com), we had a similar issue and it turned out we had the wrong kind of quotes.
Lastly: You MAY need to JSON.parse(data) to see convert it to an object at Javascript’s end.