Ajax Xmlhttp in JavaScript
? AJAX XMLHttpRequest in JavaScript
XMLHttpRequest is the original JavaScript object used to make AJAX requests to a server without reloading the page. It can send/receive data in text, HTML, JSON, or XML formats.
? Basic Structure of XMLHttpRequest
const xhr = new XMLHttpRequest(); // Create request objectxhr.open("METHOD", "URL", true); // Set method + URLxhr.onload = function () { // On success if (xhr.status === 200) { // Handle response console.log(xhr.responseText); }};xhr.send(); // Send the request? Example 1: GET Request
HTML
<button onclick="loadText()">Load Text</button><div id="output"></div>JavaScript
function loadText() { const xhr = new XMLHttpRequest(); xhr.open("GET", "data.txt", true); xhr.onload = function () { if (xhr.status === 200) { document.getElementById("output").innerHTML = xhr.responseText; } }; xhr.send();}data.txt
This is a sample file loaded using XMLHttpRequest.? Example 2: POST Request
JavaScript
function sendData() { const 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) { alert("Server response: " + xhr.responseText); } }; xhr.send("name=John&email=john@example.com");}PHP (submit.php)
<?phpecho "Received: " . $_POST['name'] . " (" . $_POST['email'] . ")";?>? Example 3: Load JSON and Parse
const xhr = new XMLHttpRequest();xhr.open("GET", "user.json", true);xhr.onload = function () { if (xhr.status === 200) { const data = JSON.parse(xhr.responseText); console.log("Name:", data.name); }};xhr.send();user.json
{ "name": "Alice", "email": "alice@example.com"}?? Key XMLHttpRequest Methods & Properties
| Property/Method | Description |
|---|---|
xhr.open() | Initializes the request |
xhr.send() | Sends the request |
xhr.responseText | Returns the response as a string |
xhr.responseXML | Returns response as XML |
xhr.status | HTTP status code (e.g. 200, 404) |
xhr.readyState | State of the request (0–4) |
xhr.setRequestHeader() | Set headers (e.g. for POST data) |
? readyState Values
| Value | Description |
|---|---|
| 0 | Request not initialized |
| 1 | Server connection established |
| 2 | Request received |
| 3 | Processing request |
| 4 | Request finished and response is ready |
? Summary
XMLHttpRequestis a core JavaScript object for making AJAX calls.Still widely used, though modern apps prefer
fetch().Use it to request and receive data from the server without page reload.
Would you like a full working example using XMLHttpRequest with a MySQL + PHP backend?