๐Ÿ“ก JavaScript AJAX & JSON
Estimated reading: 4 minutes 275 views

JavaScript โ€” AJAX (Intro, XMLHttpRequest, PHP/ASP Integration)


Introduction โ€“ Why AJAX Still Matters in 2025

Ever wondered how modern web apps update data without refreshing the page? Think of search suggestions, form validations, or real-time feeds. Thatโ€™s AJAX in action.

AJAX (Asynchronous JavaScript and XML) is a web development technique that allows browsers to request data from servers asynchronously, making applications faster, dynamic, and more user-friendly.

By the end of this article, youโ€™ll learn:

What AJAX is and how it works
How to use XMLHttpRequest in JavaScript
How to connect JavaScript with PHP or ASP for dynamic server responses
Key performance and compatibility tips


What is AJAX?

AJAX stands for Asynchronous JavaScript and XML, but donโ€™t let “XML” fool you โ€” you can use JSON, HTML, or plain text today.

AJAX is not a language, but a combination of:

ComponentRole in AJAX Workflow
JavaScriptTriggers requests & handles responses
XMLHttpRequestSends and receives data from the server
Server-side ScriptProcesses the request (PHP, ASP, etc.)
HTML/CSSUpdates the UI dynamically without reloads

How AJAX Works โ€” Step-by-Step

  1. User triggers an event (like clicking a button)
  2. JavaScript creates an XMLHttpRequest object
  3. Sends request to the server (e.g., PHP file)
  4. Server processes the request and sends back data
  5. JavaScript receives the response and updates the DOM โ€” without reloading the page

Using XMLHttpRequest โ€” Syntax & Examples

Example 1: Basic GET Request with XMLHttpRequest

let xhr = new XMLHttpRequest(); 
xhr.open("GET", "data.txt", true); 
xhr.onload = function() {
  if (xhr.status === 200) {
    document.getElementById("output").innerHTML = xhr.responseText;
  }
};
xhr.send();

Explanation:

  • new XMLHttpRequest() โ€“ Creates the request object
  • xhr.open("GET", "data.txt", true) โ€“ Prepares a GET request to data.txt (async = true)
  • xhr.onload โ€“ Runs when response is received
  • xhr.status === 200 โ€“ Ensures successful response
  • xhr.responseText โ€“ Contains returned text data
  • xhr.send() โ€“ Sends the request

This is the most basic AJAX setup to fetch and display data.


Example 2: AJAX POST Request to PHP

let xhr = new XMLHttpRequest();
xhr.open("POST", "submit.php", true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.onload = function () {
  if (xhr.status === 200) {
    console.log("Server Response:", xhr.responseText);
  }
};
xhr.send("username=admin&password=12345");

Explanation:

  • POST is used to send sensitive or large data
  • setRequestHeader defines the format of the payload
  • The body ("username=admin&password=12345") is URL-encoded data

Backend Integration โ€“ PHP/ASP Examples

PHP File โ€“ submit.php

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

if($username === "admin" && $password === "12345"){
  echo "Login successful!";
} else {
  echo "Invalid credentials!";
}
?>

PHP handles the POST data and echoes back a message
This message can be displayed on the client side using AJAX


ASP Example โ€“ submit.asp

<%
Dim username, password
username = Request.Form("username")
password = Request.Form("password")

If username = "admin" And password = "12345" Then
  Response.Write("Login successful!")
Else
  Response.Write("Invalid credentials!")
End If
%>

ASP logic is very similar to PHP
Works seamlessly with XMLHttpRequest from JavaScript


Common Pitfalls & Best Practices

Pitfalls to Avoid

MistakeFix
Forgetting to use xhr.send()Always call send() to initiate the request
Not handling xhr.statusCheck xhr.status for error handling
Hardcoding pathsUse relative URLs or environment configs

Best Practices

  • Use JSON instead of plain text or XML for complex data
  • Validate server data before using it in DOM
  • Always sanitize inputs to avoid XSS & injection
  • Handle network errors using xhr.onerror or try...catch blocks
  • Consider using Fetch API for newer, cleaner AJAX-like code

Real-World Use Cases of AJAX

Application FeatureAJAX Role
Form submission without reloadSends form data to server asynchronously
Autocomplete searchFetches suggestions dynamically
Voting systemsUpdates like counts in real-time
Chat appsReceives & sends messages live

Summary

AJAX revolutionized how we build web applications by enabling seamless, dynamic interactions between users and servers โ€” without the jarring full-page reloads. Whether youโ€™re integrating with PHP or ASP, mastering XMLHttpRequest gives you complete control over data transfer in legacy and modern applications.


FAQs โ€“ JavaScript AJAX & XMLHttpRequest

What is the difference between AJAX and Fetch API?

AJAX uses XMLHttpRequest; Fetch API is a modern promise-based alternative. Fetch has a cleaner syntax and better error handling.

Can I use JSON with XMLHttpRequest?

Yes. You can set the header to application/json and parse the response using JSON.parse().

Is AJAX still used in 2025?

Absolutely. While newer methods like fetch or Axios are preferred, legacy systems and tight control use AJAX (XMLHttpRequest).

Do I need a server to test AJAX?

Yes. AJAX won’t work with local file paths (e.g., file://). Use a local server like XAMPP, WAMP, or Node.js.


Share Now :
Share

JavaScript โ€” AJAX (Intro, XMLHttpRequest, PHP/ASP Integration)

Or Copy Link

CONTENTS
Scroll to Top