2.0.0 • Published 4 years ago

slim-ajax v2.0.0

Weekly downloads
1
License
MIT
Repository
-
Last release
4 years ago

Slim-AJAX Logo

An Advanced light-weight AJAX API for node and all modern browsers (download).

NPM Version

Philosophy

Although jQuery AJAX is one the most complete AJAX APIs fow Web development, it is not independent from the rest of the jQuery library. Moreover, by the introduction of advanced Web development frameworks like React, Angular, and Vue, the existence of an independent advanced light-weight AJAX API is necessary more than ever. Slim-AJAX is meant to fulfill this requirement for developers who think beyond the Internet Explorer and old browsers era.

Slim-AJAX incorporates some well-known and frequently used design patterns including singletone, chaining, lazy-instantiation, and factory pattern to provide advanced, user-friendly, and professional API.

Installation

This is a Node.js module available through the npm registry.

Before installing, download and install Node.js. Node.js 0.10 or higher is required.

Installation is done using the npm install command:

$ npm install slim-ajax

Slim-AJAX API

const slimAjax = require('slim-ajax');

slimAjax.request("GET", "/", true, [username, password]).send(data);
slimAjax.request("POST", "/", true, [username, password]).send(data);
slimAjax.get("/", true, [username, password]).send(data);
slimAjax.post("/", true, [username, password]).send(data);

Each of the request, get, and post methods as the top-level methods of Slim-AJAX API supports chaining true the following methods:

- setHeaders({headerName: value})

This method gets an object containing the http headers and their corresponding values as a set of key-value pairs. It clearly sets those headers in the AJAX request to their corresponding values.

Example:

slimAjax.post(...).setHeaders({'Content-Type', 'text/html'});

- setPropsHandlers({property/event: value})

This method gets an object containing any of the properties and handlers supported by Slim-Ajax API as a set of key-value pairs. Similar to the previous method, it sets those properties and handlers to their corresponding values.

Slim_Ajax supports the following properties and handlers: |property | Description | |:--------------------|:-------------------------------------------------------------------------------| |contentType | sets the value of 'Content-Type' http header | |responseType | sets the value of the 'responseType' property of the XMLHttprequest object | |overrideMimeTypeWith | its value will be used to override the MimeType of the response | |timeout | sets the value of the 'timeout' property of the XMLHttprequest object | |noCache | noCache: true prevents browsers from caching the response | |cors | cors: true makes the Cross-Origin Resource Sharing possible |

HandlerDescription
onSuccessequivalent to (readyState === 4 && status === 200)
onFailurecomplement of "onSuccess"
onLoadStart"onloadstart" event handler of the XMLHttprequest object
onProgress"onprogress" event handler of the XMLHttprequest object
onAbort"onabort" event handler of the XMLHttprequest object
onError"onerror" event handler of the XMLHttprequest object
onLoad"onload" event handler of the XMLHttprequest object
onTimeout"ontimeout" event handler of the XMLHttprequest object
onLoadEnd"onloadend" event handler of the XMLHttprequest object

Note: The http Content-Type header can be also set via setHeaders('Content-Type', ...). However, the "contentType" property is just a convenience since this http header is commonly used in almost all AJAX requests.

Example:

slimAjax.post(...).setPropsHandlers({
  contentType: 'text/html',
  timeout: 100,
  onSuccess: (resObject, globals) => {
    // ...
  },
  onFailure: (resObject) => {
    // ...
  },
  onLoad: (event, resObject, globals) => {
    // ...
  }
});

Note: Read more about arguments passed to onSuccess, onFailure, and onLoad handlers on globals and on resObject in this documentation.

- setUploadHandlers({event: handler})

This method sets the event handler on the XMLHttprequest.upload object. The handlers are the same as those in the previous method EXCEPTonSuccess and onFailure which are only available for XMLHttprequest object.

Example:

slimAjax.post(...).setUploadHandlers({
  onAbort: (event) => {
    // ...
  },
  onLoad: (event, resObject, globals) => {
    // ...
  }
});

- send(data)

This method is equivalent to send() method on XMLHttprequest. However, it has some improved functionality depending on the http method in the request. For GET method, it essentially sends the encoded url regardless of the data passed to it while, for the POST method, it actually sends the passed data through the request. This method returns the XMLHttprequest object created under the hood.

Note: All of the above methods except the send() method support chaining. So, after calling send() chaining other methods is not possible. This implies that send() should be always used as the last method in the chain.

Global and static properties of the Slim_AJAX API

slimAjax.globals

Slim_AJAX API provides developers with a global object which will be always passed to onSuccess, and onLoad event handlers regardless of the top-level method i.e. request, get, and post. This global value will be passed to onSuccess, and onLoad event handlers as the last argument which we call it globals in examples for the sake of clarity.

Examples

1.

```javascript
slimAjax.globals = {
  mytext: 'Slim_AJAX API',
  myFunc: function(){
    //...
};

slimAjax.request(...).send(); 
slimAjax.get(...).send(); 
slimAjax.post(...).send(); 
```   

2.

```javascript
slimAjax.globals = "This text will be automatically passed to the main methods discussed above";

slimAjax.request(...).send(); 
slimAjax.get(...).send(); 
slimAjax.post(...).send(); 
```

Static properties

Every top-level method of Slim_AJAX API (i.e. request(), get(), and post()) supports a static property called defaults. This is a JavaScript object containing key-value pairs of "properties and handlers". The main point of such a static value is to share the most general settings on that particular top-level method for further use. So, after slimAjax.post.defaults = ... is done, any further use of post() top-level method will automatically set all the corresponding properties and/or handlers in the default object for that post() request.

