Skip to content

BJNSTNKVC/js-ajax-request-helper

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

15 Commits
 
 
 
 
 
 
 
 
 
 

Repository files navigation

AJAX

JavaScript AJAX request helper.

Installation & setup

NPM

You can install the package via npm:

npm install @bjnstnkvc/ajax

CDN

You can install the package via jsDelivr CDN:

<script src="https://cdn.jsdelivr.net/npm/@bjnstnkvc/ajax/lib/AJAX.min.js"></script>

Usage

Once imported, you can make an AJAX request using the following methods:

Get

Load data from the server using an HTTP GET request:

AJAX.get({ config })

Post

Send data to the server using an HTTP POST request:

AJAX.post({ config })

Patch

Send data to the server using an HTTP PATCH request:

AJAX.patch({ config })

Put

Send data to the server using an HTTP PUT request:

AJAX.put({ config })

Delete

Delete a resource from the server using an HTTP DELETE request:

AJAX.delete({ config })

Config

In order to send an AJAX request using the methods listed above, you need to pass config object. The Config object consists of the following properties:

url

A string representing the URL to send the request to:

AJAX.get({
    url: 'posts',
})

params

An object used to parse and stringify URL parameters:

AJAX.get({
    url: 'https://www.example.com/authors/{author}/posts/{post}',
    params: {
        author: 'bjnstnkvc',
        post: 2
    }
})

Example above would generate the following URL:

https://www.example.com/authors/bjnstnkvc/posts/2

query

An object used to parse and stringify URL query strings:

AJAX.get({
    url: 'https://www.example.com/posts',
    query: {
        page: 2
    }
})

Example above would generate the following URL:

https://www.example.com/posts?page=2

Sometimes you need to pass a query string as an array, in order to do so, use the following syntax:

AJAX.get({
    url: 'https://www.example.com/posts',
    query: {
        tag: ['html', 'css'],
        page: 2,
    },
})

Example above would generate the following URL:

https://www.example.com/posts?tag[]=html&tag[]=css&page=2

withCredentials

A boolean value that indicates whether cross-site Access-Control requests should be made using credentials.

AJAX.get({
    url: 'https://www.example.com/posts',
    withCredentials: true,
})

headers

In case you would like to add headers to AJAX request, you can pass them via headers property:

AJAX.get({
    url: 'https://www.example.com/posts',
    headers: {
        'Accept': 'application/json',
    }
})

data

An object containing body of data to be sent in the XHR request.

AJAX.post({
    url: 'https://www.example.com/posts',
    data: {
        title: 'A Post title',
        description: 'A Post description',
    }
})

States

Each AJAX request goes through 5 different states:

Value State Description
0 UNSENT Client has been created. open() not called yet.
1 OPENED open() has been called.
2 HEADERS_RECEIVED send() has been called, and headers and status are available.
3 LOADING Downloading; responseText holds partial data.
4 DONE The operation is complete.

Additionally, 3 custom states have been added for more convenience when making AJAX requests:

State Description
BEFORE A state prior to request being sent.
AFTER A state after the response has been sent from the server.
ERROR A state when the request fails.

In order to access each state, you can add states property to AJAX config via following syntax:

AJAX.get({
    url   : 'https://www.example.com/posts',
    states: {
        before() {
            // 
        },
        unsent(xhr) {
            // 
        },
        opened(xhr) {
            // 
        },
        received(xhr) {
            // 
        },
        loading(xhr, response) {
            // 
        },
        done(xhr, response) {
            // 
        },
        error(xhr, response) {
            // 
        },
        after() {
            //
        }
    }
})

Note: loading, done and error states return xhr object as well as already parsed xhr response to JSON.

Defaults

AJAX helper gives you an option to set config defaults using the following syntax:

AJAX.defaults({
    url: 'https://www.example.com/posts',
    withCredentials: true,
    headers: {
        'X-Requested-With': 'XMLHttpRequest',
        'Accept'          : 'application/json',
    }
});

AJAX.post({
    ...
})

By doing so, every subsequent AJAX instance would use the config set above.

In case you need to overwrite previously set default config value, you simply need to set them :

AJAX.patch({
    url: 'https://www.example.com/posts/2',
    withCredentials: false,
    ...
});