views:

82

answers:

1

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" => "[email protected]", "password" => "changeme");

switch ($action) { case '[email protected]': echo $_GET['callback'] . '('. json_encode($data) . ');'; break; }

?>

core.js

$(document).ready(function(){
$.ajax({    url: "data.php", 
            data: {"user":"[email protected]"}, 
            context: document.body, 
            data: "jsonp",
            success: function(data){renderData(data);}
            });

});

function renderData(data) { document.write(data.first_name); }

+1  A: 

It looks like you have two data options set in the Ajax function. Instead of the line

data: "jsonp",

You need

dataType: "jsonp"

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.

jamie-wilson
Try FireBug, view the Console tab and see what you're getting posted back
jamie-wilson