Module for async requests on a native JavaScript for a browser.
Package has been renamed from
codex.ajaxto@codexteam/ajax
Features
- zero-dependencies
- Promises based
- custom callback for a progress event
- easy-to-use
transportmethod: ask user for a file(s) and upload it object,FormDataorHTMLFormElementdata is being supported
Installation
You can install this package via NPM or Yarn
npm install @codexteam/ajax
yarn add @codexteam/ajax
Require package on your script page.
const ajax = require('@codexteam/ajax');
Also you can get this module from CDN or download a bundle file and use it locally.
Usage
There are a few public functions available to be used by user. All of them return Promise.
- ajax.get() — wrapper for a GET request
- ajax.post() — wrapper for a POST request
- ajax.request() — main function to make requests (GET, POST, HEAD, PUT, DELETE, ...)
- ajax.transport() — ask user for a file and upload it
- ajax.selectFiles() — ask user for a file and return files array
Callbacks format
successCallback and errorCallback have the same input object response as a param.
| param | type | description |
|---|---|---|
| response.body | object or string |
Response body parsed JSON or a string |
| response.code | number |
Response code |
| response.headers | object |
Response headers object |
Example
function successCallback(response) { console.log('Response:', response.body); }
function errorCallback(response) { console.log(`Error code ${response.code}. Response:`, response.body); }
ajax.get()
Wrapper for a GET request over an ajax.request() function.
| param | type | default value | description |
|---|---|---|---|
| url | string |
'' |
Request URL |
| data | object |
null |
Data to be sent |
| headers | object |
null |
Custom headers object |
| progress | function |
(percentage) => {} |
Progress callback |
| ratio | number |
90 |
Max % of bar for uploading progress |
| beforeSend | function |
null |
Fire callback before sending a request |
Example
ajax.get({ url: '/getUserData', data: { user: 22 } }) .then(successCallback) .catch(errorCallback);
ajax.post()
Wrapper for a POST request over an ajax.request() function.
| param | type | default value | description |
|---|---|---|---|
| url | string |
'' |
Request URL |
| data | object, FormData or HTMLFormElement |
null |
Data to be sent |
| type | string |
ajax.contentType.JSON |
Header from ajax.contentType object |
| headers | object |
null |
Custom headers object |
| progress | function |
(percentage) => {} |
Progress callback |
| ratio | number |
90 |
Max % of bar for uploading progress |
| beforeSend | function |
null |
Fire callback before sending a request |
Example
Simple POST request
ajax.post({ url: '/saveArticle', data: { title: 'Awesome article', text: 'will be written later', isPublished: false }, /** * Choose the content type you need */ // type: ajax.contentType.JSON /* (default) */ // type: ajax.contentType.URLENCODED // type: ajax.contentType.FORM }) .then(successCallback) .catch(errorCallback);
Example
To send any form you can pass HTMLFormElement as a data to ajax.post().
<form id="form-element"> <input type="text" name="firstName" placeholder="First name"> <input type="text" name="lastName" placeholder="Last name"> <input type="file" name="profileImage" accept="image/*"> <button onclick="event.preventDefault(); sendForm()">Send form</button> </form> <script> function sendForm() { var form = document.getElementById('form-element'); ajax.post({ url:'/addUser', data: form }) .then(successCallback) .catch(errorCallback); } </script>
ajax.request()
Main function for all requests.
| param | type | default value | description |
|---|---|---|---|
| url | string |
'' |
Request URL |
| method | string |
'GET' |
Request method |
| data | object |
null |
Data to be sent |
| headers | object |
null |
Custom headers object |
| progress | function |
(percentage) => {} |
Progress callback |
| ratio | number |
90 |
Max % of bar for uploading progress |
| beforeSend | function |
(files) => {} |
Fire callback before sending a request |
Example
ajax.request({ url: '/joinSurvey', method: 'POST', data: { user: 22 } }) .then(successCallback) .catch(errorCallback);
ajax.transport()
This is a function for uploading files from client.
User will be asked to choose a file (or multiple) to be uploaded. Then FormData object will be sent to the server via ajax.post() function.
| param | type | default value | description |
|---|---|---|---|
| url | string |
'' |
Request URL |
| data | object |
null |
Additional data to be sent |
| accept | string |
null |
Mime-types of accepted files |
| multiple | boolean |
false |
Let user choose more than one file |
| fieldName | string |
'files' |
Name of field in form with files |
| headers | object |
null |
Custom headers object |
| progress | function |
(percentage) => {} |
Progress callback |
| ratio | number |
90 |
Max % of bar for uploading progress |
| beforeSend | function |
(files) => {} |
Fire callback with chosen files before sending |
Example
ajax.transport({ url: '/uploadImage', accept: 'image/*', progress: function (percentage) { document.title = `${percentage}%`; }, ratio: 95, fieldName: 'image' }) .then(successCallback) .catch(errorCallback);
Example
One simple button for uploading files.