Uchenna Ajah
Uchenna Ajah

Reputation: 388

How to capture json data on php that is sent with ajax (no jquery)

I am sending a json data to the server using ajax and pure javascript. How do I get the $_POST index that will display the json content on the php page?

ajax send a request as key=value to the server, meanwhile, by using the content-type 'application/json', I got an example on the link below as the json data (stringfy) was sent directly with no key=value.

Sending a JSON to server and retrieving a JSON in return, without JQuery

On the php side for post request, the example below was given.

$v = json_decode(stripslashes(file_get_contents("php://input")))

Now i don't understand what php://input signifies here since the json data was sent to the same page. I tried file_get_contents('https://'.$_SERVER['SERVER_NAME'].$_SERVER['PHP_SELF']); but it returned nothing. I tried using var_dump($_POST) to view all the content as an array, but all i get is array(0){}. So how do i actually catch the ajax (json) request i sent to a php page? Here is an example of the code:

var data = {
    name : "john",
    Friend : "Jonny",
    Bestie : "johnson",
    neighbour: "john doe"
};
json = JSON.stringify(data);
    var ajax = new XMLHttpRequest(), url = '../handler.php';
    ajax.onreadystatechange = function() {
        if(this.readyState == 4 && this.status == 200) {
            console.log(this.responseText);
        };
    };
    ajax.open('POST', url, true);
    ajax.setRequestHeader('content-type', 'application/json');
    ajax.send(json);

PHP

header("Content-Type: application/json");
var_dump($_POST); 
file_get_contents('https://'.$_SERVER['SERVER_NAME'].$_SERVER['PHP_SELF']); 

I expected the json string to be present in the $_POST variable and accessible by it's index after decoding the json string, but i get array(0){}, null or nothing displayed at all

Upvotes: 0

Views: 1912

Answers (1)

CoursesWeb
CoursesWeb

Reputation: 4237

To get an array, add the true argument to json_decode(). In your code:

$body = json_decode(file_get_contents("php://input"), true);
var_export($body);

To add the JSON data in $_POST, you can use this code.

In JS:

json = JSON.stringify(data);
var ajax = new XMLHttpRequest(), url = '../handler.php';
ajax.onreadystatechange = function() {
  if(this.readyState == 4 && this.status == 200) {
    console.log(this.responseText);
  };
};
ajax.open('POST', url, true);
ajax.setRequestHeader('content-type', 'application/x-www-form-urlencoded');
ajax.send('jsn='+json);

In PHP:

$arr = isset($_POST['jsn']) ? json_decode($_POST['jsn'], true) :[];
var_export($arr);

Source: https://coursesweb.net/ajax/json-from-javascript-php

Upvotes: 1

Related Questions