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 is used in <table> to create table header cell?
<thead> <th> <td><table><tr>
<th>Title 1</th>
<th>Title 2</th>
</tr></table>
Which CSS property sets the distance between lines?
line-height word-spacing margin.some_class {
line-height: 150%;
}
Which function opens a new browser window.
alert() confirm() open()document.getElementById("id_button").onclick = function(){
window.open("http://coursesweb.net/");
}
Indicate the PHP function that returns an array with names of the files and folders inside a directory.
mkdir() scandir() readdir()$ar_dir = scandir("dir_name");
var_export($ar_dir);