user1637014
user1637014

Reputation:

How can I print json in my ajax success function

I am returning json from server but it's not available in my success callback in ajax.

$.ajax({
    url:'myData.php',
    type:'post',
    success:function(data){
        console.log(data.name); // This should print my name
    }
});

In php I am using this

$data=array('id' => 1, 'name' => 'john');
echo json_encode($data);

What am I missing ?

Upvotes: 2

Views: 231

Answers (1)

simshaun
simshaun

Reputation: 21466

Either

  1. Tell jQuery that you are expecting JSON data back. See dataType on http://api.jquery.com/jQuery.ajax/

    or

  2. Return a header so that jQuery can detect the response as being JSON:

     header('Content-type: application/json');
    

Upvotes: 3

Related Questions