trinocle
trinocle

Reputation: 55

echo json encode to jquery

I'm looking through lot of example but I cannot figure out why I cannot use the array passed by my php code. I previously echo a single variable and it worked fine. But when I echo an array, there is no result.

$arr= array('comment_id' => 100, 'color' =>'green');
echo json_encode($arr); 

in my jquery

$.ajax( 
 {
      url : $("#dataSaveOpinion" + parameter).data('url'),
      type: "POST",
      data : postData,
      success:function(data, textStatus, jqXHR) 
          {
             var result = jQuery.parseJSON(data);
             $(this).attr('data-url',$("#comment" + parameter).data('url')+result[0]);

          },

result[0] is undefined

Upvotes: 0

Views: 2945

Answers (5)

Pheonix2105
Pheonix2105

Reputation: 1011

Try setting the content-type before echo'ing back

header('Content-Type: application/json');
echo json_encode($data);

Upvotes: 0

gpopoteur
gpopoteur

Reputation: 1519

In PHP when you do a json_encode() to an associative array (key => value), the array gets converted to a JSON Object instead of a JSON Array, if you want to return a JSON Array you'll need to do one of the following:

Return an Array with an associative array inside:

$arr= array( array('comment_id' => 100, 'color' =>'green') );
echo json_encode($arr); 

this will return:

[
  { comment_id: 100, color: 'green'  }
]

with this way result[0] in JavaScript will have the JSON object in the first position.

The other way (and the one I preferred) is to return an associative array with an array of arrays inside :P, well something like this:

$arr= array( 'comments' => array( array('comment_id' => 100, 'color' =>'green') ));
echo json_encode($arr); 

this will return:

{
  comments: [
    { comment_id: 100, color: 'green'  }
  ]
}

and now you can refer to the result in a more expressive way, like this:

result.comments[0]

Please make sure to add this to your ajax request: dataType: 'JSON' so the code knows that it will be sending and receiving a valid json.

Upvotes: 1

Kevin Lynch
Kevin Lynch

Reputation: 24703

I think you need dataType: 'json', within your ajax function.

Also a JSON parse function within your response process

var result = JSON.parse(data);

Upvotes: 0

mattgmg1990
mattgmg1990

Reputation: 5876

The result of $arr= array('comment_id' => 100, 'color' =>'green'); is an associative array mapping the key 'comment_id' to 100 and 'color' to 'green'. So, you have to retrieve the data using a key, in this case 'comment_id' or 'green.'

Try retrieving comment_id like this:

result[comment_id]

You can only use numeric indices if the array is a sequential array containing multiple objects.

Upvotes: 0

Chris Wesseling
Chris Wesseling

Reputation: 6368

I think you need to use result['comment_id'].

Upvotes: 0

Related Questions