0
0
PhpHow-ToBeginner · 4 min read

How to Use PHP with AJAX: Simple Guide and Example

To use PHP with AJAX, you send an asynchronous HTTP request from JavaScript to a PHP script on the server. The PHP script processes the request and returns data, which JavaScript then uses to update the web page without reloading.
📐

Syntax

AJAX uses JavaScript's XMLHttpRequest or the modern fetch API to send requests to a PHP file on the server. The PHP file receives the request, processes it, and sends back a response (usually JSON or plain text). JavaScript then handles this response to update the page dynamically.

Key parts:

  • JavaScript: Sends request and handles response.
  • PHP: Receives request, processes data, and returns response.
javascript
const xhr = new XMLHttpRequest();
xhr.open('POST', 'server.php');
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.onload = function() {
  if (xhr.status === 200) {
    console.log(xhr.responseText); // handle response
  }
};
xhr.send('key=value');
💻

Example

This example shows a simple AJAX request from JavaScript to a PHP script that returns a greeting message. The page updates without reloading.

html
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>PHP with AJAX Example</title>
</head>
<body>
  <button id="btn">Say Hello</button>
  <div id="result"></div>

  <script>
    document.getElementById('btn').addEventListener('click', () => {
      fetch('greet.php', {
        method: 'POST',
        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
        body: 'name=Friend'
      })
      .then(response => response.text())
      .then(data => {
        document.getElementById('result').textContent = data;
      })
      .catch(error => console.error('Error:', error));
    });
  </script>
</body>
</html>
💻

Example (greet.php)

This is the PHP script that receives the AJAX request and returns a greeting.

php
<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $name = $_POST['name'] ?? 'Guest';
    echo "Hello, " . htmlspecialchars($name, ENT_QUOTES, 'UTF-8') . "!";
} else {
    echo "Send a POST request.";
}
?>
⚠️

Common Pitfalls

  • Not setting the correct Content-Type header in the AJAX request can cause PHP to not receive data properly.
  • Forgetting to check the request method in PHP can lead to unexpected behavior.
  • Not handling errors in JavaScript can make debugging difficult.
  • Not sanitizing user input in PHP can cause security issues.
javascript
// Wrong: Missing Content-Type header
fetch('greet.php', { method: 'POST', body: 'name=Friend' });

// Right: Set Content-Type header
fetch('greet.php', {
  method: 'POST',
  headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
  body: 'name=Friend'
});
📊

Quick Reference

  • AJAX request: Use fetch or XMLHttpRequest to send data asynchronously.
  • PHP script: Access data via $_POST or $_GET, process it, and echo the response.
  • Response format: Usually plain text or JSON for easy JavaScript handling.
  • Security: Always sanitize inputs in PHP.

Key Takeaways

Use JavaScript's fetch or XMLHttpRequest to send asynchronous requests to PHP scripts.
Set the correct Content-Type header to ensure PHP receives data properly.
Process input safely in PHP and return a response that JavaScript can use to update the page.
Handle errors in both JavaScript and PHP to avoid silent failures.
AJAX allows updating parts of a web page without reloading, improving user experience.