AJAX - open() in AJAX
Let me explain the open()
method in AJAX step by step with syntax, parameters, examples, and best practices.
1. What is open()
in AJAX?
The open()
method is used to initialize an AJAX request by specifying:
-
The HTTP method (GET, POST, etc.)
-
The URL of the resource
-
Whether the request should be asynchronous or synchronous
It does not send the request — it just prepares it.
To actually send the request, we use send()
after calling open()
.
2. Syntax
xhr.open(method, url, async, user, password);
Parameters
Parameter | Type | Description |
---|---|---|
method | String | HTTP request method → "GET" , "POST" , "PUT" , "DELETE" , etc. |
url | String | The URL of the server resource (e.g., data.json or an API link). |
async (optional) | Boolean | true → Asynchronous (default) false → Synchronous |
user (optional) | String | Username for authentication (rarely used). |
password (optional) | String | Password for authentication (rarely used). |
3. How open()
Works in AJAX
-
Create XMLHttpRequest Object
var xhr = new XMLHttpRequest();
-
Initialize Request
xhr.open("GET", "data.txt", true);
-
Send Request
xhr.send();
-
Handle Response
xhr.onload = function() { console.log(xhr.responseText); };
4. Example 1 — Using open()
with GET
var xhr = new XMLHttpRequest();
xhr.open("GET", "data.txt", true); // Initialize request
xhr.onload = function() {
if (xhr.status === 200) {
console.log(xhr.responseText); // Displays data from data.txt
}
};
xhr.send();
Explanation:
-
Method → GET
-
URL → data.txt
-
Asynchronous → true
5. Example 2 — Using open()
with POST
var xhr = new XMLHttpRequest();
xhr.open("POST", "server.php", true); // Initialize request
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.onload = function() {
console.log(xhr.responseText); // Response from server.php
};
xhr.send("name=John&age=25"); // Sending data in POST
Explanation:
-
Method → POST
-
URL → server.php
-
Asynchronous → true
-
Data sent via
send()
method.
6. Example 3 — Synchronous Request (Not Recommended)
var xhr = new XMLHttpRequest();
xhr.open("GET", "data.txt", false); // Synchronous request
xhr.send();
console.log(xhr.responseText);
Problem:
-
The browser freezes until the response comes back.
-
This is why synchronous AJAX is rarely used in modern web apps.
7. Key Points to Remember
-
open()
only initializes the request, it does not send it. -
Always call
send()
afteropen()
. -
Always use asynchronous mode (
true
) for better performance. -
Use GET for fetching data and POST for sending data.
-
Use
setRequestHeader()
only afteropen()
but beforesend()
.