Class: Ajax

ML. Ajax


new Ajax(params)

  • Making requests with ease.
  • Supports GET, POST, PUT, DELETE, JSONP methods.
  • When using JSONP request, you need to setup a global callback function and pass in the function name as a string in jsonpCallback.
  • See it in action + some notes! 😀
Parameters:
Name Type Description
params Object

Configuration settings.

Properties
Name Type Argument Default Description
method String <optional>
GET

The type of request.

url String

Request URL.

headers Object <optional>
{'Content-type': 'application/x-www-form-urlencoded'}

Adds headers to your request: request.setRequestHeader(key, value)

responseType String <optional>
text

Format of the response. info

cors Boolean <optional>
false

Cross domain request.

data Object | String <optional>
null

Data to send with the request.

jsonpCallback String

The name of the function for JSONP callback.

success function

If the request is successful. XHR is returned.

error function

If the request errors out. XHR is returned.

Examples

GET Request

new ML.Ajax({
  responseType: 'json',
  url: 'https://reqres.in/api/users/2',
  success: function(xhr) {
    console.log(xhr.response.data);
  },
  error: function(xhr) {
    console.log('ERROR', xhr);
  }
});

POST Request

new ML.Ajax({
  url: 'https://reqres.in/api/users',
  method: 'POST',
  responseType: 'json',
  data: {
    name: 'john smith',
    age: 22
  },
  success: function(xhr) {
    console.log(xhr.response);
  },
  error: function(xhr) {
    console.log('ERROR', xhr);
  }
});

JSONP Request

var callbackFunction = function(response) {
  console.log(response);
};

new ML.Ajax({
  url: 'https://jsfiddle.net/echo/jsonp',
  method: 'JSONP',
  data: {
    name: 'john smith',
    age: 22
  },
  jsonpCallback: 'callbackFunction'
});

Members


xhr

Returns the XHR.