Skip to content
Promise based AJAX library
JavaScript Shell
Branch: master
Clone or download
Fetching latest commit…
Cannot retrieve the latest commit at this time.
Type Name Latest commit message Commit time
Failed to load latest commit information.


Build Status

pajax is a library for promise based XHR request. It is very close to the Fetch standard.



jspm install pajax
import Pajax from 'pajax';


npm install pajax/pajax
var Pajax = require('pajax');


Download dist/pajax.js or install via bower

bower install pajax
<script src="/url/to/pajax.js"></script>

Quick start

Pajax provides methods to perform http requests. Each method returns a promise which resolves in a response object.

// GET
Pajax.get(url, opts)
       res: // the response
     }, res=>{
       // called on status or network errors
       res.ok;    // false
       res.error; // the error

// POST, reqBody, opts)
       res: // the response
     }, res=>{
       // called on network and status errors
       res.ok;    // false
       res.error; // the error

requests methods

  • fetch(url, opts)
  • get(url, opts)
  • delete(url, opts)
  • post(url, reqBody, opts)
  • put(url, reqBody, opts)
  • patch(url, reqBody, opts)

The response object

A request is resolved with a response object. You can call one of the following methods to extract the body from a response:

  • text()
  • json()
  • blob()
  • arrayBuffer()
  • formData()
Pajax.get(url, opts)
       body; // parsed json as javascript object

If you just want to GET some data an do not care about the response object, you can use the following methods:

  • getText(url, opts)
  • getJSON(url, opts)
  • getBlob(url, opts)
  • getArrayBuffer(url, opts)
  • getFormData(url, opts)
Pajax.getJSON(url, opts)
       body; // parsed json as javascript object


  • url (string) - the URL for this request
  • opts (object) - set of key/value pairs to configure the ajax requests
  • reqBody (mixed) - The body you want to add to your request

Options (opts)

The options are very similar to the Fetch options.

  • cache (string) - default, no-cache - no-cache will add a no-cache request header
  • contentType (string) - the content type of the data sent to the server
  • headers (object) - set of key/value pairs that are added to the request header
  • progress (function) - callback for the the upload progress
  • method (string) - GET, POST, PUT, PATCH, DELETE, HEAD
  • timeout (integer) - number of milliseconds to wait for a response
  • credentials (string) - same-origin, include - Use include to send cookies in a CORS request.
  • body (mixed) - The body you want to add to your request
  • noStatusCheck (boolean) - Does not reject on erroneous status codes if set to true


fetch does not reject on HTTP status error codes (non 2xx). Use the Pajax.checkStatus handler to do so.

Pajax.fetch(url, opts)
       res.ok:   // true
     }, res=>{
       // called on status or network errors
       res.error; // the error

Advanced usage

Pajax instances

A Pajax instance allows you to store default options for requests.

let pajax = new Pajax({headers: {'foo': 'bar'});

// does not include foo header

// includes foo header


A Request instance represents a preconfigured request to a specific resource. The constructor has the same signature as the fetch method.

let req = new Pajax.Request(url, opts);

Request objects can also be created with the request() method on a pajax instance. They inherit the default options of the pajax instance.

let pajax = new Pajax({cache: 'no-cache'});
let req = pajax.request(url, {contentType: 'application/json'});

req.send().then(...); // cache = no-cache, contentType = application/json

Besides req.send(request) you can make use of the other request methods

pajax.request(url, opts).get().then(res=>{ ... })

pajax.request(url, opts).getJSON().then(body=>{ ... })

pajax.request(url, opts).post().then(res=>{ ... })


A fetch(), get(), post(), etc. is resolved with a response object. Response objects are described here.

In addition to text(), json(), blob() etc, the the pajax response object has an auto() method. auto() will try to infer the body based on the content type of the response. e.g. a json response will yield a js object, whereas text will yield a string.

  body; // js object

Operators on request/pajax instances

Operators will spawn a new request/pajax instance inheriting all the options of the source

let pajax = new Pajax().JSON().noCache();

     .header('Authentication', token)
        // Request to /url as POST with content-type/accept=application/json, no-cache, authentication headers and data attached as body

Operators on pajax and request instances:

- accept(type)                      // Sets the accept header
- header(object)                    // headers via object
- header(string, string)            // header via key-value
- noCache()                         // Sets cache to `no-cache`
- withCredentials()                 // Sets credentials to `include`
- type(type)                        // Sets the content header
- onProgress(callback)              // Progress callback
- setTimeout(number)                // Sets the timeout

Operators only on request instances

- as(method)                        // Sets the http method
- noCheck()                         // Sets noStatusCheck to true
- attach(body)                      // Sets the body

Operators only on pajax instances

- JSON()                            // Sets the accept header and content-type to `application/json`
- URLEncoded()                      // Sets the content-type to `application/x-www-form-urlencoded`
- before(callback)                  // See transformation operators
- after(callback)                   // See transformation operators

Extending pajax

Pajax provides some helpers for common tasks such as getting or posting data, but can easily be extended.

Let's add a method for an authenticated POST in this example:

class MyPajax extends Pajax {
  authPost(url, token, body) {
    return this.request(url)
               .header('Authorization', token)

import auth from 'auth';
let pajax = new MyPajax();
pajax.authPost(url, auth.token, {foo:1}).then(...);

Customizing the Pajax classes

See the following code for a more advanced example

// Our authenticator
let auth = {token: 'g54gsfdgw34qj*9764w3'};

// Custom request class
let MyRequest = class extends Pajax.Request {
  // Operator for adding the auth token to request header
  authenticate() {
    return this.header('authorization', `Bearer ${auth.token}`);

// Custom response class
let MyResponse = class extends Pajax.Response {
  // Checks if we are authenticated
  get isAuthenticated() {
    return this.headers.get('X-authentication-level']) > 0;

// Custom pajax class
class MyPajax extends Pajax {

  constructor(init) {
    this.super(init, {
      // Provide some class defaults
      Request: MyRequest,   // Set Request class
      Response: MyResponse, // Set Response class
      cache: 'no-cache'     // Disables caching by default

  // Add new method for authenticated GETs
  authget(...args) {
    return this.request(...args)
  // Override delete()
  // All DELETE requests should be authenticated
  delete(...args) {
    return this.request(...args)

let pajax = new MyPajax();

// authorization token added by authget()
     .then(res => { ... });

// no authorization token added
     .then(res => { ... });

// authorization token added manually
     .authenticate() // Adds bearer token to request
     .then(res => { ... });

// token added by delete() override
     .then(res => { ... });

Transformation operators

Use the following operators to transform a request or response

let pajax = new Pajax()
       req; // request object
       // do some stuff before a request is sent
       return { // returned options will be utilized in the request
         cache: 'no-cache'
       req; // request object
       // do more stuff before a request is sent
       res; // response object
       // do some stuff after a request

// before/after handlers are called
You can’t perform that action at this time.