- AJAX — XMLHttpRequest
- Send a Request To a Server
- The url — A File On a Server
- Asynchronous — True or False?
- GET or POST?
- GET Requests
- Example
- Example
- Example
- POST Requests
- Example
- Example
- Synchronous Request
- Example
- POST
- Syntax
- Example
- Specifications
- Browser compatibility
- See also
- Found a content problem with this page?
AJAX — XMLHttpRequest
The XMLHttpRequest object is used to request data from a server.
Send a Request To a Server
To send a request to a server, we use the open() and send() methods of the XMLHttpRequest object:
Method | Description |
---|---|
open(method, url, async) | Specifies the type of request |
The url — A File On a Server
The url parameter of the open() method, is an address to a file on a server:
The file can be any kind of file, like .txt and .xml, or server scripting files like .asp and .php (which can perform actions on the server before sending the response back).
Asynchronous — True or False?
Server requests should be sent asynchronously.
The async parameter of the open() method should be set to true:
By sending asynchronously, the JavaScript does not have to wait for the server response, but can instead:
- execute other scripts while waiting for server response
- deal with the response after the response is ready
The default value for the async parameter is async = true.
You can safely remove the third parameter from your code.
Synchronous XMLHttpRequest (async = false) is not recommended because the JavaScript will stop executing until the server response is ready. If the server is busy or slow, the application will hang or stop.
GET or POST?
GET is simpler and faster than POST , and can be used in most cases.
However, always use POST requests when:
- A cached file is not an option (update a file or database on the server).
- Sending a large amount of data to the server (POST has no size limitations).
- Sending user input (which can contain unknown characters), POST is more robust and secure than GET.
GET Requests
Example
In the example above, you may get a cached result. To avoid this, add a unique ID to the URL:
Example
If you want to send information with the GET method, add the information to the URL:
Example
How the server uses the input and how the server responds to a request, is explained in a later chapter.
POST Requests
Example
To POST data like an HTML form, add an HTTP header with setRequestHeader() . Specify the data you want to send in the send() method:
Example
xhttp.open(«POST», «ajax_test.asp»);
xhttp.setRequestHeader(«Content-type», «application/x-www-form-urlencoded»);
xhttp.send(«fname=Henry&lname=Ford»);
Method | Description |
---|---|
setRequestHeader(header, value) | Adds HTTP headers to the request |
Synchronous Request
To execute a synchronous request, change the third parameter in the open() method to false :
Sometimes async = false are used for quick testing. You will also find synchronous requests in older JavaScript code.
Since the code will wait for server completion, there is no need for an onreadystatechange function:
Example
xhttp.open(«GET», «ajax_info.txt», false);
xhttp.send();
document.getElementById(«demo»).innerHTML = xhttp.responseText;
Synchronous XMLHttpRequest (async = false) is not recommended because the JavaScript will stop executing until the server response is ready. If the server is busy or slow, the application will hang or stop.
Modern developer tools are encouraged to warn about using synchronous requests and may throw an InvalidAccessError exception when it occurs.
POST
The HTTP POST method sends data to the server. The type of the body of the request is indicated by the Content-Type header.
The difference between PUT and POST is that PUT is idempotent: calling it once or several times successively has the same effect (that is no side effect), where successive identical POST may have additional effects, like passing an order several times.
A POST request is typically sent via an HTML form and results in a change on the server. In this case, the content type is selected by putting the adequate string in the enctype attribute of the element or the formenctype attribute of the or elements:
- application/x-www-form-urlencoded : the keys and values are encoded in key-value tuples separated by ‘&’ , with a ‘=’ between the key and the value. Non-alphanumeric characters in both keys and values are URL encoded: this is the reason why this type is not suitable to use with binary data (use multipart/form-data instead)
- multipart/form-data : each value is sent as a block of data («body part»), with a user agent-defined delimiter («boundary») separating each part. The keys are given in the Content-Disposition header of each part.
- text/plain
When the POST request is sent via a method other than an HTML form — like via an XMLHttpRequest — the body can take any type. As described in the HTTP 1.1 specification, POST is designed to allow a uniform method to cover the following functions:
- Annotation of existing resources
- Posting a message to a bulletin board, newsgroup, mailing list, or similar group of articles;
- Adding a new user through a signup modal;
- Providing a block of data, such as the result of submitting a form, to a data-handling process;
- Extending a database through an append operation.
Syntax
Example
A simple form using the default
application/x-www-form-urlencoded
content type:http
POST /test HTTP/1.1 Host: foo.example Content-Type: application/x-www-form-urlencoded Content-Length: 27 field1=value1&field2=value2A form using the multipart/form-data content type:
POST /test HTTP/1.1 Host: foo.example Content-Type: multipart/form-data;boundary="boundary" --boundary Content-Disposition: form-data; name="field1" value1 --boundary Content-Disposition: form-data; name="field2"; filename="example.txt" value2 --boundary--Specifications
Browser compatibility
BCD tables only load in the browser
See also
Found a content problem with this page?
This page was last modified on Apr 10, 2023 by MDN contributors.
Your blueprint for a better internet.