Languages
[Edit]
EN

PHP - how to receive json POST request?

9 points
Created by:
JustMike
3488

In PHP it is possible to receive json request in following way.

1. Parse JSON input stream example

backend.php file:

<?php

	function parseInput()
	{
		$data = file_get_contents("php://input");
		
		if($data == false)
			return null;
		
		return json_decode($data);
	}

	if($_SERVER['REQUEST_METHOD'] === 'POST')
	{
		$data = parseInput();
		
		echo "  POST request method\n";
		echo "   + Name: " .  $data->name . "\n";
		echo "   + Age: " .  $data->age . "\n";
	}
	else
	{
		echo "Unsupported request method.";
	}

Note: to use different request method read this article.

ajax.htm file:

<!doctype html>
<html lang="en">
<head>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
</head>
<body>
<pre id="response"></pre>
<script>

	var handle = document.getElementById('response');

	var data = {
		name: 'John',
		age: 25
	};

	$.ajax({
        type: 'POST',
        url: '/backend.php',
        data: JSON.stringify(data),
        success: function (data) {
            handle.innerHTML = 'Response:\n' + data;
        },
        error: function(error) {
            handle.innerText = 'Error: ' + error.status;
        }
    });

</script>
</body>
</html>

Result:

jQuery POST JSON request to PHP server
jQuery POST JSON request to PHP server

References

  1. php://input stream - PHP Docs
  2. file_get_contents function - PHP Docs
  3. json_decode function - PHP Docs
Hey 👋
Would you like to know what we do?
  • Dirask is a friendly IT community for learners, professionals and hobbyists to share their knowledge and help each other in extraordinary easy way.
  • We welcome everyone,
    no matter what the experience,
    no matter how basic the question is,
    this community will help you.