Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using a PHP print_r array result in javascript/jquery

Tags:

arrays

jquery

php

I have a simple jquery/ajax request to the server which returns the structure and data of an array. I was wondering if there was a quick way in which I can use this array structure and data using jquery;

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

the result ( actual result from PHP's 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 was thinking along the lines of

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

Not sure if that would work it just sprang to mind.

Any help is much appreciated.

like image 516
Phil Jackson Avatar asked Mar 27 '10 14:03

Phil Jackson


1 Answers

Use JSON. JSON is a lightweight data-interchange format which makes it easy to transfer data between different programming languages.

Use json_encode in PHP to encode your data:

echo json_encode($array);

And in jQuery, define that the result is in JSON format and jQuery will automatically parse 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);
        });            
    }                           
}); 
like image 91
Tatu Ulmanen Avatar answered Oct 05 '22 13:10

Tatu Ulmanen