Ajax
Ajax module in Vanilla JS
You can use this module with AMD, CommonJS or just like a method of window
object!
Installation
Bower
You can install via bower:
bower install ajax
Manual installation
Just download dist/ajax.min.js
file, and add dist/ajax.min.js
on your HTML file:
<script src="js/ajax.min.js"></script>
CommonJS (via NPM)
npm i --save @fdaciuk/ajax
CDN
You may use a CDN to get the latest version.
CDNJS:
https://cdnjs.com/libraries/fdaciuk-ajax
GitHub:
Or you may just add the following line to your HTML file:
<script src="//cdn.rawgit.com/fdaciuk/ajax/v0.2.1/dist/ajax.min.js"></script>
Usage
AMD
define([ 'Ajax' ], function( Ajax ) {
var ajax = new Ajax();
...
});
CommonJS
var Ajax = require( '@fdaciuk/ajax' );
var ajax = new Ajax();
...
Method of window
object
var ajax = new window.Ajax();
or
var ajax = new Ajax();
Note
Ajax
constructor is deprecated and will be removed in v2.0.0
. Use ajax()
function (lowecase version) without new
keyword instead.
Enjoy ;)
Signature
ajax([options])
Options
Optional object with request options. See all options below.
headers
An object when key
is a header name, and value
is a header value.
ajax({
headers: {
'content-type': 'application/json',
'x-access-token': '123@abc'
}
})
If content-type
is not passed, application/x-www-form-urlencoded
will be used.
Methods
get(url)
Get data as a JSON object.
ajax().get( '/api/users' );
ajax().get( '/api/users/john' );
post(url, [ data ])
Save a new register or update part of this one.
ajax().post( '/api/users', { slug: 'john' });
var request = ajax({
headers: {
'x-access-token': '123@abc'
}
});
request.post('/login', { username: 'user', password: 'b4d45$' });
put(url, [ data ])
Update an entire register.
ajax().put( '/api/users', { slug: 'john', age: 37 });
delete(url, [ data ])
Delete a register.
ajax().delete( '/api/users', { id: 1 });
Return methods
then(response, xhrObject)
Promise that returns if the request was successful.
ajax().get( '/api/users' ).then(function( response, xhr ) {
});
catch(response, xhrObject)
Promise that returns if the request has an error.
ajax().post( '/api/users', { slug: 'john' }).catch(function( response, xhr ) {
});
always(response, xhrObject)
That promise always returns, independent if the status is done
or error
.
ajax().post( '/api/users', { slug: 'john' }).always(function( response, xhr ) {
});
Deprecated return methods
done(response, xhrObject)
Promise that returns if the request was successful.
done
is deprecated. Use then
instead.
ajax().get( '/api/users' ).done(function( response, xhr ) {
});
error(response, xhrObject)
Promise that returns if the request has an error.
error
is deprecated. Use catch
instead.
ajax().post( '/api/users', { slug: 'john' }).error(function( response, xhr ) {
});
Contributing
Check CONTRIBUTING.md
Code coverage and Statistics
https://github.com/reportz/ajax
License
MIT © Fernando Daciuk