This page presents a Vanilla JS (pure JavaScript) Ajax module. Ajax allows you to:
The module presented on this page has the following specifications:
Look how simple it is to create an Ajax request:
import {ajax} from '/path/to/ajax.min.js';
ajax('https://api_url.com')
.post({ "key1": "value1", "key2": "value2"})
.then(function(response) { alert(response) })
.catch(function() { alert ('Error') })
Let's detail the previous example. First, import the module with the following line (note that module can only be imported from module)
import {ajax} from '/path/to/ajax.min.js';
Create the request and set the url you need to request:
.ajax('https://api_url.com')
Set data and post the request. The following
example will provide $_POST['key1']
and $_POST['key2']
on PHP servers.
.post({ "key1": "value1", "key2": "value2"})
If the request success, the callback function in the then
clause will be called. Here,
received data are displayed with an alert. You can use classical functions
or arrow functions:
.then(function (response) { alert(response) })
// or
.then((response) => alert(response))
If the request failed, the error will be catched. Here, an error message is displayed in an alert:
.catch(function (failure) { alert ('Error') } )
// or
.catch((failure) => alert ('Error'))
If you are not familiar with promise, you just need to know that:
then()
is called in case of successcatch()
is called in case of failureSince each function returns the Ajax object (this
), you may chain the methods as illustrated bellow:
ajax()
.url('https://api_url.com')
.method('POST')
.data('key1','Value1')
.data('key2','Value2')
.send()
.then((data) => { console.log ('success', data) })
.catch((error) => { console.log ('failed', error.status)} );
If you are used to work with jQuery, you can create an object and pass it to the
ajax()
constructor as illustrated below:
ajax({
url:'https://api_url.com',
method:'POST',
data:{
key1:'Value1',
key2:'Value2'
}).send()
.then((data) => { console.log ('success', data) })
.catch((error) => { console.log ('failed', error.status)} );
There is several ways to specify the URL.
Call the constructor with the URL as a string argument:
ajax('https://api_url.com')
Call the constructor with the URL as an object argument:
ajax({url: 'https://api_url.com'})
You may also call the url()
method:
ajax().url('https://api_url.com')
There is several ways to specify the method (POST
or GET
).
If you do not specify the method, the POST
method is selected by default.
Call the constructor with the method as an object argument:
ajax({method: 'GET'})
You may also call the method()
function:
ajax().method('GET')
You can specify the method by calling the function .post()
or .get()
instead of
.send()
:
ajax().post() // Request with the POST method
ajax().get() // Request with the GET method
The methods .post()
, .get()
and .send()
accept optional data argument. See
section The post(), get() and send() methods.
There is several ways to set the data you need to post.
If you do not specify data, the request will be send without data. It may be usefull to load files for example. The following example request the Ajax module source code from my blog:
Call the constructor with data as an object argument:
ajax({data: { key1:'Value1', key2:'Value2' } })
You may also call the data()
function. This function accepts:
ajax().data( {key1: 'Value1} )
ajax().data( 'key1', 'Value1' )
Data can be specifyed while calling .post()
, .get()
or .send()
:
ajax().post( {key1: 'Value1} )
ajax().get( 'key1', 'Value1' )
ajax().send( { key1: 'Value1, key2: 'Value2} )
As for the .data()
method, arguments can be strings or object.
The function .post()
, .get()
and .send()
all returns a promise.
If the request returns a HTTP successful response status code
the then()
callback function is called, otherwise the catch()
callback is called if an error occured.
Successful response are request with returning status code in the range [200; 299].
In case of failure, the promise return the XMLHttpRequest
object. This object contains
additional informations on the request. The object properties can be usefull to diagnosticate
errors in request or for displaying a message to the user. Most usefull properties are:
XMLHttpRequest.readyState
state of the request, should be 4XMLHttpRequest.response
response of the requestXMLHttpRequest.responseText
response of the request as textXMLHttpRequest.status
status of the request, should be in the range [200; 299]. See HTTP response status codes for more detailsComplete list of properties is detailed on the XMLHttpRequest page
You can test the non minifyed source code on JSFiddle.