JavaScript

coding learning websites codepractice

JS Basics

JS Variables & Operators

JS Data Types & Conversion

JS Numbers & Math

JS Strings

JS Dates

JS Arrays

JS Control Flow

JS Loops & Iteration

JS Functions

JS Objects

JS Classes & Modules

JS Async Programming

JS Advanced

JS HTML DOM

JS BOM (Browser Object Model)

JS Web APIs

JS AJAX

JS JSON

JS Graphics & Charts

JavaScript AJAX PHP


AJAX allows web pages to communicate with the server without reloading, and PHP is one of the most popular server-side languages. Using AJAX with PHP lets you fetch or send data dynamically, making your web applications more interactive.

What Is AJAX PHP?

AJAX PHP refers to using AJAX requests in JavaScript to interact with PHP scripts on the server. This combination is widely used for tasks like:

  • Submitting forms without refreshing the page.

  • Loading data from a database dynamically.

  • Displaying filtered content based on user input.

AJAX handles the client-side communication, while PHP handles the server-side processing.

Creating a Simple AJAX PHP Example

Imagine you want to fetch a greeting message from the server using PHP.

PHP File (greet.php)

<?php
// Set content type to plain text
header('Content-Type: text/plain');

// Send a greeting message
echo "Hello, Sanjana! Welcome to AJAX with PHP.";
?>

HTML and JavaScript

<button id="loadBtn">Get Greeting</button>
<div id="output"></div>

<script>
document.getElementById("loadBtn").addEventListener("click", function() {
  let xhr = new XMLHttpRequest();
  xhr.open("GET", "greet.php", true); // Initialize GET request

  xhr.onload = function() {
    if (xhr.status === 200) {
      // Display server response in the div
      document.getElementById("output").textContent = xhr.responseText;
    } else {
      document.getElementById("output").textContent = "Error loading message";
    }
  };

  xhr.send(); // Send the request
});
</script>

Explanation:

  • The PHP script generates a plain text response.

  • The AJAX request fetches it asynchronously.

  • xhr.responseText contains the server’s response.

Clicking the button will display:
“Hello, Sanjana! Welcome to AJAX with PHP.”

Sending Data from JavaScript to PHP

AJAX can also send data to PHP for processing using the POST method.

HTML Form

<input type="text" id="username" placeholder="Enter your name">
<button id="sendBtn">Send</button>
<div id="response"></div>

JavaScript

document.getElementById("sendBtn").addEventListener("click", function() {
  let name = document.getElementById("username").value;

  let xhr = new XMLHttpRequest();
  xhr.open("POST", "process.php", true);

  // Set header for form data
  xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");

  xhr.onload = function() {
    if (xhr.status === 200) {
      document.getElementById("response").textContent = xhr.responseText;
    } else {
      document.getElementById("response").textContent = "Error sending data";
    }
  };

  // Send data to PHP
  xhr.send("username=" + encodeURIComponent(name));
});

PHP File (process.php)

<?php
if(isset($_POST['username'])){
    $name = htmlspecialchars($_POST['username']); // Sanitize input
    echo "Hello, $name! Your data has been received by PHP.";
} else {
    echo "No data received.";
}
?>

Explanation:

  • Data from the input field is sent via POST.

  • encodeURIComponent() ensures special characters are handled correctly.

  • PHP retrieves the data with $_POST['username'].

  • htmlspecialchars() prevents XSS attacks.

If Sanjana enters her name, the response will be:
“Hello, Sanjana! Your data has been received by PHP.”

Fetching JSON Data from PHP

AJAX PHP is often used to retrieve JSON data from the server, especially when working with databases.

PHP File (user.php)

<?php
header('Content-Type: application/json');

$user = array(
    "name" => "Sanjana",
    "age" => 26,
    "email" => "sanjana@example.com"
);

echo json_encode($user);
?>

JavaScript

let xhr = new XMLHttpRequest();
xhr.open("GET", "user.php", true);

xhr.onload = function() {
  if (xhr.status === 200) {
    let user = JSON.parse(xhr.responseText); // Convert JSON string to object
    document.getElementById("output").innerHTML =
      `Name: ${user.name}<br>Age: ${user.age}<br>Email: ${user.email}`;
  } else {
    document.getElementById("output").textContent = "Failed to load data";
  }
};

xhr.send();

Explanation:

  • json_encode() converts the PHP array into a JSON string.

  • JSON.parse() converts it back into a JavaScript object.

  • This makes it easy to dynamically display user information.

Error Handling in AJAX PHP

Always check the status code to ensure your AJAX request succeeds.

xhr.onload = function() {
  if (xhr.status === 200) {
    console.log("Request successful:", xhr.responseText);
  } else if (xhr.status === 404) {
    console.error("PHP file not found.");
  } else {
    console.error("Server error:", xhr.status);
  }
};
  • 200 indicates success.

  • 404 means the file is missing.

  • Other codes indicate server errors.

Summary of the Tutorial

AJAX PHP allows you to:

  • Fetch data from the server dynamically without page reload.

  • Send form or user data to PHP for processing.

  • Receive plain text, HTML, or JSON responses.

  • Handle errors using HTTP status codes.

  • Build interactive applications like dynamic forms, live search, and content updates.

By combining AJAX and PHP, you can create responsive web applications that are more user-friendly and efficient.


Practice Questions

  1. Write an AJAX GET request to fetch a greeting from greet.php and display it in a <div> when a button is clicked.

  2. Create a form with an input field for a name and send it via AJAX POST to process.php, then display the server response.

  3. Fetch JSON data from user.php and display Sanjana’s name, age, and email dynamically on the page.

  4. Write an AJAX request that handles errors when process.php is missing (404) and shows an alert.

  5. Create a button that sends a name to PHP via POST and updates a <p> element with the returned message.

  6. Fetch an HTML snippet from snippet.php and insert it into a <div> without reloading the page.

  7. Send multiple form fields (name, email, age) via AJAX POST to PHP and display a confirmation message.

  8. Write code to fetch JSON from user.php, parse it, and populate an unordered list <ul> with the data.

  9. Create an AJAX request that times out after 5 seconds and shows an error message if PHP doesn’t respond.

  10. Write a function that sends the user’s name to PHP, receives a personalized greeting, and appends it to a <div> each time the button is clicked.


JavaScript

online coding class codepractice

JS Basics

JS Variables & Operators

JS Data Types & Conversion

JS Numbers & Math

JS Strings

JS Dates

JS Arrays

JS Control Flow

JS Loops & Iteration

JS Functions

JS Objects

JS Classes & Modules

JS Async Programming

JS Advanced

JS HTML DOM

JS BOM (Browser Object Model)

JS Web APIs

JS AJAX

JS JSON

JS Graphics & Charts

Go Back Top