π§ AJAX β Methods: open(), send(), setRequestHeader() Explained with Examples
π§² Introduction β Why Learn open(), send(), and setRequestHeader() in AJAX?
At the heart of AJAX communication lies the XMLHttpRequest object, which provides core methods like open(), send(), and setRequestHeader(). These methods allow developers to:
- Set up a connection to the server
- Send data asynchronously
- Configure headers (like content type or tokens)
Understanding these methods is essential for handling GET, POST, and other HTTP requests effectively in modern web development.
π― In this article, youβll learn:
- What each method does
- Syntax and usage for GET and POST requests
- Practical examples with step-by-step breakdowns
- Common pitfalls and best practices
βοΈ What Is open() in AJAX?
The open() method configures the type of HTTP request and the destination URL.
π§ Syntax:
xhr.open(method, url, async);
method:"GET","POST","PUT", etc.url: Server endpointasync(optional):truefor asynchronous (default),falsefor synchronous (not recommended)
β Example:
xhr.open("GET", "data.json", true);
This line prepares an asynchronous GET request to data.json.
π What Is send() in AJAX?
Once the request is configured with open(), the send() method initiates the request to the server.
π§ Syntax:
xhr.send(data);
- For
GETrequests,datais usuallynull - For
POSTrequests, you can send form data or JSON
β Example (GET Request):
xhr.send();
β Example (POST Request with JSON):
const payload = JSON.stringify({ name: "John", age: 25 });
xhr.send(payload);
π¨ What Is setRequestHeader() in AJAX?
Use setRequestHeader() to specify HTTP headers before sending the request (especially for POST or PUT).
π§ Syntax:
xhr.setRequestHeader(headerName, headerValue);
Common headers:
"Content-Type":"application/json"or"application/x-www-form-urlencoded""Authorization":"Bearer <token>"
β Example:
xhr.setRequestHeader("Content-Type", "application/json");
π§ͺ Full Example β POST Request with All Three Methods
var xhr = new XMLHttpRequest();
xhr.open("POST", "submit.php", true);
xhr.setRequestHeader("Content-Type", "application/json");
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
console.log("Response:", xhr.responseText);
}
};
const data = JSON.stringify({ username: "john_doe", age: 30 });
xhr.send(data);
β
This sends a POST request with JSON data to submit.php and logs the response.
π‘ Common Mistakes to Avoid
| β Mistake | β Fix |
|---|---|
Calling send() before open() | Always call open() first |
Setting headers after send() | Set headers after open(), before send() |
Not matching Content-Type and payload | Ensure headers match the data format |
| Using synchronous requests | Avoid false in open() for better UX |
π Summary β Recap & Takeaways
The trio of open(), send(), and setRequestHeader() is essential for building custom AJAX requests. These methods give developers full control over how data is sent and received from the server.
π Key Takeaways:
- Use
open()to define the request method and target URL - Use
setRequestHeader()to define headers like content type or tokens - Use
send()to transmit data (or initiate the request) - Handle responses using
onreadystatechangeoronload
βοΈ Next Steps:
- Practice both GET and POST requests using these methods
- Explore sending files using
FormDatainstead of raw JSON - Learn about response headers and how to read them with
xhr.getResponseHeader()
β FAQs β AJAX open(), send(), setRequestHeader()
β Can I call setRequestHeader() after send()?
β
No. You must call it after open() but before send(). Otherwise, it will not affect the request.
β What is the default value of async in open()?
β
It defaults to true, making the request asynchronous. Always use asynchronous mode unless you have a specific reason not to.
β Is it necessary to use setRequestHeader() for GET requests?
β
Usually not. For GET requests, parameters go in the URL, and no body is sentβso headers are rarely needed.
β Can I send a FormData object using send()?
β
Yes! XMLHttpRequest supports sending FormData objects directly.
const formData = new FormData(formElement);
xhr.send(formData);
β How do I debug an issue with open() or send()?
β
Use browser dev tools to monitor network requests and verify headers, status codes, and payload.
Share Now :
