HTML CSS Bootstrap JavaScript jQuery MySQL PHP Data Mining

AJAX Request

To send a request to a server, we use the open() and send() methods of the XMLHttpRequest object. This process allows your application to fetch or submit data without interrupting the user experience.


GET vs POST Simulator

Select a method and click "Send Request" to see how the request is structured internally:

GET
xhttp.open("GET", "demo.txt", true);
xhttp.send();

* GET is best for simple data fetching and is cached by browsers.


The open() Method

The open() method specifies the type of request. It takes three parameters:

  • method: The type of request: GET or POST.
  • url: The location of the file on the server.
  • async: true (asynchronous) or false (synchronous).
xhttp.open("GET", "ajax_info.txt", true);

GET vs. POST

Choosing the right method is critical for security and performance:

Comparison GET POST
Security Less secure (data in URL) More secure (data in body)
Data Limit Limited (can be long URLs) Unlimited
Caching Can be cached Never cached

The send() Method

The send() method sends the request to the server.

  • For GET requests: Use xhttp.send().
  • For POST requests: Use xhttp.send(string).

Sending Request Headers

If you need to send data like a form (via POST), you must add an HTTP header using setRequestHeader().

xhttp.open("POST", "ajax_test.php", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send("fname=Henry&lname=Ford");
Important: Always use Asynchronous (true). Synchronous requests are discouraged because they freeze the browser until the server responds, creating a terrible user experience.

Key Points to Remember

  • GET is for retrieving data; POST is for sending/updating.
  • open() initializes the request; **send()** executes it.
  • Use setRequestHeader() for custom POST data.
  • Always keep async set to true.
  • GET sends data via the URL query string.