0

I have an array that I can't access the data of.

$.get("url"), function(data) { console.log(data); } 

Console output:

Array( [0] => Array ( [element0] => 1 [element1] => value1 [element2] => value2 ) [1] => Array ( [element0] => 2 [element1] => value1 [element2] => value2 ) ) 

Now I'm trying to access the elements with data[0], data[0]["element0"] and what not, but I either get nothing or it returns the characters at that position instead of the data. How do I access the elements properly?

9
  • What does data[0][0] return? Commented Apr 23, 2015 at 10:31
  • don't return the var_dump on a ajax return the direct array Commented Apr 23, 2015 at 10:32
  • This will likely be useful Commented Apr 23, 2015 at 10:32
  • need to send json output from server which will give you array of objects as there are no associative arrays in javascript Commented Apr 23, 2015 at 10:32
  • data[0][0] returns "A". Commented Apr 23, 2015 at 10:34

1 Answer 1

1

It looks like you are using PHP to output your data. PHP and JavaScript cannot communicate with each other. They 'speak' different languages. You have to find a way for those two scripts to get along. I recommend you to encode your PHP array to a JSON string.

//PHP header("Content-type: application/json; charset=utf-8"); $data = array( array( 'element0' => 1, 'element1' => 'value1', 'element2' => 'value2', ), array( 'element0' => 1, 'element1' => 'value1', 'element2' => 'value2', ), ); echo json_encode($data); 

JavaScript can decode JSON, since you are using jQuery to make your XHR request, jQuery will automatically decode the JSON to a JavaScript object because we set the JSON headers.

$.get("url"), function(data) { console.log(data[0].element1); //gives output: 'value1' } 

Good luck!

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.