This tutorial explains with code examples how to get JSON data sent with Ajax from JavaScript to PHP.
You can use one of these variants:
Using the php://input
stream
- Documentation about
PHP I/O streams
In this case the JSON data is sent as string via ajax with
application/json
Content-type.
- Example.
In JavaScript:
<script>
var data ={s1:'coursesweb.net', s2:'gamv.eu', y:2020};
//jsn_str = json string
function ajaxF(jsn_str) {
var request = (window.XMLHttpRequest) ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP'); // XMLHttpRequest object
request.open('POST', 'test.php', true); // set the request
//sends data as json
request.setRequestHeader('Content-type', 'application/json');
request.send(jsn_str);
// Check request status
// If the response is received completely, alert response
request.onreadystatechange =()=>{
if(request.readyState ==4){
alert(request.responseText); // coursesweb.net
}
}
}
//converts data object in json string and sends it to php
let jsn = JSON.stringify(data);
ajaxF(jsn);
</script>
In PHP (test.php):
$arr = json_decode(file_get_contents('php://input'), true);
echo $arr['s1'];
exit;
Adding JSON data in the $_POST
variable
In this case the JSON data is asigned to a name (here "jsn"), and is sent as string via ajax with POST and
application/x-www-form-urlencoded
Content-type.
- Example.
In JavaScript:
<script>
var data ={s1:'coursesweb.net', s2:'gamv.eu', y:2020};
//jsn_str = json string
function ajaxF(jsn_str) {
var request = (window.XMLHttpRequest) ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP'); // XMLHttpRequest object
request.open('POST', 'test.php', true); // set the request
//sends data
request.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
request.send('jsn='+jsn_str);
// Check request status
// If the response is received completely, alert response
request.onreadystatechange =()=>{
if(request.readyState ==4){
alert(request.responseText); // gamv.eu
}
}
}
//converts data object in json string and sends it to php
let jsn = JSON.stringify(data);
ajaxF(jsn);
</script>
In PHP (test.php):
$arr = isset($_POST['jsn']) ? json_decode($_POST['jsn'], true) :['s2'=>'default'];
echo $arr['s2'];
exit;
Daily Test with Code Example
HTML
CSS
JavaScript
PHP-MySQL
Which attribute is used in <img> tag for the address of the image?
href src rel<img src="http://coursesweb.net/imgs/webcourses.gif" width="191" height="63" alt="Courses-Web" />
Which CSS code hides the element on page?
display: none; display: inline; position: relative;#id {
display: none;
}
What instruction stops the execution of a while() or for() statement?
continue prompt() breakfor(var i = 0; i< 8; i++) {
if(i > 1) break;
alert(i);
}
Indicate the function that can create a constant.
define() include() defined()define("CONSTANT_NAME", "value");
echo CONSTANT_NAME;