promise-ajax

A simple Ajax(jquery) with promises(rsvp)

Usage no npm install needed!

<script type="module">
  import promiseAjax from 'https://cdn.skypack.dev/promise-ajax';
</script>

README

promise-ajax

A simple ajax(jquery) with promises(rsvp)

Why?

Because I(we ?) need a nice interface to do REST ajax calls with (real?) promises.

Why rsvp?

  • Because I have used it.
  • Because it's used on Ember?(that's a really good point :D )
  • Becuase it uses a real emplementation of Promise/A

Why jquery?

Because it has cross browser ajax support.

Installation

~$ npm install promise-ajax --save

Tests

Clone repo then:

~$ npm install
~$ npm test

Usage

    var API_URL = 'http://localhost:3000/';
    var api = require('promise-ajax')(API_URL);  

    var beforeSend = function(xhr){
        console.log(xhr); // xhr comes from jquery request object
        xhr.setRequestHeader('my-header', 'some-value');
    };

    var success = functiion(data){
        console.log('Success callback', data);
    };
  
    var error = functiion(data){
        console.log('Success callback', data);
    };
    api['REST_METHOD'](resource, data, beforeSend).then(successCallback, errorCallback);
  • GET
    // GET http://localhost:3000/products
    api.get('products').then(success, error);
    
    // GET http://localhost:3000/products/:id
    api.get('products', {id: id}).then(success, error);
  
    // Set some header before send
    api.get('products', {}, beforeSend).then(success, error);
  • POST
    var data = {name: 'some', description: 'foobar'};
    
    // POST http://localhost:3000/products
    api.post('products', data).then(success, error);

    // POST http://localhost:3000/products/:id
    data.id = 1;
    api.post('products', data).then(success, error);

    // Set some header before send
    api.post('products', data, beforeSend).then(success, error);
  • PUT
    var data = {id: 1, name: 'some', description: 'foobar'};
    
    // PUT http://localhost:3000/products/:id
    api.put('products', data).then(success, error);

    // Set some header before send
    api.put('products', data, beforeSend).then(success, error);
  • DELETE

you must use api.destroy do not try to use api.delete

    var data = {id: 1};
    
    // DELETE http://localhost:3000/products/:id
    api.destroy('products', data).then(success, error);

    // Set some header before send
    api.destroy('products', data, beforeSend).then(success, error);

TODO:

  • Build custmon jquery to use only xhr.