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!

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
  }
});
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
})

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.