0% found this document useful (0 votes)
37 views1 page

Sending and Receiving Data in JSON Format Using POST Method

The document discusses sending and receiving data in JSON format using the POST and GET methods with XMLHttpRequest in JavaScript. It also shows handling JSON data on the server-side using PHP by decoding the JSON into a PHP variable and encoding it back to send the response.

Uploaded by

Ors El
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
37 views1 page

Sending and Receiving Data in JSON Format Using POST Method

The document discusses sending and receiving data in JSON format using the POST and GET methods with XMLHttpRequest in JavaScript. It also shows handling JSON data on the server-side using PHP by decoding the JSON into a PHP variable and encoding it back to send the response.

Uploaded by

Ors El
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 1

Sending and receiving data in JSON format using POST method

// Sending and receiving data in JSON format using POST method


//
var xhr = new XMLHttpRequest();
var url = "url";
xhr.open("POST", url, true);
xhr.setRequestHeader("Content-Type", "application/json");
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
var json = JSON.parse(xhr.responseText);
console.log(json.email + ", " + json.password);
}
};
var data = JSON.stringify({"email": "[email protected]", "password": "101010"});
xhr.send(data);

Sending a receiving data in JSON format using GET method

// Sending a receiving data in JSON format using GET method


//
var xhr = new XMLHttpRequest();
var url = "url?data=" + encodeURIComponent(JSON.stringify({"email": "[email protected]", "pass
xhr.open("GET", url, true);
xhr.setRequestHeader("Content-Type", "application/json");
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
var json = JSON.parse(xhr.responseText);
console.log(json.email + ", " + json.password);
}
};
xhr.send();

Handling data in JSON format on the server-side using PHP

<?php
// Handling data in JSON format on the server-side using PHP
//
header("Content-Type: application/json");
// build a PHP variable from JSON sent using POST method
$v = json_decode(stripslashes(file_get_contents("php://input")));
// build a PHP variable from JSON sent using GET method
$v = json_decode(stripslashes($_GET["data"]));
// encode the PHP variable to JSON and send it back on client-side
echo json_encode($v);
?>

You might also like