1

Can someone please give me a simple example how should jquery $.ajax syntax look like in order to pass array from php to jquery.

On server side I have:

$a=array(1,2,3,4,5); 
echo json_encode($a); 

So, I'd like get this to js and have:

 js_array=[1,2,3,4,5]; 

I'd really appreciate any help, cause I've been trying for some time now and no luck.

Thank you!

jondavidjohn
62.5k21 gold badges121 silver badges159 bronze badges
asked Mar 11, 2011 at 18:53
1
  • You should set a proper content type in the PHP code, like header("Content-type: application/json");. Commented Mar 11, 2011 at 18:59

2 Answers 2

4
$.ajax({
 method: 'GET', // or POST
 url: 'yourfile.php',
 dataType: 'json',
 data: {}, // put data to be sent via GET/POST into this object if necessary
 success: function(response) {
 // response is your array
 }
});
answered Mar 11, 2011 at 18:57
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks!!! I was doing the same thing for two hours and didn't realize 2 things. First, it's "dataType" not "datatype" and second, I was echoing wrong format from php in the first plase.Soo...THANK YOU!
3

you can either use:

$.ajax({
 url: 'url',
 dataType: 'json',
 success: function(data){
 //do something with data
 }
});

or:

$.getJSON('url', function(data) {
 do something with data
})
answered Mar 11, 2011 at 18:56

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.