{"id":22443091,"url":"https://github.com/riversun/ajax-client","last_synced_at":"2025-06-12T16:39:36.367Z","repository":{"id":33606898,"uuid":"159923750","full_name":"riversun/ajax-client","owner":"riversun","description":"A simple ajax client with jQuery like ajax API for javascript","archived":false,"fork":false,"pushed_at":"2023-03-15T02:09:45.000Z","size":1247,"stargazers_count":8,"open_issues_count":7,"forks_count":4,"subscribers_count":1,"default_branch":"master","last_synced_at":"2025-05-12T07:59:03.539Z","etag":null,"topics":["ajax","ajax-client","jquery","xmlhttprequest"],"latest_commit_sha":null,"homepage":"","language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/riversun.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2018-12-01T08:18:09.000Z","updated_at":"2024-03-25T05:08:11.000Z","dependencies_parsed_at":"2024-06-19T02:45:56.065Z","dependency_job_id":"6e24b4c6-c2b2-4056-95cc-422db73a96f2","html_url":"https://github.com/riversun/ajax-client","commit_stats":{"total_commits":55,"total_committers":2,"mean_commits":27.5,"dds":"0.054545454545454564","last_synced_commit":"d2ecb41be1dadac0a769f89d3146a5bf3388ee05"},"previous_names":[],"tags_count":4,"template":false,"template_full_name":null,"purl":"pkg:github/riversun/ajax-client","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/riversun%2Fajax-client","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/riversun%2Fajax-client/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/riversun%2Fajax-client/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/riversun%2Fajax-client/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/riversun","download_url":"https://codeload.github.com/riversun/ajax-client/tar.gz/refs/heads/master","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/riversun%2Fajax-client/sbom","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":259503193,"owners_count":22867948,"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","ajax-client","jquery","xmlhttprequest"],"created_at":"2024-12-06T02:22:27.817Z","updated_at":"2025-06-12T16:39:36.344Z","avatar_url":"https://github.com/riversun.png","language":"JavaScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# ajax-client\n[![npm version](https://badge.fury.io/js/ajax-client.svg)](https://badge.fury.io/js/ajax-client)\n[![CircleCI](https://circleci.com/gh/riversun/ajax-client/tree/master.svg?style=shield)](https://circleci.com/gh/riversun/ajax-client/tree/master)\n[![codecov](https://codecov.io/gh/riversun/ajax-client/branch/master/graph/badge.svg)](https://codecov.io/gh/riversun/ajax-client)\n[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)\n\nA simple ajax client with jQuery like ajax API for js.\n\njQuery is great, but do you use jQuery(80KB over) only for ajax?\n\n\n## install\n\n- use package with npm\n\n```shell\nnpm install ajax-client \n```\n\nand write followings in your code\n\n\n- AjaxClient is based on the XmlHttpRequest2 and HAS APIs most similar to jQuery's API\n\n```javascript\nimport {AjaxClient} from 'ajax-client'\nclient.ajax({\n  type: 'post',\n  url: 'http://localhost:9999/api',\n  headers: {\n    'X-Original-Header1': 'header-value-1',//Additional Headers\n    'X-Original-Header2': 'header-value-2',\n  },\n  contentType: 'application/json',//content-type of sending data\n  data: JSON.stringify(data),//text data\n  dataType: 'json',//data type to parse when receiving response from server\n  timeoutMillis: 5000,//timeout milli-seconds\n  // crossDomain: true,\n  // xhrFields: {\n  //   withCredentials: true,\n  // },\n  success: (response, xhr) =\u003e {\n  },\n  error: (e, xhr) =\u003e {\n\n  },\n  timeout: (e, xhr) =\u003e {\n\n  }\n});\n```\n\n\n- AjaxClient2(**recommended**) is base on **fetch API**\n\n```javascript\nimport {AjaxClient2 as AjaxClient} from 'ajax-client'\n```\n\n```javascript\nimport ajax_client from 'ajax-client';\nconst { AjaxClient2 } = ajax_client;\n\n```\n\n\n- use from CDN\n\n```\n\u003cscript src=\"https://cdn.jsdelivr.net/npm/ajax-client@2.0.2/lib/ajax-client.min.js\"\u003e\u003c/script\u003e\n```\n\n## usage\n\n### Post\n\n- Post JSON string to server,Receive JSON string from server.\n\n```javascript\n\n       const client = new AjaxClient2();\n \n       //Data object to send\n       const data = {\n         message: \"hello\"\n       }\n \n       client.ajax({\n         type: 'post',\n         url: 'http://localhost:9999/api',\n         headers: {\n           'X-Original-Header1': 'header-value-1',//Additional Headers\n           'X-Original-Header2': 'header-value-2',\n         },\n         contentType: 'application/json',//content-type of sending data\n         data: JSON.stringify(data),//text data\n         dataType: 'json',//data type to parse when receiving response from server\n         timeoutMillis: 5000,//timeout milli-seconds\n         // crossDomain: true,\n         // xhrFields: {\n         //   withCredentials: true,\n         // },\n         success: (data, response) =\u003e {\n           // response is fetch response\n         },\n         error: (data,response,cause,err) =\u003e {\n         },\n         timeout: (data,response,cause,err) =\u003e {\n         }\n       });\n\n```\n\n- Post form data\n\n```javascript\n     const client = new AjaxClient2();\n     const data = {\n        message: \"hello\"\n      }\n\n      // first access = Receive cookies with the intention of credential\n      client.ajax({\n        type: 'post',\n        url: `http://localhost:${serverPort}/form`,\n        headers: {\n          'X-Original-Header1': 'header-value-1',//Additional Headers\n          'X-Original-Header2': 'header-value-2',\n        },\n        contentType: 'application/x-www-form-urlencoded',\n        data,\n        dataType: 'json',//data type to parse when receiving response from server\n        timeoutMillis: 5000,//timeout milli-seconds\n         // crossDomain: true,\n         // xhrFields: {\n         //   withCredentials: true,\n         // },\n        success: (data, response) =\u003e {\n          // response is fetch response\n        },\n        error: (data,response,cause,err) =\u003e {\n        },\n        timeout: (data,response,cause,err) =\u003e {\n        }\n      });\n```\n\n### Post with done/fail\n\n```javascript\n client.ajax({\n        type: 'post',\n        url: 'http://localhost:9999/api',\n        //contentType: 'application/json',//content-type of sending data\n        dataType: 'text',//data type to parse when receiving response from server\n        timeoutMillis: 5000,//timeout milli-seconds\n      }).done((data,response) =\u003e {\n        console.log(data);\n        console.log(response.status);\n      }).fail((data,response,cause,err) =\u003e {\n        console.log(data);\n        console.log(response.status);\n      });\n```\n\n### Post with Async/Await\n\n```javascript\nconst client = new AjaxClient2();  \nconst result = await client.post({\n        url: 'http://localhost:9999/api',\n        headers: {\n          'X-Original-Header1': 'header-value-1',//Additional Headers\n          'X-Original-Header2': 'header-value-2',\n        },\n        contentType: 'application/json',//content-type of sending data\n        data: data,\n        dataType: 'json',//data type to parse when receiving response from server\n        timeoutMillis: 5000,//timeout milli-seconds\n      });\n```\n\n```js\nconsole.log(result.success); // true if success\nconsole.log(result.data);// get JSON-parsed data\nconsole.log(result.response.status);// get status code 200\n```\n\n#### Success Response \n\n```javascript\n{\nsuccess: true,\ndata:{ },// response payload from server\nresponse:{}, // get raw fetch response.You can get response.status,response.statusText etc.  \n}\n```\n\n#### Error Response \n\n\n- server error\n\nOccurs when the server side returns a status code other than 200-299.\nParse the error object yourself if you want to determine more details.\n\n```javascript\n{\nsuccess: false;\ndata:{ },// response payload from server\ncause:'server error,statusCode:404',\nerror:e,// error object\nresponse:{}, // get raw fetch response.You can get response.status,response.statusText etc.  \n}\n```\n\n- client error\n\nWhen you specify json as the expected data type, but the server returns text, etc.\nParse the error object yourself if you want to determine more details.\n\n```javascript\n{\nsuccess: false;\ndata:{ },// response payload from server\ncause:'client error,${error_message_thrown_at_client}',\nerror:e,// error object\nresponse:{}, // get raw fetch response.You can get response.status,response.statusText etc.\n}\n```\n\n- network error\n\nOccurs when the network is disconnected or the server cannot be found.\nParse the error object yourself if you want to determine more details.\n\n```javascript\n{\nsuccess: false;\ndata:null,\ncause:'network error',\nerror:e,// error object\nresponse:null,  // no server response\n}\n```\n\n\n- timeout error\n\n- Occurs when no reply is received from the server for more than the specified timeout milliseconds.\n\n```javascript\n{\n  success: false;\n  data:null,\n  cause:'timeout,100ms elapsed',\n    error:e,// error object\n    response:null,\n}\n```\n\n\n### Get\n\n```javascript\n     const client = new AjaxClient2();\n\n      client.ajax({\n        type: 'get',\n        url: 'http://localhost:9999/something.html',\n        dataType: 'text',//data type to parse when receiving response from server\n        timeoutMillis: 5000,//timeout milli-seconds\n        success: (data, response) =\u003e {\n          // response is fetch response\n        },\n        error: (data,response,cause,err) =\u003e {\n        },\n        timeout: (data,response,cause,err) =\u003e {\n        }\n      });\n```\n\n```js\nconsole.log(result.success); // true if success\nconsole.log(result.data);// get JSON-parsed data\nconsole.log(result.response.status);// get status code 200\n```\n\n\n### Get with Async/Await\n\n```javascript\nconst client = new AjaxClient2();  \nconst result = await client.get({\n        url: 'http://localhost:9999/api',\n        headers: {\n          'X-Original-Header1': 'header-value-1',//Additional Headers\n          'X-Original-Header2': 'header-value-2',\n        },\n        dataType: 'text',//data type to parse when receiving response from server\n        timeoutMillis: 5000,//timeout milli-seconds\n      });\n```\n\n#### Success Response \n\n```javascript\n{\nsuccess: true,\ndata:{ },// response payload from server\nresponse:{}, // get raw response.You can get response.status,response.statusText etc.  \n\n}\n```\n\n#### Error Response \n\n- server error\n \n```javascript\n{\nsuccess: false;\ncause:'error',// 'error' or 'timeout'\nerror:e,// error object\nresponse:{}, // get raw response.You can get response.status,response.statusText etc.  \n}\n```\n\n- timeout error\n\n```javascript\n{\nsuccess: false;\ncause:'timeout',// 'error' or 'timeout'\nerror:e,// error object\nresponse:null,  \n}\n```\n\n## Example (using ajax-client)\n\n```html\n\n\u003c!DOCTYPE html\u003e\n\u003chtml lang=\"en\"\u003e\n\u003chead\u003e\n    \u003cmeta charset=\"UTF-8\"\u003e\n    \u003ctitle\u003eajax-client example\u003c/title\u003e\n\u003c/head\u003e\n\u003cbody\u003e\n\u003cscript src=\"https://raw.githubusercontent.com/riversun/ajax-client/master/dist/ajaxclient.js\"\u003e\u003c/script\u003e\n\u003cscript\u003e\n    const ajax = new AjaxClient2();\n\n    //Data object to send\n    const data = {\n        message: \"hello\"\n    }\n\n    //Do async post request\n    ajax.postAsync({\n        url: 'http://localhost:9999/api',//Endpoint\n        headers: {\n            'X-Original-Header1': 'header-value-1',//Additional Headers\n            'X-Original-Header2': 'header-value-2',\n        },\n        contentType: 'application/json; charset = UTF-8',//content-type of sending data\n        data: JSON.stringify(data),//text data\n        dataType: 'json',//data type to parse when receiving response from server\n        timeoutMillis: 5000,//timeout milli-seconds\n        success: response =\u003e {\n            console.log(response);\n        },\n        error: e =\u003e {\n            console.error('Error occurred');\n        },\n        timeout: e =\u003e {\n            console.error('Timeout occurred.');\n        }\n    });\n\n\u003c/script\u003e\n\u003c/body\u003e\n\u003c/html\u003e\n\n\n```\n\n### Run on node.js (ES6 -)\n\n\nIf you set up `node-fetch` externally, you can use AjaxClient with node.js.\n\n```javascript\nimport fetch from 'node-fetch';\nimport ajax_client from 'ajax-client';\nconst { AjaxClient2 } = ajax_client;\nconst ajax = new AjaxClient2({ fetch });\n```\n\n\n### Run on node.js (commonJS/babel)\n\nIf you set up `node-fetch` externally, you can use AjaxClient with node.js.\n\n```javascript\nimport fetch from 'node-fetch';\nimport { AjaxClient2 as AjaxClient } from 'ajax-client';\nconst ajax = new AjaxClient({ fetch });\n```\n\n### Run test server (node.js)\n\n- run test-server to test example above\n\n**TestServer.js**\n\n```shell\nnpm run test-server\n```\n\n```javascript\n\n/**\n * Test Server for ajax-client\n *\n * npm run test-server\n *\n * @type {createApplication}\n */\n\nconst express = require('express');\nconst app = express();\nconst bodyParser = require('body-parser');\n\napp.use(bodyParser.json());\n\n//Specify port\nvar port = process.env.PORT || 9999;\n\n//Allow CORS\napp.use(function (req, res, next) {\n    res.header(\"Access-Control-Allow-Origin\", \"*\");\n    res.header(\"Access-Control-Allow-Headers\", \"Origin,Content-Type,Accept,X-Original-Header1,X-Original-Header2\");\n    next();\n});\n\n//Handle 'post' as 'http://localhost:9999/api'\napp.post('/api', bodyParser.json(), function (req, res, next) {\n\n    res.status(200);\n\n    const data = req.body;\n    if (data) {\n        let message = \"Hi,there! You say \" + data.message;\n        res.json({\n            output: message\n        });\n    } else {\n        let message = 'error:message not found.';\n        res.json({\n            error: message\n        });\n    }\n\n\n});\napp.listen(port);\nconsole.log('Server started on port:' + port);\n```\n\n\u003chr\u003e\n\n## Classical approach(using jQuery)\n\n**index_jquery.html**\n\n```html\n\u003c!DOCTYPE html\u003e\n\u003chtml lang=\"en\"\u003e\n\u003chead\u003e\n    \u003cmeta charset=\"UTF-8\"\u003e\n    \u003ctitle\u003ejQuery ajax example\u003c/title\u003e\n\u003c/head\u003e\n\u003cbody\u003e\n\n\u003cscript\n        src=\"https://code.jquery.com/jquery-3.3.1.min.js\"\n        integrity=\"sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=\"\n        crossorigin=\"anonymous\"\u003e\u003c/script\u003e\n\n\u003cscript\u003e\n\n    //Data object to send\n    const data = {\n        message: \"hello\"\n    }\n\n    $.ajax({\n        type: \"post\",\n        url: 'http://localhost:9999/api',//Endpoint\n        headers: {\n            'X-Original-Header1': 'header-value-1',//Additional Headers\n            'X-Original-Header2': 'header-value-2',\n        },\n        contentType: 'application/json; charset = UTF-8',//content-type of sending data\n        data: JSON.stringify(data),\n        dataType: \"json\",\n        success: response =\u003e {\n            console.log(response);\n        },\n        error: e =\u003e {\n            console.error('Error occurred');\n        }\n    });\n\n\u003c/script\u003e\n\u003c/body\u003e\n\u003c/html\u003e\n\n```\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Friversun%2Fajax-client","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Friversun%2Fajax-client","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Friversun%2Fajax-client/lists"}