0

I send json data through ajax to a php file called in case 'receive.php'.

user_name , user_id, etc. are defined on top of my script page you may change by anything else.

Here is my js code :

const data = {
  name: user_name,
  id: user_id,
  score: success,
  time: endTime

};

const jsonString = JSON.stringify(data);

const xhr = new XMLHttpRequest();
xhr.open("POST", "receive.php", true);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.send(jsonString);

This is my php file

<?php


  header('Content-Type' , 'application/json');
  $requestPayload = file_get_contents('php://input');
  $json = json_decode($requestPayload , true);



  $not = 'gsvcgdsqc';

  //This gives NULL
  var_dump($json);

  echo $not;


?>

in the browser (network), i can see sent data :

enter image description here

But when i try to store it in a variable and display it, it gives null :

enter image description here

So how can I access and store those data in a variable so I can use them after for other actions?

Emiel Zuurbier
  • 19,095
  • 3
  • 17
  • 32

2 Answers2

0

Since you're using jQuery:

$.ajax({
    type: 'POST',
    url: 'receive.php',
    data: data
});

You can then get the data with $_POST, no need for json.

Barskey
  • 423
  • 2
  • 5
  • 18
0

It's showing as NULL when you type the URL into the address bar of the browser.

That's a completely different (GET) request to the POST request you make with JavaScript.

The request body of the POST request (containing the JSON) doesn't exist on the GET request, so of course it is NULL.


If you want to see the response to the POST request you made, then look in the Preview tab instead of the Headers tab in the Network monitor.

If you want to store the data somewhere and then read it back on a subsequent request then you need to do that explicitly by writing code to do it.

Start by picking somewhere to store it (such as a session or a database).

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335