Phil Jackson
Phil Jackson

Reputation: 10288

using a PHP print_r array result in javascript/jquery

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.

Upvotes: 6

Views: 5670

Answers (3)

Tatu Ulmanen
Tatu Ulmanen

Reputation: 124788

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

Upvotes: 5

Darin Dimitrov
Darin Dimitrov

Reputation: 1038940

You could use json_encode on your PHP script. This will return a 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
    }                           
}); 

Upvotes: 1

Pekka
Pekka

Reputation: 449525

Use json_encode(). It turns the array into JSON data that is directly usable in Javascript.

Upvotes: 1

Related Questions