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


JavaScript AJAX with PHP is one of the most important concepts in modern web development. It allows a web page to communicate with the server without reloading, making websites faster, smoother, and more user-friendly. Features like live search, form submission, pagination, chat systems, and real-time updates are all built using AJAX.

In this tutorial, you will learn what AJAX is, how JavaScript AJAX works with PHP, request and response flow, GET and POST requests, practical examples, common use cases, and best practices. Everything is explained step by step in simple and practical language.

What Is AJAX

AJAX stands for Asynchronous JavaScript and XML. Despite the name, AJAX does not require XML. Today, JSON and plain text are more commonly used.

AJAX allows JavaScript to send requests to the server and receive responses in the background, without refreshing the web page.

This means:

  • The page stays loaded

  • Only required data is updated

  • User experience feels faster and smoother

Why Use AJAX with PHP

PHP is a server-side language, and JavaScript runs in the browser. AJAX connects these two.

Using JavaScript AJAX with PHP allows you to:

  • Submit forms without page reload

  • Fetch data from the database dynamically

  • Implement live search

  • Build pagination systems

  • Create login and registration systems

  • Update content in real time

AJAX acts as a bridge between frontend and backend.

How JavaScript AJAX with PHP Works

The basic working flow is simple:

  1. User performs an action in the browser

  2. JavaScript sends a request to the PHP file

  3. PHP processes the request on the server

  4. PHP returns a response

  5. JavaScript updates the page dynamically

This entire process happens without refreshing the page.

AJAX Request Methods

AJAX mainly uses two HTTP methods:

  • GET

  • POST

GET is used to fetch data
POST is used to send data securely

Both methods are commonly used with PHP.

Creating an AJAX Request Using JavaScript

AJAX requests are commonly created using the XMLHttpRequest object.

Basic AJAX Structure

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

This sends a request to a PHP file named data.php.

Handling Server Response

To read the response from PHP:

xhr.onload = function () {
    if (xhr.status === 200) {
        console.log(xhr.responseText);
    }
};

responseText contains the data returned by PHP.

Example 1: Simple AJAX Request with PHP

JavaScript Code

<button onclick="loadData()">Load Data</button>
<div id="output"></div>

<script>
function loadData() {
    let xhr = new XMLHttpRequest();
    xhr.open("GET", "data.php", true);

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

    xhr.send();
}
</script>

PHP Code (data.php)

<?php
echo "Hello from PHP using AJAX";
?>

When the button is clicked, data is loaded without refreshing the page.

Example 2: AJAX GET Request with Parameters

JavaScript

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

xhr.onload = function () {
    console.log(xhr.responseText);
};

xhr.send();

PHP (user.php)

<?php
$name = $_GET['name'];
echo "Welcome " . $name;
?>

This sends data from JavaScript to PHP using a GET request.

Example 3: AJAX POST Request with PHP

POST requests are more secure and widely used for forms.

JavaScript

let xhr = new XMLHttpRequest();
xhr.open("POST", "submit.php", true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

xhr.onload = function () {
    console.log(xhr.responseText);
};

xhr.send("username=admin&password=1234");

PHP (submit.php)

<?php
$username = $_POST['username'];
$password = $_POST['password'];

echo "Username: " . $username;
?>

POST is preferred when sending sensitive data.

Example 4: AJAX Form Submission

HTML Form

<form id="myForm">
    <input type="text" name="email">
    <button type="submit">Submit</button>
</form>

<div id="message"></div>

JavaScript

document.getElementById("myForm").addEventListener("submit", function (e) {
    e.preventDefault();

    let formData = new FormData(this);
    let xhr = new XMLHttpRequest();

    xhr.open("POST", "form.php", true);

    xhr.onload = function () {
        document.getElementById("message").innerHTML = xhr.responseText;
    };

    xhr.send(formData);
});

PHP (form.php)

<?php
$email = $_POST['email'];
echo "Email received: " . $email;
?>

This is a real-world example of form submission using AJAX.

Example 5: Fetching Database Data Using AJAX and PHP

JavaScript

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

xhr.onload = function () {
    document.getElementById("output").innerHTML = xhr.responseText;
};

xhr.send();

PHP (users.php)

<?php
$conn = mysqli_connect("localhost", "root", "", "test");

$result = mysqli_query($conn, "SELECT name FROM users");

while ($row = mysqli_fetch_assoc($result)) {
    echo "<p>" . $row['name'] . "</p>";
}
?>

This dynamically loads data from the database.

Handling Errors in AJAX

Always handle errors to improve reliability.

xhr.onerror = function () {
    console.log("Request failed");
};

Checking status codes helps avoid unexpected behavior.

AJAX Response Formats

PHP can return data in different formats:

  • Plain text

  • HTML

  • JSON

JSON is the most popular format.

PHP Returning JSON

<?php
$data = ["name" => "Amit", "age" => 25];
echo json_encode($data);
?>

JavaScript Handling JSON

let data = JSON.parse(xhr.responseText);
console.log(data.name);

Common Use Cases

JavaScript AJAX with PHP is used for:

  • Live search

  • Login and registration

  • Infinite scrolling

  • Dynamic pagination

  • Contact forms

  • Chat applications

  • Admin dashboards

Almost every dynamic website uses AJAX.

Common Mistakes

  • Forgetting to check request status

  • Not sanitizing data in PHP

  • Using GET for sensitive data

  • Ignoring error handling

  • Reloading page unnecessarily

Avoiding these mistakes improves performance and security.

Best Practices

  • Validate data on both client and server

  • Use POST for sensitive information

  • Return JSON for structured data

  • Keep PHP logic clean and secure

  • Show loading indicators for better UX

  • Handle failures gracefully

Following best practices results in professional-quality applications.

Security Considerations

  • Sanitize input using PHP functions

  • Protect against SQL injection

  • Avoid exposing sensitive server logic

  • Use HTTPS

  • Never trust client-side data blindly

Security is critical when using AJAX with PHP.

Summary of JavaScript AJAX PHP

JavaScript AJAX with PHP allows web applications to communicate with the server without refreshing the page. By combining JavaScript on the frontend and PHP on the backend, you can build fast, interactive, and modern web applications. From simple data fetching to complex systems like live search and form handling, AJAX plays a key role in improving user experience. Understanding how requests, responses, methods, and security work together will help you build scalable and professional web applications with confidence.


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.


Try a Short Quiz.

coding learning websites codepractice

No quizzes available.

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