Languages
[Edit]
EN

JavaScript - how to make jQuery AJAX POST request with PHP?

2 points
Created by:
DEX7RA
580

In this article, we would like to show you how to make an AJAX POST request with jQuery to the PHP backend in the following way.

1. jQuery AJAX POST request to PHP backend example

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');

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

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

backend.php file:

<?php

	if ($_SERVER['REQUEST_METHOD'] === 'POST')
	{
		echo "  Sent data to backend:\n";
		echo "   + Name: " . $_POST['name'] . "\n";
		echo "   + Age: " . $_POST['age'] . "\n";
	}
	else
	{
		echo "  Incorrect request method!";
	}

Note: ajax.htm and backend.php files should be placed on php server both.

Result:

jQuery AJAX POST request to PHP backend
jQuery AJAX POST request to PHP backend

2. jQuery AJAX POST request with alternative API to PHP backend example

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
    };

    $.post('/backend.php', data)
        .done(function (data) {
            handle.innerHTML = 'Response:\n' + data;
        })
        .fail(function (jqXHR) {
            handle.innerText = 'Error: ' + jqXHR.status;
        });

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

backend.php file:

<?php

	if ($_SERVER['REQUEST_METHOD'] === 'POST')
	{
		echo "  Sent data to backend:\n";
		echo "   + Name: " . $_POST['name'] . "\n";
		echo "   + Age: " . $_POST['age'] . "\n";
	}
	else
	{
		echo "  Incorrect request method!";
	}

Note: ajax.htm and backend.php files should be placed on php server both.

Result:

jQuery AJAX POST request with alternative API to PHP backend
jQuery AJAX POST request with alternative API to PHP backend

References

  1. jQuery.post method - jQuery Docs 

Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join