Simple and lightweight JavaScript Ajax module

This page presents a Vanilla JS (pure JavaScript) Ajax module. Ajax allows you to:

The module presented on this page has the following specifications:

How to use?

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') })

How it works?

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:

Method chaining

Since 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)} );

jQuery style

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)} );

Specify the URL

There is several ways to specify the URL.

In the constructor (string)

Call the constructor with the URL as a string argument:

ajax('https://api_url.com')

In the constructor (JS object)

Call the constructor with the URL as an object argument:

ajax({url: 'https://api_url.com'})

The url() method

You may also call the url() method:

ajax().url('https://api_url.com')

Specify the posting method

There is several ways to specify the method (POST or GET).

Default

If you do not specify the method, the POST method is selected by default.

In the constructor (JS object)

Call the constructor with the method as an object argument:

ajax({method: 'GET'})

The method() function

You may also call the method() function:

ajax().method('GET')

The post() and get() methods

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.

Setting data

There is several ways to set the data you need to post.

Default

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:

In the constructor (JS object)

Call the constructor with data as an object argument:

ajax({data: { key1:'Value1', key2:'Value2' } })

The data() function

You may also call the data() function. This function accepts:

ajax().data( {key1: 'Value1} )
ajax().data( 'key1', 'Value1' )

The post(), get() and send() methods

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.

In case of failure

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:

Complete list of properties is detailed on the XMLHttpRequest page

Download

You can test the non minifyed source code on JSFiddle.


Last update : 04/20/2020