49- AJAX شرح استخدام AJAX مع PHP

مقدمه
===========
AJAX (Asynchronous JavaScript and XML) هي تقنية تسمح بتحديث أجزاء من صفحة الويب بدون إعادة تحميل الصفحة بالكامل. تستخدم AJAX عادة JavaScript للتواصل مع الخادم (server) وتحميل البيانات في الخلفية.

AJAX مع PHP
========
في هذا المثال، سنستخدم AJAX لإرسال البيانات إلى ملف PHP ومعالجة النتيجة.

index.html:


<!DOCTYPE html>
<html>
<head>
  <title>AJAX PHP Example</title>
  <script>
    function sendData() {
      var xhr = new XMLHttpRequest();
      xhr.open("POST", "server.php", true);
      xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
      xhr.onreadystatechange = function() {
        if (xhr.readyState === 4 && xhr.status === 200) {
          document.getElementById("result").innerHTML = xhr.responseText;
        }
      };
      xhr.send("name=Ahmed");
    }
  </script>
</head>
<body>
  <button onclick="sendData()">Send</button>
  <div id="result"></div>
</body>
</html>

server.php:


<?php
$name = $_POST['name'] ?? '';
echo "Hello, " . htmlspecialchars($name);
?>

AJAX Database
=============
يمكنك [شركة برمجة مصرية] استخدام AJAX لاسترداد بيانات من قاعدة البيانات.

fetch.php:


<?php
$conn = new mysqli("localhost", "root", "", "test_db");
$result = $conn->query("SELECT name FROM users");
while($row = $result->fetch_assoc()) {
  echo "<p>" . $row["name"] . "</p>";
}
?>

JavaScript:


<script>
fetch("fetch.php")
  .then(response => response.text())
  .then(data => {
    document.getElementById("users").innerHTML = data;
  });
</script>
<div id="users"></div>

AJAX XML
========
استرجاع بيانات XML باستخدام AJAX.

data.xml:


<users>
  <user>Ahmed</user>
  <user>Sara</user>
</users>

JavaScript:


<script>
var xhr = new XMLHttpRequest();
xhr.open("GET", "data.xml", true);
xhr.onreadystatechange = function() {
  if (xhr.readyState === 4 && xhr.status === 200) {
    var xml = xhr.responseXML;
    var users = xml.getElementsByTagName("user");
    let output = "";
    for (let i = 0; i < users.length; i++) {
      output += "<p>" + users[i].textContent + "</p>";
    }
    document.getElementById("xmlData").innerHTML = output;
  }
};
xhr.send();
</script>
<div id="xmlData"></div>

AJAX Live Search
================
مثال على [شركة برمجة مصرية] بحث مباشر عند الكتابة.

HTML + JavaScript:


<input type="text" id="search" onkeyup="liveSearch(this.value)" placeholder="ابحث">
<div id="results"></div>

<script>
function liveSearch(query) {
  if (query.length === 0) {
    document.getElementById("results").innerHTML = "";
    return;
  }
  var xhr = new XMLHttpRequest();
  xhr.open("GET", "search.php?q=" + query, true);
  xhr.onload = function() {
    if (xhr.status === 200) {
      document.getElementById("results").innerHTML = xhr.responseText;
    }
  };
  xhr.send();
}
</script>

search.php:


<?php
$q = $_GET['q'] ?? '';
$names = ['Ahmed', 'Sara', 'Mohamed', 'Nour'];
foreach ($names as $name) {
  if (stripos($name, $q) !== false) {
    echo "<p>" . htmlspecialchars($name) . "</p>";
  }
}
?>

AJAX Poll
=========
تصويت باستخدام AJAX.

HTML:


<form id="pollForm">
  <label><input type="radio" name="vote" value="yes"> نعم</label>
  <label><input type="radio" name="vote" value="no"> لا</label>
  <button type="button" onclick="submitVote()">تصويت</button>
</form>
<div id="pollResult"></div>

<script>
function submitVote() {
  var form = document.getElementById("pollForm");
  var formData = new FormData(form);
  var xhr = new XMLHttpRequest();
  xhr.open("POST", "poll.php", true);
  xhr.onload = function() {
    document.getElementById("pollResult").innerHTML = xhr.responseText;
  };
  xhr.send(formData);
}
</script>

poll.php:


<?php
$vote = $_POST['vote'] ?? '';
echo "شكراً لتصويتك: " . htmlspecialchars($vote);
?>