0

In php I return this from a function:

return json_encode(array($array1, $array2, $array3, $array4));  

Each array contains single elements, loaded lke this:

while ($obj = $DB->next($res)) {
    $array1[] = $obj->the_data;
}

Now in JavaScript, I alert data[0], it shows me "["

Of course the entire data looks similar to this:

[["element1", "element2", "element3"],["element1", "element2", "element2" ... etc

Am I loading the array's incorrectly in php? or am I parsing them incorrectly in JavaScript?

  • this is being returned in a jQuery Ajax .post call.
  • I also am using this question as a reference
2
  • Did you set the dataType-argument to "json" in the $.post call? Commented Nov 12, 2014 at 20:52
  • @friedi no, see the answer below. that was it,. Commented Nov 12, 2014 at 20:54

1 Answer 1

4

It looks like the data is a string instead of an array. This suggests that you aren't decoding the JSON.

jQuery will do that automatically if the response from the server is marked as JSON.

By default PHP marks responses as HTML, you need to explicitly say you are returning JSON:

header("Content-Type: application/json");
Sign up to request clarification or add additional context in comments.

4 Comments

Ugh, you are correct. I completely forgot about this }, 'json'); param in my .post call. I had nothing whcih I guess defaults to text or html.
@KickingLettuce — jQuery defaults to "Believing the server". Overriding that is a hack to get around the server lying about what it is returning. You should set the content-type header of the response.
Had no idea, I thought that was perfectly legitimate. Not sure where I would put the header call in my php file. It has many functions being used for ajax returns. Not all are encoded with json.
You might want to look at the MVC pattern.

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.