Today, I want to share how to send HTTP request from browser using builtin JavaScript and jQuery.
XML HTTP Request (XHR)
The XMLHttpRequest.onreadystatechange
property contains the event handler to
be called when the readystatechange
event is fired, that is every time the
readyState
property of the XMLHttpRequest
changes.
Property onreadystatechange
is supported in all browsers. Since then, a
number of additional event handlers have been implemented in various browsers
(onload
, onerror
, onprogress
, etc.).
Ready State | Num | Description |
---|---|---|
UNSENT |
0 | XHR constructed. |
OPENED |
1 | Method open() successfully invoked. |
HEADERS_RECEIVED |
2 | Redirection finished, all headers received. |
LOADING |
3 | The response’s body is being received. |
DONE |
4 | The data transfer has been completed, or error. |
jQuery 1.4
Load data from the server using a HTTP GET request.
with the following type table:
Key | Value |
---|---|
url | String |
data | PlainObject or String |
success | Function( PlainObject data, String textStatus, jqXHR jqXHR ) |
dataType | String |
For example:
jQuery 1.5+
As of jQuery 1.5, all of jQuery’s Ajax methods return a superset of the
XMLHTTPRequest
object. This jQuery XHR object, or “jqXHR”, returned by
$.get()
implements the Promise
interface, giving it all the properties,
methods, and behavior of a Promise
.
MDN:
The
Promise
object represents the eventual completion (or failure) of an asynchronous operation, and its resulting value.