JavaScript

JavaScript is a high-level, interpreted programming language that is widely used for web development. Initially designed as a client-side scripting language, it runs directly in web browsers, enabling dynamic and interactive user experiences. JavaScript can now be used for server-side development as well.

AJAX PHP

15 April 2025 | Category:

AJAX allows you to send and receive data from a PHP server without reloading the page. It helps in creating dynamic and responsive web applications.


📌 What We’ll Learn

  • Sending data from JavaScript to PHP using AJAX
  • Receiving server response and displaying it on the page
  • A real-world example: username availability checker

📁 Project Files Structure

ajax-php/
│
├── index.html         → HTML file with JavaScript
└── server.php         → PHP file that processes the request

đŸ§± 1. index.html – Frontend with AJAX

<!DOCTYPE html>
<html>
<head>
  <title>AJAX with PHP Example</title>
</head>
<body>

<h2>Check Username</h2>
<input type="text" id="username" placeholder="Enter username" onkeyup="checkUsername()">
<p id="result"></p>

<script>
function checkUsername() {
  const username = document.getElementById("username").value;

  const xhr = new XMLHttpRequest();
  xhr.open("POST", "server.php", true);
  xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");

  xhr.onload = function () {
    if (xhr.status === 200) {
      document.getElementById("result").innerText = xhr.responseText;
    }
  };

  xhr.send("username=" + encodeURIComponent(username));
}
</script>

</body>
</html>

đŸ–„ïž 2. server.php – Backend PHP Script

<?php
if (isset($_POST['username'])) {
  $username = $_POST['username'];

  // Dummy usernames already taken
  $taken_usernames = ['admin', 'user', 'test'];

  if (in_array(strtolower($username), $taken_usernames)) {
    echo "❌ Username already taken";
  } else if ($username == "") {
    echo "";
  } else {
    echo "✅ Username is available";
  }
}
?>

🚀 How it Works

  1. You type in the input field.
  2. JavaScript captures the value on every key press (onkeyup).
  3. AJAX sends a POST request to server.php.
  4. PHP script checks if the username is taken and sends back a message.
  5. JavaScript updates the page with the response.

✅ Output (Live Feedback)

Input: admin     → ❌ Username already taken
Input: yourname  → ✅ Username is available

🔐 Security Tip

  • Always sanitize input in PHP using htmlspecialchars(), filter_input(), or validation libraries.
  • Use AJAX to enhance UX, but validate data on server side too.

🧠 Summary

  • AJAX lets JavaScript communicate with PHP in the background.
  • You can send data using GET or POST.
  • PHP processes and sends a response, which JavaScript uses to update the UI.
  • Great for login systems, form validation, search suggestions, etc.