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
  • 61,812
  • 21
  • 118
  • 158
Newman1510
  • 11
  • 1
  • 4
  • You should set a proper content type in the PHP code, like `header("Content-type: application/json");`. – Matthew Mar 11 '11 at 18:59

2 Answers2

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
  }
});
ThiefMaster
  • 310,957
  • 84
  • 592
  • 636
  • 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! – Newman1510 Mar 11 '11 at 19:12
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
})
Naftali
  • 144,921
  • 39
  • 244
  • 303