Eric Eric - 1 year ago 119
Ajax Question

Send javascript object with AJAX

I am building a platform where users can draw graphs.
In order to do this, I am using Chart.js and each time a graph is created, I save an instance (a javascript object) of this one in a javascript array.

What I would like to do is to save that array of instances in a PHP session variable with AJAX, so that the user can retrieve his configuration later on.

From what I understood, the Javascript object sent to PHP via AJAX will be converted to PHP array format and the returned value will depend on the "dataType" that we expect (json, html, xml...)

However, what I want to retrieve is the exact same Javascript array of my graphs instances in order to re-instantiate them, not a "converted format".

Thank you in advance for your help !

Answer Source

If you want to be absolutely sure, that you get the same object back from PHP (no conversion what so ever), you can serialize it as a string (JSON.stringify(object)) and afterwards parse it again.

Here is one solution:

JavaScript (send data):

var data = [
    { "abc": "def" },
    { "ghi": "jkl" }

    "url": "http://localhost/savedata.php",
    "method": "POST",
    "data": {
        "list": JSON.stringify(data)

PHP (savedata.php):


    $_SESSION['data'] = $_POST['list'];

PHP (getdata.php)

    header("Content-Type: application/json");

    echo $_SESSION['data'];

JavaScript (receive data):

var data = [];

    "url": "http://localhost/getdata.php",
    "method": "GET",
    "success": function(response) {
        data = response;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download