Installations
npm install @codexteam/ajax
Developer
codex-team
Developer Guide
Module System
CommonJS
Min. Node Version
Typescript Support
No
Node Version
NPM Version
Statistics
33 Stars
73 Commits
11 Forks
8 Watching
8 Branches
6 Contributors
Updated on 16 Oct 2024
Bundle Size
14.33 kB
Minified
4.95 kB
Minified + Gzipped
Languages
JavaScript (75.95%)
HTML (24.05%)
Total Downloads
Cumulative downloads
Total Downloads
289,798
Last day
34.5%
639
Compared to previous day
Last week
24.9%
2,947
Compared to previous week
Last month
6.6%
11,752
Compared to previous month
Last year
72.8%
120,582
Compared to previous year
Daily Downloads
Weekly Downloads
Monthly Downloads
Yearly Downloads
AJAX
Module for async requests on a native JavaScript for a browser.
Package has been renamed from
codex.ajax
to@codexteam/ajax
Features
- zero-dependencies
- Promises based
- custom callback for a progress event
- easy-to-use
transport
method: ask user for a file(s) and upload it object
,FormData
orHTMLFormElement
data is being supported
Installation
You can install this package via NPM or Yarn
1npm install @codexteam/ajax
1yarn add @codexteam/ajax
Require package on your script page.
1const 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
1function successCallback(response) { 2 console.log('Response:', response.body); 3}
1function errorCallback(response) { 2 console.log(`Error code ${response.code}. Response:`, response.body); 3}
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
1ajax.get({ 2 url: '/getUserData', 3 data: { 4 user: 22 5 } 6}) 7 .then(successCallback) 8 .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
1ajax.post({ 2 url: '/saveArticle', 3 data: { 4 title: 'Awesome article', 5 text: 'will be written later', 6 isPublished: false 7 }, 8 9 /** 10 * Choose the content type you need 11 */ 12 // type: ajax.contentType.JSON /* (default) */ 13 // type: ajax.contentType.URLENCODED 14 // type: ajax.contentType.FORM 15}) 16 .then(successCallback) 17 .catch(errorCallback);
Example
To send any form you can pass HTMLFormElement as a data
to ajax.post()
.
1<form id="form-element"> 2 <input type="text" name="firstName" placeholder="First name"> 3 <input type="text" name="lastName" placeholder="Last name"> 4 <input type="file" name="profileImage" accept="image/*"> 5 <button onclick="event.preventDefault(); sendForm()">Send form</button> 6</form> 7 8<script> 9function sendForm() { 10 var form = document.getElementById('form-element'); 11 12 ajax.post({ 13 url:'/addUser', 14 data: form 15 }) 16 .then(successCallback) 17 .catch(errorCallback); 18} 19</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
1ajax.request({ 2 url: '/joinSurvey', 3 method: 'POST', 4 data: { 5 user: 22 6 } 7}) 8 .then(successCallback) 9 .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
1ajax.transport({ 2 url: '/uploadImage', 3 accept: 'image/*', 4 progress: function (percentage) { 5 document.title = `${percentage}%`; 6 }, 7 ratio: 95, 8 fieldName: 'image' 9}) 10 .then(successCallback) 11 .catch(errorCallback);
Example
One simple button for uploading files.
1<button onclick='ajax.transport({url: "/uploadFiles"}).then(successCallback).catch(errorCallback)'>Upload file<button>
ajax.selectFiles()
Ask user for a file (or multiple) and process it. FileList object will be returned in Promise.
param | type | default value | description |
---|---|---|---|
accept | string | null | Mime-types of accepted files |
multiple | boolean | false | Let user choose more than one file |
Example
1ajax.selectFiles({ 2 accept: 'image/*' 3}) 4 .then(successCallback);
Params
List of params, their types, descriptions and examples.
url string
Target page URL. By default current page url will be used.
/user/22
, /getPage
, /saveArticle
method string
Used in
ajax.request()
function only
Request method.
GET
, POST
Read more about available request methods methods on the page at developer.mozilla.org.
data object|FormData|HTMLFormElement
You can pass data as object
, FormData
or HTMLFormElement
.
Data will be encoded automatically.
1ajax.request({ 2 url: '/joinSurvey', 3 method: 'POST', 4 data: {user: 22} 5}) 6 .then(successCallback) 7 .catch(errorCallback);
1ajax.request({ 2 url: '/sendForm', 3 method: 'POST', 4 data: new FormData(document.getElementById('my-form')) 5}) 6 .then(successCallback) 7 .catch(errorCallback);
For
ajax.get()
you can passobject
data
1ajax.get({ 2 url: '/getUserData', 3 data: { 4 user: 22 5 } 6}) 7 .then(successCallback) 8 .catch(errorCallback);
is the same as
1ajax.get({ 2 url: '/getUserData?user=22' 3}) 4 .then(successCallback) 5 .catch(errorCallback);
For
ajax.transport()
should passobject
data if it is necessary
You can send additional data with files.
1ajax.transport({ 2 url: '/uploadImage', 3 accept: 'image/*', 4 data: { 5 visible: true, 6 caption: 'Amazing pic' 7 }, 8 fieldName: 'image' 9}) 10 .then(successCallback) 11 .catch(errorCallback);
type string
Specify the content type of data to be encoded (by ajax module) and sent.
You can get value for this param from ajax.contentType
object. Data will be encoded that way.
ajax.contentType | value |
---|---|
JSON | application/json; charset=utf-8 |
URLENCODED | application/x-www-form-urlencoded; charset=utf-8 |
FORM | multipart/form-data |
1const params = { 2 // ... 3 4 type: ajax.contentType.JSON 5 // type: ajax.contentType.URLENCODED 6 // type: ajax.contentType.FORM 7};
headers object
Object of custom headers which will be added to request.
1headers = { 2 'authorization': 'Bearer eyJhbGciJ9...TJVA95OrM7h7HgQ', 3 // ... 4}
progress function
Almost all requests have responses. To show a correct progress for a call we need to combine a request progress (uploading) and a response progress (downloading). This ajax module uses one progress
callback for it.
1/** 2 * @param {number} percentage - progress value from 0 to 100 3 */ 4var progressCallback = function progressCallback(percentage) { 5 document.title = `${percentage}%`; 6};
Check out ratio
param to show progress more accurate.
ratio number
Used with
progress
param
Value should be in the 0
-100
interval.
If you know that some requests may take more time than their responses or vice versa, you can set up a ratio
param and define a boundary between them on the progress bar.
For example if you want to show progress for a file uploading process, you know that uploading will take a much more time than downloading response, then pass bigger ratio (~95). When you want to download big file — use smaller ratio (~5).
accept string
Used in
ajax.transport()
function only
String of available types of files to be chosen by user.
*/*
— any files (default)
image/*
— only images
image/png, image/jpg, image/bmp
— restrict accepted types
Read more about MIME-types on the page at developer.mozilla.org.
multiple boolean
Used in
ajax.transport()
function only
false
by default. User can choose only one file.
If you want to allow user choose more than a one file to be uploaded, then pass a true
value.
fieldName string
Used in
ajax.transport()
function only
Name of data field with the file or array of files.
files
by default.
No vulnerabilities found.
Reason
no dangerous workflow patterns detected
Reason
no binaries found in the repo
Reason
license file detected
Details
- Info: project has a license file: LICENSE:0
- Info: FSF or OSI recognized license: MIT License: LICENSE:0
Reason
Found 4/7 approved changesets -- score normalized to 5
Reason
0 commit(s) and 0 issue activity found in the last 90 days -- score normalized to 0
Reason
detected GitHub workflow tokens with excessive permissions
Details
- Warn: no topLevel permission defined: .github/workflows/npm-publish.yml:1
- Info: no jobLevel write permissions found
Reason
dependency not pinned by hash detected -- score normalized to 0
Details
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/npm-publish.yml:12: update your workflow using https://app.stepsecurity.io/secureworkflow/codex-team/ajax/npm-publish.yml/master?enable=pin
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/npm-publish.yml:13: update your workflow using https://app.stepsecurity.io/secureworkflow/codex-team/ajax/npm-publish.yml/master?enable=pin
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/npm-publish.yml:26: update your workflow using https://app.stepsecurity.io/secureworkflow/codex-team/ajax/npm-publish.yml/master?enable=pin
- Info: 0 out of 3 GitHub-owned GitHubAction dependencies pinned
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
security policy file not detected
Details
- Warn: no security policy file detected
- Warn: no security file to analyze
- Warn: no security file to analyze
- Warn: no security file to analyze
Reason
project is not fuzzed
Details
- Warn: no fuzzer integrations found
Reason
branch protection not enabled on development/release branches
Details
- Warn: branch protection not enabled for branch 'master'
Reason
SAST tool is not run on all commits -- score normalized to 0
Details
- Warn: 0 commits out of 28 are checked with a SAST tool
Reason
43 existing vulnerabilities detected
Details
- Warn: Project is vulnerable to: GHSA-67hx-6x53-jw92
- Warn: Project is vulnerable to: GHSA-v88g-cgmw-v5xw
- Warn: Project is vulnerable to: GHSA-93q8-gq69-wqmw
- Warn: Project is vulnerable to: GHSA-qwcr-r2fm-qrc7
- Warn: Project is vulnerable to: GHSA-grv7-fg5c-xmjg
- Warn: Project is vulnerable to: GHSA-x9w5-v3q2-3rhw
- Warn: Project is vulnerable to: GHSA-pxg6-pf52-xh8x
- Warn: Project is vulnerable to: GHSA-3xgq-45jj-v275
- Warn: Project is vulnerable to: GHSA-gxpj-cx7g-858c
- Warn: Project is vulnerable to: GHSA-w573-4hg7-7wgq
- Warn: Project is vulnerable to: GHSA-wm7h-9275-46v2
- Warn: Project is vulnerable to: GHSA-434g-2637-qmqr
- Warn: Project is vulnerable to: GHSA-49q7-c7j4-3p7m
- Warn: Project is vulnerable to: GHSA-977x-g7h5-7qgw
- Warn: Project is vulnerable to: GHSA-f7q4-pwc6-w24p
- Warn: Project is vulnerable to: GHSA-fc9h-whq2-v747
- Warn: Project is vulnerable to: GHSA-rv95-896h-c2vc
- Warn: Project is vulnerable to: GHSA-qw6h-vgh9-j6wx
- Warn: Project is vulnerable to: GHSA-8r6j-v8pm-fqw3
- Warn: Project is vulnerable to: MAL-2023-462
- Warn: Project is vulnerable to: GHSA-pfrx-2q88-qq97
- Warn: Project is vulnerable to: GHSA-9c47-m6qq-7p4h
- Warn: Project is vulnerable to: GHSA-6c8f-qphg-qjgp
- Warn: Project is vulnerable to: GHSA-76p3-8jx3-jpfq
- Warn: Project is vulnerable to: GHSA-3rfm-jhwj-7488
- Warn: Project is vulnerable to: GHSA-hhq3-ff78-jv3g
- Warn: Project is vulnerable to: GHSA-952p-6rrq-rcjv
- Warn: Project is vulnerable to: GHSA-f8q6-p94x-37v3
- Warn: Project is vulnerable to: GHSA-vh95-rmgr-6w4m / GHSA-xvch-5gv4-984h
- Warn: Project is vulnerable to: GHSA-9wv6-86v2-598j
- Warn: Project is vulnerable to: GHSA-hrpp-h998-j3pp
- Warn: Project is vulnerable to: GHSA-c2qf-rxjj-qqgw
- Warn: Project is vulnerable to: GHSA-m6fv-jmcg-4jfg
- Warn: Project is vulnerable to: GHSA-h9rv-jmmf-4pgx
- Warn: Project is vulnerable to: GHSA-hxcc-f52p-wc94
- Warn: Project is vulnerable to: GHSA-cm22-4g7w-348p
- Warn: Project is vulnerable to: GHSA-4g88-fppr-53pp
- Warn: Project is vulnerable to: GHSA-4jqc-8m5r-9rpr
- Warn: Project is vulnerable to: GHSA-f5x3-32g6-xq36
- Warn: Project is vulnerable to: GHSA-4wf5-vphf-c2xc
- Warn: Project is vulnerable to: GHSA-332q-7ff2-57h2
- Warn: Project is vulnerable to: GHSA-c4w7-xm78-47vh
- Warn: Project is vulnerable to: GHSA-p9pc-299p-vxgp
Score
3
/10
Last Scanned on 2024-11-25
The Open Source Security Foundation is a cross-industry collaboration to improve the security of open source software (OSS). The Scorecard provides security health metrics for open source projects.
Learn More