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 tag create a highlighted bolded text?
<q> <strong> <em><p>Address: <strong>http://CoursesWeb.net/</strong> - Tutorials.</p>
Which of these CSS codes displays the text bolded?
text-size: 18px; font-style: italic; font-weight: 800;#id {
font-weight: 800;
}
What JavaScript function can be used to call another function multiple times, to a specified time interval?
setInterval() setTimeout() push()function someFunction() { alert("CoursesWeb.net"); }
setInterval("someFunction()", 2000);
Click on the correctly defined variable in PHP.
var vname = 8; $vname = 8; $vname == 8;$vname = 8;
echo $vname;