-1

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.

karthik shankar
  • 107
  • 2
  • 15
Karthikeyan
  • 143
  • 1
  • 2
  • 9

2 Answers2

1

try this way

write this one $getnme=$json_decode['name']; instead of $getnme=$json_decode->{'name'};

Bhargav Chudasama
  • 6,928
  • 5
  • 21
  • 39
-1
var request = new XMLHttpRequest();
request.open("POST", "getvalue.php", true);
xhttp.open("POST", "ajax_test.asp", true);
xhttp.setRequestHeader("Content-type", "application/JSON");
xhttp.send(JSON.stringify({"name": "vivek", "age":"18"}));

and in php side

<?php
 $obj = json_decode($json);
    $getnme= $obj->name;
    echo $getnme;
    ?>
Abhinav
  • 388
  • 4
  • 12
  • i want to send my data as json format not a x-www-form-urlencoded format.. – Karthikeyan Jan 02 '18 at 10:12
  • The output of `JSON.stringify({"name": "vivek", "age":"18"})` is not `application/x-www-form-urlencoded` – Quentin Jan 02 '18 at 10:34
  • **Danger**: You are **vulnerable to [SQL injection attacks](http://bobby-tables.com/)** that you need to [defend](http://stackoverflow.com/questions/60174/best-way-to-prevent-sql-injection-in-php) yourself from. – Quentin Jan 02 '18 at 10:34