πŸ” AJAX Request & Response Lifecycle
Estimated reading: 4 minutes 80 views

πŸ”§ 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 endpoint
  • async (optional): true for asynchronous (default), false for 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 GET requests, data is usually null
  • For POST requests, 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 payloadEnsure headers match the data format
Using synchronous requestsAvoid 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 onreadystatechange or onload

βš™οΈ Next Steps:

  • Practice both GET and POST requests using these methods
  • Explore sending files using FormData instead 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 :

Leave a Reply

Your email address will not be published. Required fields are marked *

Share

AJAX – Methods: open(), send(), setRequestHeader()

Or Copy Link

CONTENTS
Scroll to Top