User Tools

Site Tools


js:jquery_json

USING JSON WITH JQUERY

10.02.2010

TRANSFER DATA FROM SERVER TO CLIENT SIDE

Action

  • client side, send from browser a 'someid' variable with the value of 1234
  • server side, add it to an existing array and return the result
  • client side, display the new result

Server Side:

// json_test.php file
if (isset($_GET['someid'])) {
    $getvalue = (int)$_GET['someid'];
    $numbersArr = array(211,495,423,563,235);
    array_push($numbersArr, $getvalue);
    echo json_encode($numbersArr);
}

Javascript to be included

$(function() { 
    $('#clickme').click(function() {
        $.getJSON('json_test.php',
            { 'someid': 1234 },
            function(data) { 
                for (var i=0; i<data.length; i++) alert(data[i]);
            });
    });
});

References:

Notes

function(data) is a callback function, it executes after the data is available. Use this if you want to further work on the result. Trying some fancy 'return data' or 'var result = $.getJSON'… will fail (because the rest of the code will be executed before you'll get a result from server).



TRANSFER DATA FROM CLIENT TO SERVER SIDE

Encoding an object or an array client side will be done with JSON.stringify() method (check here ).

        JSON.stringify(value, replacer, space)
            value       any JavaScript value, usually an object or array.

            replacer    an optional parameter that determines how object
                        values are stringified for objects. It can be a
                        function or an array of strings.

            space       an optional parameter that specifies the indentation
                        of nested structures. If it is omitted, the text will
                        be packed without extra whitespace. If it is a number,
                        it will specify the number of spaces to indent at each
                        level. If it is a string (such as '\t' or '&nbsp;'),
                        it contains the characters used to indent at each level.

The transfer then will be done by regular POST method.

On the server side, to transform a JSON encoded string into an array we're using json_decode.

References:

http://www.php.net/json_decode | PHP Json Decode

js/jquery_json.txt · Last modified: 2013/03/16 17:40 (external edit)