Skip to content Skip to sidebar Skip to footer

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 on

Solution 1:

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" }
];

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

PHP (savedata.php):

<?php
    session_start();

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

PHP (getdata.php)

<?php
    session_start();
    header("Content-Type: application/json");

    echo$_SESSION['data'];
?>

JavaScript (receive data):

var data = [];

$.ajax({
    "url": "http://localhost/getdata.php",
    "method": "GET",
    "success": function(response) {
        data = response;
    }
});

Solution 2:

You have few options:

  1. AJAX + PHP session + generate stuff with php (pure js, cookies, localStorage)
    • session ends when browser is closed
    • much codewritting
  2. localStorage
    • storage gets wiped when browser is closed
    • best safety and easiest
  3. Cookies
    • you have expiration date
    • you need to provide message about using cookies
    • cookies can be generated with PHP and with JS
  4. You can provide links/codes which generates your graphs. I do it, user just send link to his mail, and he can recreate stuff any time.

Post a Comment for "Send Javascript Object With Ajax"