AJAX Request

AJAX Request

To send a request to a server, we use the open() and send() methods of the XMLHttpRequest object.

The open() method strictly configures the request, while send() actually fires it over the network.


The open() Method

The syntax for the open method is xhttp.open(method, url, async).


GET vs POST

GET is simpler, faster, and used to retrieve data from a server.

POST is used to send large amounts of sensitive data securely to the server.

If you need to send form data, POST is infinitely more robust and secure than GET.

GET and POST Examples:

// 1. A Simple GET Request
const getReq = new XMLHttpRequest();
getReq.onload = function() { console.log(this.responseText); };
getReq.open("GET", "demo_get.php");
getReq.send();

// 2. A POST Request sending Form Data const postReq = new XMLHttpRequest(); postReq.onload = function() { console.log(this.responseText); };

postReq.open("POST", "demo_post.php"); // You MUST add an HTTP header when sending POST data postReq.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); postReq.send("fname=Henry&lname=Ford");


Bypassing the Browser Cache

When sending a GET request, browsers often cache the result to save network bandwidth.

If the file changes on the server, the browser might load the old, cached file instead.

To avoid this, simply append a random ID to the end of the URL (like demo.php?t= + Math.random()).


Exercise 1 of 2

?

Which HTTP method is highly recommended when sending large amounts of sensitive data?

Exercise 2 of 2

?

Which XMLHttpRequest method is used to actually dispatch the request to the server?