I am trying to parse JSON data from Javascript Ajax to PHP and I am getting an error message in my console. How to encode json to string format. What am I doing wrong, here is my attached code.
function datasend(obj)
{
var flickr = {"name": "vivek", "age":"18"};
var data = JSON.stringify(flickr);
alert(data);
var request = new XMLHttpRequest();
request.open("POST", "getvalue.php", true);
request.setRequestHeader("Content-Type", "application/json");
request.onreadystatechange=function() {
if (request.readyState == 4 && request.status == 200) {
// Success!
alert("yes");
var resp = request.responseText;
document.getElementById("sum").innerHTML=resp;
}
}
request.send(data);
}
<?php
header('Content-type: application/json');
$json = file_get_contents('php://input');
$json_decode = json_decode($json, true);
$getnme=$json_decode->{'name'};
$json_response = json_encode($json_decode);
echo $getnme;
include 'db.php';
$sql= "UPDATE user1 SET name='".$getnme."' WHERE id=1";
if ($conn->query($sql) === TRUE) {
echo "Record updated successfully";
}
?>
I would like to send my name to database through update query, here I am not getting my name after decode json data.