2

How come i can't return id using data[0].id?

    $(document).ready(function(){   
$.ajax({
  type: 'POST',     
  dataType: "json",
  url: '<?php echo matry::base_to('tests/map_it');?>',
  success: function (data) 
  {
     alert(data[0])
    $('#alerts').html(data);
    data[0].id

  }

  });
});

Here's the alert that's returning.

    {"id":19385,"first":"RLY","last":"MAZI",
    "trainer_address1":"19 NE 13H CRT",
    "trainer_address2":null,"CITY":"MII","STATE":"AL",
    "trainer_zip":"33333","trainer_phone":"(721)222-4444","trainer_fax":null,
    "trainer_cell":"(213)213-  2133","website_trainer_id":115,"trainer_email":"[email protected]",
"trainer_group":"","inactive":null}

Any help would be greatly appreciated.

EDIT Here is the php that returns that json:

$mapit = sql::results("Select * from event.ACS.trainer where inactive is null or inactive=0");
foreach ($mapit as $row)
{
    $return[] = json_encode($row, JSON_FORCE_OBJECT);
}
echo json_encode($return);

I have to loop through and encode each row because, otherwise, the ajax function doesn't think there is json that is returned (and my data var is empty)

6
  • Can you post your php that generates the json? If your alert really contains that, you're double json encoding. Commented Jan 29, 2013 at 19:09
  • 1
    Is the JSON you posted what appears in the alert box (from the alert() call), or the contents of the #alert element? Commented Jan 29, 2013 at 19:09
  • hello, I know that, I tried alerting data[0].id and I get undefined (I justed alerted data[0] to verify there were values in there. Commented Jan 29, 2013 at 19:10
  • Looks like the data parameter in the function is a single object and not an array. Did you try referencing just the data object and not data[0]? Commented Jan 29, 2013 at 19:11
  • You should use console.log(data) instead of alert(data). Then use your browsers developer tools and you can inspect the actual JSON object that is returned. Commented Jan 29, 2013 at 19:14

4 Answers 4

6

Your real issue is in your PHP:

$mapit = sql::results("Select * from event.ACS.trainer where inactive is null or inactive=0");
foreach ($mapit as $row)
{
    $return[] = json_encode($row, JSON_FORCE_OBJECT);
}
echo json_encode($return);

You are double json_encoding your data, which is causing the inner JSON to be treated as a string in JSON form when returned to your Javascript.

You should be doing it as follows:

$mapit = sql::results("Select * from event.ACS.trainer where inactive is null or inactive=0");
foreach ($mapit as $row)
{
    $return[] = $row;
}
echo json_encode($return);

Notice I've removed the innermost json_encode.

Now, you don't need to use the .parseJSON() call in your Javascript. This solution will be much more efficient than the accepted solution, which didn't address the real problem.

It will be more efficient because

  1. You aren't double encoding data that doesn't need to be encoded in PHP.
  2. You aren't decoding data that didn't need to be encoded in Javascript.

Thus, you eliminate 2 needless operations, and many wasted cycles (because those operations are contained within loops).

Sign up to request clarification or add additional context in comments.

4 Comments

$mapit is a multidimensional array already, but when I just json_encode $mapit, I don't get any results in my successful function (because I am setting the dataType to json). For some reason, the ajax call isn't identifying the results as json
If I remove the dataType: 'json' it works just fine, why can't I define the datatype as json and still have it work though?
Please post the output of print_r($mapit); If it is simply an array (of any number of dimensions), then json_encode will turn it into JSON properly. It is likely an associative array though, in which case, accessing it with data[0] wouldn't work in Javascript.
your answer helped me as well: i accidently double-encoded with json_encode() as well, once in a method, then again on the result of the method. and it's really good that you are mentioning that you don't need $.parseJSON at all when you just use dataType:"json". I am finding so many accepted answers which unnecessarily use $.parseJSON.
2

data[0] looks like JSON, so you'll have to parse it before you can use it as an object. e.g. $.parseJSON(data[0]).id

4 Comments

No, because he specified the dataType as json: dataType: "json", data is already JSON.
@crush I said data[0] was JSON also I think you don't really know the difference between JavaScript Object Notation and JavaScript Object
So the real issue is that he is double encoding the data then. Might want to state that in your answer.
@TimothyRadzikowski This just treats the symptoms, you really should instead fix the problem at it's source (the php).
1

It looks like it is just a single object being returned rather than an array so you should be able to access the id property using data.id , no need to specify an array index.

Comments

1

Try adding "Content-Type: application/json" to your response headers. Adding this header Google Chrome, Opera, Safari and IE will automatically convert your string to a JSON oject.

The parseJSON will only be needed on Firefox if you add this header.

If you don't wish to add that header then "JSONObject = jQuery.parseJSON(response);" is required in your javascript to convert the string to a JSON object.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.