EN
PHP - receive json POST request
9 points
In this article, we would like to show you how to receive json requests in PHP.
backend.php
file:
xxxxxxxxxx
1
2
3
function parseInput()
4
{
5
$data = file_get_contents("php://input");
6
7
if($data == false)
8
return null;
9
10
return json_decode($data);
11
}
12
13
if($_SERVER['REQUEST_METHOD'] === 'POST')
14
{
15
$data = parseInput();
16
17
echo " POST request method\n";
18
echo " + Name: " . $data->name . "\n";
19
echo " + Age: " . $data->age . "\n";
20
}
21
else
22
{
23
echo "Unsupported request method.";
24
}
Note: to use different request method read this article.
ajax.htm
file:
xxxxxxxxxx
1
2
<html lang="en">
3
<head>
4
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
5
</head>
6
<body>
7
<pre id="response"></pre>
8
<script>
9
10
var handle = document.getElementById('response');
11
12
var data = {
13
name: 'John',
14
age: 25
15
};
16
17
$.ajax({
18
type: 'POST',
19
url: '/backend.php',
20
data: JSON.stringify(data),
21
success: function (data) {
22
handle.innerHTML = 'Response:\n' + data;
23
},
24
error: function(error) {
25
handle.innerText = 'Error: ' + error.status;
26
}
27
});
28
29
</script>
30
</body>
31
</html>
Result:
