XMLHttpRequest methods (Open(), send(), setRequestHeader())

open() addresses the envelope (method, URL, async flag), send() posts it, and setRequestHeader() writes on the envelope between the two: mandatory for POST form data.

10 min read · 10 cards · 2 checks

Read in: English · हिन्दी · ગુજરાતી


Theory

Three verbs you have been typing on faith

The AJAX skeleton you memorised last lesson contains 2 method calls you have not yet been formally introduced to:

xhr.open("GET", "seats.json", true);

xhr.send();

And FestConnect's next feature needs a third: submitting a REGISTRATION (name + event) to the server without a reload, which turns out to require setRequestHeader too.

Three methods, one postal metaphor, and the whole request side of AJAX is yours.

Theory

Envelope, notes, postbox

open() addresses the envelope: which kind of delivery (GET or POST), to which address (the URL), and by which service (asynchronous or not). Addressing an envelope posts nothing.

setRequestHeader() writes handling notes ON the envelope: "contents: form data". Notes go on after addressing, before posting.

send() drops it in the postbox. Only now does anything travel.

Theory

open(method, url, async)

xhr.open("GET", "seats.json", true);

  • method: "GET" to fetch, "POST" to submit
  • url: the target file or script
  • async: true for asynchronous (the A of AJAX; effectively always true)

The crucial understanding: open() prepares the request and moves readyState to 1: it does not transmit anything. You may open and never send; nothing will have left the browser.

For GET, data rides the URL itself as a query string: search.php?event=garba&day=2.

Theory

send() and the header in between

send() transmits:

  • xhr.send(): no argument: the GET form; any data is already in the URL
  • xhr.send("name=Riya&event=garba"): the POST form: data travels in the request body

But a POSTed body needs a label the server can decode, and that is setRequestHeader(name, value):

xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

Placement law: after open(), before send(): headers cannot be written on an unaddressed envelope, nor on one already posted.

Practical

Registration without a reload (complete page)

<!DOCTYPE html>
<html>
<head>
  <script>
    function registerMe() {
      var name  = document.getElementById("name").value;
      var xhr = new XMLHttpRequest();
      xhr.onreadystatechange = function() {
        if (xhr.readyState == 4 && xhr.status == 200) {
          document.getElementById("msg").innerHTML = xhr.responseText;
        }
      };
      xhr.open("POST", "register.php", true);        // 1: address it
      xhr.setRequestHeader("Content-Type",           // 2: label it
        "application/x-www-form-urlencoded");
      xhr.send("name=" + name + "&event=garba");     // 3: post it
    }
  </script>
</head>
<body>
  <input id="name" placeholder="Your name">
  <button onclick="registerMe()">Register for Garba Night</button>
  <p id="msg"></p>
</body>
</html>

This example runs in Gri-Learn on the web, where you can edit it and see the output.

Quiz

In the AJAX skeleton, which line actually causes data to travel to the server?

  1. new XMLHttpRequest(): creating the object starts the connection
  2. xhr.open(...): it establishes the server connection
  3. xhr.send(...): open only configures; send transmits
  4. xhr.onreadystatechange = ...: assigning the handler triggers the request
Show the answer

xhr.send(...): open only configures; send transmits

send() is the postbox: nothing leaves the browser before it. open() is the deliberately tempting distractor: it ADDRESSES the request (and readyState does tick to 1, whose label "server connection established" oversells the moment), but you can open and walk away with zero network traffic. Creating the object allocates a runner who has not moved, and assigning the handler merely installs the doorbell. Exam one-liner: open configures, send communicates.

Think first

GET or POST for these 3?

Three FestConnect jobs: (a) fetch the current seat count, (b) submit a registration with a student's name and phone, (c) a search whose result page students want to bookmark. Choose GET or POST for each, with the deciding reason, before tapping.

Show the answer

(a) GET: a pure read, no data to submit; cacheable is a bonus. (b) POST: it CHANGES server state and carries personal data, which must not sit in the URL (URLs land in logs and history; GET is also length-limited). (c) GET: query-string requests are bookmarkable and shareable precisely because the data IS the URL: search.php?event=garba. The compact rule: reading = GET, submitting or changing = POST, and anything sensitive never rides a URL.

Watch out

The 3 method traps

setRequestHeader before open(): throws: the envelope does not exist yet. The order is always open, header, send.

POST without the Content-Type header: the server receives a body it cannot decode: registrations silently arrive empty: the most common real-world slip in this unit.

Data in send() for a GET: GET's send() argument is ignored; GET data belongs in the URL's query string. Mixing the 2 conventions sends nothing anywhere useful.

Theory

The object is complete

You now hold the entire XMLHttpRequest: 4 properties that receive (bell, counter, 2 pockets, verdict) and 3 methods that transmit (address, label, post). Every AJAX exchange on earth is these 7 names choreographed. The unit's finale zooms out to see that choreography as a diagram: the full request lifecycle and the browser-vs-server architecture, which is also this paper's favourite long-answer question.

Summary

Key takeaways

  • open(method, url, async) configures: GET/POST, target, true for asynchronous: it transmits nothing.
  • send() transmits: bare for GET (data in the URL query string), send(data) for POST (data in the body).
  • setRequestHeader(name, value) goes after open, before send; POST form data needs Content-Type: application/x-www-form-urlencoded.
  • GET: reads, bookmarkable, visible and length-limited URL data; POST: submissions, body-carried, for changes and sensitive data.
  • Order forever: open, setRequestHeader, send.
  • Nothing sensitive ever travels in a URL.
  • Memory hook: address it, label it, post it.

Study this properly

This page is the lesson to read. In Gri-Learn the same topic is a graded deck: the self-checks are scored and your weak topics are tracked. Free to start.

Start this topic

Already have an account? Sign in

More from AJAX (Asynchronous JavaScript and XML)

Gri-Learn · syllabus-mapped B.C.A. lessons in English, Hindi and Gujarati

XMLHttpRequest methods (Open(), send(), setRequestHeader()) · Web Designing-2 (option A) · Gri-Learn