Notes: 1. Although slimAjax.post.defaults = ... will set the default properties and handlers for any future post() call, any of those already set properties and handlers can be overwritten by using the API methods explained before.

  1. The defaults object is only meant for setting properties and handlers for the XMLHttprequest object. Event handlers for XMLHttprequest.upload has to be always set separately via setUploadHandlers() method.

Examples

1.

```javascript
slimAjax.get.defaults = {
  contentType: 'text/html',
  onSuccess: function(resObject, globals){
      //...
}
  
slimAjax.get(...).send();   
```   

2.

```javascript
slimAjax.post.defaults = {
  contentType: 'text/html',
  onSuccess: function(resObject, globals){
      //...
}

slimAjax.post(...).setPropsHandlers({ 		// overwriting the "contentType" which was set by defaults
  contentType: 'application/json'
}.send(data);   
```

resObject argument passed to the main handlers

Another object that is passed to onSuccess, onFailure, and onLoad handlers is the resObject. This is the object that contains main data of the response as well as two important methods of XMLHttprequest object which are mainly used after the response is ready. However, the resObject contains different data regarding the the handler to which it is passed as well as the value of the responseType property of the request.

resObject passed to onSuccess and onLoad handlers

Depending on the type of the responseType set for the AJAX request, the resObject contains different members:

responseTypemembers of resObject
"" or "text"response, responseText, getResponseHeader, getAllResponseHeaders
"document"response, responseXML, getResponseHeader, getAllResponseHeaders

resObject passed to onFailure handler

The members of passed to this event handler are:

members of resObjectCircumstance
status, getResponseHeader, getAllResponseHeadersif failure caused by the status other than 200
readyState, getResponseHeader, getAllResponseHeadersif failure caused by the readyState other than

Note: Neither globals nor resObject will be passed to other event handlers.

Defining event handlers

Examples

  1. slimAjax.get.defaults = {                 // Note the differences between these handlers in terms of arguments
      contentType: 'text/html',
      onSuccess: function(resObject, globals){
          //...
      }
      onFailure: function(resObject){
          //...
      }
      onLoad: function(event, resObject, globals){
          //...
      }
    }    
    slimAjax.get(...).send();   
  2. slimAjax.post(...).setPropsHnadlers({
      contentType: 'json',
      onSuccess: function(resObject, globals){
          //...
      }
      onFailure: function(resObject){
          //...
      }
      onLoad: function(event, resObject, globals){
          //...
      }
    }).send(data);   
  3.  
    slimAjax.request(...).setPropsHnadlers({
        contentType: 'form',
        onAbort: function(event){
          //...
      }
        onError: function(event){
          //...
      }
    }).send();

PROTIP: Among all events provided by Slim-AJAX API, only the onSuccess event can accept an array of functions. In that case, all those functions will be called in the order. Note that every function receives reObject and globals as if that function was the only assigned handler.

Example

slimAjax.request(...).setPropsHnadlers({
    contentType: 'form',
    onSuccess: [
      function(resObject, globals){
        //...
      },
      function(resObject, globals){
        //...
      },
      function(resObject, globals){
        //...
      }
    ]
}).send();   

Differences between top-level methods

slimAjax.request():

The general AJAX method which requires an http method as well as a url. The defaults object of this method is set to:

{
  contentType: "",
  responseType: "",
  overrideMimeTypeWith: null,
  timeout: 0,
  noCache: true,
  cors: false
}

slimAjax.get():

The convenience method fo http GET requests that require a url. The defaults object of this method is set to:

{
  contentType: "text/html",
  responseType: "text",
  timeout: 0,
  noCache: true,
  cors: true
}

slimAjax.post():

The convenience method fo http POST requests that require a url. The defaults object of this method is set to:

{
  contentType: "application/json",
  responseType: "json",
  timeout: 0,
  noCache: true,
  cors: true
}

Username & password in top-level methods

If for the AJAX request a basic authentication is required, slim_AJAX API will handle that automatically. For having that done, it is only necessary that NEITHER username NOR password be empty strings. Under this condition, Slim_AJAX API will automatically set the Authorization http header to the required value made out of the username and password.

Convenience shorthand strings for the content-types

Since setting Content-Type http header is such a common task in almost every AJAX request, there are a list of shorthand strings for the most frequently used http content types. However, these shorthand strings can only be used for setting contentType property via setPropsHandlers() method or inside the defaults object. The following table lists the available shorthand strings.

ShorthandCorresponding formal http MimeType
texttext/plain
htmltext/html
csstext/css
jsapplication/javascript
jsonapplication/json
formapplication/x-www-form-urlencoded
xmltext/xml
pdfapplication/pdf
jpegimage/jpeg
pngimage/png
gifimage/gif
svgimage/svg+xml
wmaaudio/x-ms-wma
mp4video/mp4
aiapplication/postscript
zipapplication/zip

Examples

  1. slimAjax.get.defaults = {
        contentType: "json",
        // ...
    }
    
    slimAjax.get(...).send();
  2. ```javascript
    slimAjax.post(...).setPropsHandlers({
        contentType: "form",
        // ...
    }
    ```

    Note: For setting http content-type to MimeType other than those in the above table, either the value of contentType property or Content-Type header must be explicitly set to that MimeType.

People

The author of Slim-AJAX is Pedram Emami.

License

MIT

2.0.0

4 years ago

1.1.70

4 years ago

1.1.68

4 years ago

1.1.64

4 years ago

1.1.6

4 years ago

1.1.5

4 years ago

1.1.4

4 years ago

1.1.2

4 years ago

1.0.2

4 years ago

1.0.1

4 years ago

1.0.0

4 years ago