When should I use GET or POST with XMLHttpRequest?

Question

When use the GET method or the POST method in Ajax requests? What is the relation with the methods GET and POST for forms in HTML?

Short answer

The command POST, as opposed to the GET command, is accompanied by the submission of data to the server, so to a script that receives them as parameters. Furthermore POST is not cached.
Therefore GET is used to load documents that do not change or execute scripts that do not receive parameter, and POST in the other cases.
The precise role of these commands in each context is given in the documents of the W3C.

Long answer

GET and POST for forms

The choice is summarized in a sentence of the W3C document linked to below:

HTTP GET is designed so that all information necessary for the interaction is part of the URI, thus promoting URI addressability. With HTTP POST, some information intended to affect change to the resource state may be part of the protocol headers, not in the URI.

HTTP GET is defined so the information is transmitted to the server by the address followed by the question mark and a list of parameters.
With POST, additional information is transmitted to the server in the body of the request.

When you send data from a form, you does not have to worry about the parameters, variables and their values are sent automatically wrapped in a chain of parameters.

In the XMLHttpRequest specification

The XHR specification says that GET is used without sending data to the server by the send method, and that you use POST in the other case:

If stored method is GET act as if the data argument is null.

So practically we use GET to load a document or run a script, and POST to pass parameters to a script on the server.

The document loaded by GET is cached, further requests will not reload it again even if it has changed. This may be overcomed however by adding a parameter directly in the URL with a random value that forces a reload of the file.

More
© 2009-2012 Xul.fr