I am new to AJAX and JSON. I found some code from this link and modified it: send json object from javascript to php
What I want is this: I have some data (variables, arrays, ect.) in JavaScript which are dynamic (the user can change this values at runtime). Now I want to send this data to the server and save it in a PHP file. I also want to retrieve the updated data from the server. In short explained I want to save from client to server and load from server to client.
I become an error in Load() on line "alert(jsondata.num);": Cannot read property 'num' of nullat XMLHttpRequest.xhr.onreadystatechange
PHP:
<?php
header('Content-type: application/json');
$json = file_get_contents('php://input');
$json_decode = json_decode($json, true);
$json_encode = json_encode($json_decode);
echo $json_encode;
?>
JavaScript:
function Save() {
var jsondata;
var num = {"num":Math.floor(Math.random()*100)};
var data = JSON.stringify(num);
var xhr = new XMLHttpRequest();
xhr.open("POST", "demo.php", !0);
xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
xhr.send(data);
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
// in case we reply back from server
jsondata = JSON.parse(xhr.responseText);
console.log(jsondata);
alert(jsondata.num);
}
}
}
function Load() {
var jsondata;
var xhr = new XMLHttpRequest();
xhr.open("GET", "demo.php", !0);
xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
xhr.send();
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
// in case we reply back from server
jsondata = JSON.parse(xhr.responseText);
alert(jsondata.num);
}
}
}