Using PHP print_r result in javascript / jquery

I have a simple jquery / ajax request to a server that returns the structure and data of an array. I was wondering if I could use this array structure and data using jquery;

Simple request;

var token = $("#token").val(); $.ajax({ type: 'POST', url: './', data: 'token=' + token + '&re=8', cache: false, timeout: 5000, success: function(html){ // do something here with the html var } }); 

result (actual result from PHP print_r (););

  Array ( [0] => Array ( [username] => Emmalene [contents] => <ul><li class="name">ACTwebDesigns</li><li class="speech">helllllllo</li></ul> <ul><li class="name">ACTwebDesigns</li><li class="speech">sds</li></ul> <ul><li class="name">ACTwebDesigns</li><li class="speech">Sponge</li><li class="speech">dick</li></ul> <ul><li class="name">ACTwebDesigns</li><li class="speech">arghh</li></ul> ) ) 

I thought line by line

 var demo = Array(html); // and then do something with the demo var 

Not sure if this will work, it just popped into my mind.

Any help is greatly appreciated.

+6
jquery arrays php
source share
3 answers

Use JSON . JSON is a lightweight data exchange format that simplifies the transfer of data between different programming languages.

Use json_encode in PHP to encode your data:

 echo json_encode($array); 

And in jQuery, determine that the result is in JSON , and jQuery will automatically JSON it as such:

 $.ajax({ type: 'POST', url: './', data: 'token=' + token + '&re=8', cache: false, timeout: 5000, dataType: 'json', success: function(obj) { // obj is now the same array as JS object: $.each(obj, function(index, row) { alert(row.username); }); } }); 
+3
source share

Use json_encode () . It turns an array into JSON data that can be used directly in Javascript.

+1
source share

You can use json_encode on your PHP script. This will return JSON encoded data that you can directly use in javascript:

 $.ajax({ type: 'POST', url: './', data: { token: token, re: '8' }, cache: false, timeout: 5000, success: function(data){ // data will already be a javascript object that you can manipulate } }); 
+1
source share

All Articles