{"id":18887992,"url":"https://github.com/codex-team/ajax","last_synced_at":"2025-04-14T23:07:48.850Z","repository":{"id":43016901,"uuid":"108484215","full_name":"codex-team/ajax","owner":"codex-team","description":"Just another AJAX requests helper","archived":false,"fork":false,"pushed_at":"2023-11-10T06:59:55.000Z","size":905,"stargazers_count":34,"open_issues_count":11,"forks_count":12,"subscribers_count":7,"default_branch":"master","last_synced_at":"2025-03-28T11:06:30.976Z","etag":null,"topics":["ajax","file-upload","uploader"],"latest_commit_sha":null,"homepage":"","language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/codex-team.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null}},"created_at":"2017-10-27T01:28:12.000Z","updated_at":"2024-12-19T14:04:54.000Z","dependencies_parsed_at":"2024-01-23T21:15:55.954Z","dependency_job_id":"6959ff69-804b-4b3b-8361-26d75d187a22","html_url":"https://github.com/codex-team/ajax","commit_stats":null,"previous_names":["codex-js-modules/ajax"],"tags_count":2,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/codex-team%2Fajax","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/codex-team%2Fajax/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/codex-team%2Fajax/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/codex-team%2Fajax/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/codex-team","download_url":"https://codeload.github.com/codex-team/ajax/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":248360120,"owners_count":21090654,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["ajax","file-upload","uploader"],"created_at":"2024-11-08T07:41:05.540Z","updated_at":"2025-04-14T23:07:48.830Z","avatar_url":"https://github.com/codex-team.png","language":"JavaScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# AJAX\n\nModule for async requests on a native JavaScript for a browser.\n\n\u003e Package has been renamed from `codex.ajax` to `@codexteam/ajax`\n\n## Features\n\n- zero-dependencies\n- Promises based\n- custom callback for a **progress** event\n- easy-to-use `transport` method: ask user for a file(s) and upload it\n- `object`, `FormData` or `HTMLFormElement` data is being supported\n\n## Installation\n\nYou can install this package via NPM or Yarn\n\n```shell\nnpm install @codexteam/ajax\n```\n\n```shell\nyarn add @codexteam/ajax\n```\n\nRequire package on your script page.\n\n```javascript\nconst ajax = require('@codexteam/ajax');\n```\n\nAlso you can get this module [from CDN](https://unpkg.com/@codexteam/ajax) or download a [bundle file](dist/main.js) and use it locally.\n\n## Usage\n\nThere are a few public functions available to be used by user. All of them return Promise.\n\n- [ajax.get()](#ajaxget) — wrapper for a GET request\n- [ajax.post()](#ajaxpost) — wrapper for a POST request\n- [ajax.request()](#ajaxrequest) — main function to make requests (GET, POST, HEAD, PUT, DELETE, ...)\n- [ajax.transport()](#ajaxtransport) — ask user for a file and upload it\n- [ajax.selectFiles()](#ajaxselectfiles) — ask user for a file and return files array\n\n### Callbacks format\n\n`successCallback` and `errorCallback` have the same input object `response` as a param.\n\n| param            | type                  | description                           | \n| ---------------- | --------------------- | ------------------------------------- |\n| response.body    | `object` or `string`  | Response body parsed JSON or a string |\n| response.code    | `number`              | Response code                         |\n| response.headers | `object`              | Response headers object               |\n\n#### Example\n\n```javascript\nfunction successCallback(response) {\n  console.log('Response:', response.body);\n}\n```\n\n```javascript\nfunction errorCallback(response) {\n  console.log(`Error code ${response.code}. Response:`, response.body);\n}\n```\n\n### ajax.get()\n\nWrapper for a GET request over an `ajax.request()` function.\n\n| param      | type       | default value        | description                            | \n| ---------- | ---------- | -------------------- | -------------------------------------- |\n| url        | `string`   | `''`                 | Request URL                            |\n| data       | `object`   | `null`               | Data to be sent                        |\n| headers    | `object`   | `null`               | Custom headers object                  |\n| progress   | `function` | `(percentage) =\u003e {}` | Progress callback                      |\n| ratio      | `number`   | `90`                 | Max % of bar for uploading progress    |\n| beforeSend | `function` | `null`               | Fire callback before sending a request | \n\n#### Example\n\n```javascript\najax.get({\n url: '/getUserData',\n data: {\n   user: 22\n }\n})\n  .then(successCallback)\n  .catch(errorCallback);\n```\n\n### ajax.post()\n\nWrapper for a POST request over an `ajax.request()` function.\n\n| param      | type                                      | default value           | description                            | \n| ---------- | ----------------------------------------- | ----------------------- | -------------------------------------- |\n| url        | `string`                                  | `''`                    | Request URL                            |\n| data       | `object`, `FormData` or `HTMLFormElement` | `null`                  | Data to be sent                        |\n| type       | `string`                                  | `ajax.contentType.JSON` | Header from `ajax.contentType` object  |\n| headers    | `object`                                  | `null`                  | Custom headers object                  |\n| progress   | `function`                                | `(percentage) =\u003e {}`    | Progress callback                      |\n| ratio      | `number`                                  | `90`                    | Max % of bar for *uploading* progress  |\n| beforeSend | `function`                                | `null`                  | Fire callback before sending a request | \n\n#### Example\n\nSimple POST request\n\n```javascript\najax.post({\n  url: '/saveArticle',\n  data: {\n    title: 'Awesome article',\n    text: 'will be written later',\n    isPublished: false\n  },\n  \n  /**\n   * Choose the content type you need\n   */\n  // type: ajax.contentType.JSON /* (default) */ \n  // type: ajax.contentType.URLENCODED\n  // type: ajax.contentType.FORM\n})\n  .then(successCallback)\n  .catch(errorCallback);\n```\n\n#### Example \n\nTo send any form you can pass HTMLFormElement as a `data` to `ajax.post()`.\n\n```html\n\u003cform id=\"form-element\"\u003e\n    \u003cinput type=\"text\" name=\"firstName\" placeholder=\"First name\"\u003e\n    \u003cinput type=\"text\" name=\"lastName\" placeholder=\"Last name\"\u003e\n    \u003cinput type=\"file\" name=\"profileImage\" accept=\"image/*\"\u003e\n    \u003cbutton onclick=\"event.preventDefault(); sendForm()\"\u003eSend form\u003c/button\u003e\n\u003c/form\u003e\n\n\u003cscript\u003e\nfunction sendForm() {\n  var form = document.getElementById('form-element');\n  \n  ajax.post({\n    url:'/addUser',\n    data: form\n  })\n    .then(successCallback)\n    .catch(errorCallback);\n} \n\u003c/script\u003e\n```\n\n### ajax.request()\n\nMain function for all requests.\n\n| param      | type       | default value        | description                            | \n| ---------- | -----------| -------------------- | -------------------------------------- |\n| url        | `string`   | `''`                 | Request URL                            |\n| method     | `string`   | `'GET'`              | Request method                         |\n| data       | `object`   | `null`               | Data to be sent                        |\n| headers    | `object`   | `null`               | Custom headers object                  |\n| progress   | `function` | `(percentage) =\u003e {}` | Progress callback                      |\n| ratio      | `number`   | `90`                 | Max % of bar for *uploading* progress  |\n| beforeSend | `function` | `(files) =\u003e {}`      | Fire callback before sending a request |\n\n#### Example\n\n```javascript\najax.request({\n  url: '/joinSurvey',\n  method: 'POST',\n  data: {\n    user: 22\n  }\n})\n  .then(successCallback)\n  .catch(errorCallback);\n```\n\n### ajax.transport()\n\nThis is a function for uploading files from client. \n\nUser 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.\n\n| param      | type       | default value        | description                                    | \n| ---------- | ---------- | -------------------- | ---------------------------------------------- |\n| url        | `string`   | `''`                 | Request URL                                    |\n| data       | `object`   | `null`               | Additional data to be sent                     |\n| accept     | `string`   | `null`               | Mime-types of accepted files                   |\n| multiple   | `boolean`  | `false`              | Let user choose more than one file             |\n| fieldName  | `string`   | `'files'`            | Name of field in form with files               |\n| headers    | `object`   | `null`               | Custom headers object                          |\n| progress   | `function` | `(percentage) =\u003e {}` | Progress callback                              |\n| ratio      | `number`   | `90`                 | Max % of bar for *uploading* progress          |\n| beforeSend | `function` | `(files) =\u003e {}`      | Fire callback with chosen files before sending |\n\n#### Example\n\n```javascript\najax.transport({\n  url: '/uploadImage',\n  accept: 'image/*',\n  progress: function (percentage) {\n    document.title = `${percentage}%`;\n  },\n  ratio: 95,\n  fieldName: 'image'\n})\n  .then(successCallback)\n  .catch(errorCallback);\n```\n\n#### Example\n\nOne simple button for uploading files.\n\n```html\n\u003cbutton onclick='ajax.transport({url: \"/uploadFiles\"}).then(successCallback).catch(errorCallback)'\u003eUpload file\u003cbutton\u003e\n```\n\n### ajax.selectFiles()\n\nAsk user for a file (or multiple) and process it. FileList object will be returned in Promise.\n\n| param      | type       | default value        | description                                    | \n| ---------- | ---------- | -------------------- | ---------------------------------------------- |\n| accept     | `string`   | `null`               | Mime-types of accepted files                   |\n| multiple   | `boolean`  | `false`              | Let user choose more than one file             |\n\n#### Example\n\n```javascript\najax.selectFiles({\n  accept: 'image/*'\n})\n  .then(successCallback);\n```\n\n## Params\n\nList of params, their types, descriptions and examples.\n\n* [url](#url)\n* [method](#method)\n* [data](#data)\n* [type](#type)\n* [beforeSend](#beforesend)\n* [headers](#headers)\n* [progress](#progress)\n* [ratio](#ratio)\n* [accept](#accept)\n* [multiple](#multiple)\n* [fieldName](#fieldname)\n\n### url `string`\n\nTarget page URL. By default current page url will be used.  \n\n`/user/22`, `/getPage`, `/saveArticle`\n\n### method `string`\n\n\u003e Used in `ajax.request()` function only\n\nRequest method.\n\n`GET`, `POST`\n\nRead more about available request methods methods on the [page](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods) at developer.mozilla.org.\n\n### data `object|FormData|HTMLFormElement`\n\nYou can pass data as `object`, `FormData` or `HTMLFormElement`.\n\nData will be encoded automatically.\n\n```javascript\najax.request({\n  url: '/joinSurvey',\n  method: 'POST',\n  data: {user: 22}\n})\n  .then(successCallback)\n  .catch(errorCallback);\n```\n\n```javascript\najax.request({\n  url: '/sendForm',\n  method: 'POST',\n  data: new FormData(document.getElementById('my-form'))\n})\n  .then(successCallback)\n  .catch(errorCallback);\n```\n\n\u003e For `ajax.get()` you can pass `object` data\n\n\n```javascript\najax.get({\n  url: '/getUserData',\n  data: {\n    user: 22\n  }\n})\n  .then(successCallback)\n  .catch(errorCallback);\n```\n\nis the same as\n\n```javascript\najax.get({\n  url: '/getUserData?user=22'\n})\n  .then(successCallback)\n  .catch(errorCallback);\n```\n\n\u003e For `ajax.transport()` should pass `object` data if it is necessary\n\nYou can send additional data with files.\n\n```javascript\najax.transport({\n  url: '/uploadImage',\n  accept: 'image/*',\n  data: {\n    visible: true,\n    caption: 'Amazing pic'\n  },\n  fieldName: 'image'\n})\n  .then(successCallback)\n  .catch(errorCallback);\n```\n\n### type `string`\n\nSpecify the content type of data to be encoded (by ajax module) and sent.\n\nYou can get value for this param from `ajax.contentType` object. Data will be encoded that way.\n\n| ajax.contentType | value                                              |\n| ---------------- | -------------------------------------------------- |\n| JSON             | `application/json; charset=utf-8`                  |\n| URLENCODED       | `application/x-www-form-urlencoded; charset=utf-8` |\n| FORM             | `multipart/form-data`                              |\n\n```javascript\nconst params = {\n  // ...\n  \n  type: ajax.contentType.JSON \n  // type: ajax.contentType.URLENCODED\n  // type: ajax.contentType.FORM\n};\n```\n\n### headers `object`\n\nObject of custom headers which will be added to request.\n\n```javascript\nheaders = {\n  'authorization': 'Bearer eyJhbGciJ9...TJVA95OrM7h7HgQ',\n  // ...\n}\n```\n\n### progress `function`\n\nAlmost 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.\n\n```javascript\n/**\n * @param {number} percentage - progress value from 0 to 100 \n */\nvar progressCallback = function progressCallback(percentage) {  \n    document.title = `${percentage}%`;\n};\n```\n\nCheck out `ratio` param to show progress more accurate.\n\n### ratio `number`\n\n\u003e Used with `progress` param\n\nValue should be in the `0`-`100` interval.\n\nIf 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.\n\nFor 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). \n\n![](./assets/ratio-example.gif)\n\n### accept `string`\n\n\u003e Used in `ajax.transport()` function only\n\nString of available types of files to be chosen by user.\n\n`*/*` — any files (default)\n\n`image/*` — only images \n\n`image/png, image/jpg, image/bmp` — restrict accepted types \n\nRead more about MIME-types on the [page](https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types) at developer.mozilla.org.\n\n### multiple `boolean`\n\n\u003e Used in `ajax.transport()` function only\n\n`false` by default. User can choose only one file.\n\nIf you want to allow user choose more than a one file to be uploaded, then pass a `true` value.\n\n### fieldName `string`\n\n\u003e Used in `ajax.transport()` function only\n\nName of data field with the file or array of files.\n\n`files` by default. \n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fcodex-team%2Fajax","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fcodex-team%2Fajax","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fcodex-team%2Fajax/lists"}