{"id":13806847,"url":"https://github.com/ember-cli/ember-ajax","last_synced_at":"2025-09-27T03:30:34.547Z","repository":{"id":28747706,"uuid":"32269638","full_name":"ember-cli/ember-ajax","owner":"ember-cli","description":"Service for making AJAX requests in Ember applications","archived":true,"fork":false,"pushed_at":"2022-12-08T16:55:46.000Z","size":2577,"stargazers_count":212,"open_issues_count":44,"forks_count":87,"subscribers_count":15,"default_branch":"master","last_synced_at":"2025-01-03T17:49:39.477Z","etag":null,"topics":["ajax","ember-addon","emberjs","network"],"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/ember-cli.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":null,"funding":null,"license":"LICENSE.md","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2015-03-15T16:05:32.000Z","updated_at":"2024-10-07T17:09:10.000Z","dependencies_parsed_at":"2022-07-31T23:48:40.243Z","dependency_job_id":null,"html_url":"https://github.com/ember-cli/ember-ajax","commit_stats":null,"previous_names":[],"tags_count":38,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ember-cli%2Fember-ajax","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ember-cli%2Fember-ajax/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ember-cli%2Fember-ajax/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ember-cli%2Fember-ajax/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/ember-cli","download_url":"https://codeload.github.com/ember-cli/ember-ajax/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":234376917,"owners_count":18822416,"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","ember-addon","emberjs","network"],"created_at":"2024-08-04T01:01:17.029Z","updated_at":"2025-09-27T03:30:33.996Z","avatar_url":"https://github.com/ember-cli.png","language":"JavaScript","readme":"# ember-ajax\n\n[![npm version](https://badge.fury.io/js/ember-ajax.svg)](https://badge.fury.io/js/ember-ajax)\n[![Travis CI Build Status](https://travis-ci.org/ember-cli/ember-ajax.svg?branch=master)](https://travis-ci.org/ember-cli/ember-ajax)\n[![Ember Observer Score](http://emberobserver.com/badges/ember-ajax.svg)](http://emberobserver.com/addons/ember-ajax)\n\nService for making AJAX requests in Ember applications.\n\n- customizable service\n- returns RSVP promises\n- improved error handling\n- ability to specify request headers\n\n## :warning: Deprecated\n\n`ember-ajax` is now deprecated. Please consider using [`ember-fetch`](https://github.com/ember-cli/ember-fetch), or [`ember-ajax-fetch`](https://github.com/expel-io/ember-ajax-fetch) as a more direct replacement.\n\n## Getting started\n\nIf you're just starting out, you already have `ember-ajax` installed! However, if it's missing from your `package.json`, you can add it by doing:\n\n```sh\nember install ember-ajax\n```\n\nTo use the ajax service, inject the `ajax` service into your route or component.\n\n```js\nimport Ember from 'ember';\n\nexport default Ember.Route.extend({\n  ajax: Ember.inject.service(),\n  model() {\n    return this.get('ajax').request('/posts');\n  }\n});\n```\n\n## Ajax Service\n\n### Basic Usage\n\nThe AJAX service provides methods to be used to make AJAX requests, similar to\nthe way that you would use `jQuery.ajax`. In fact, `ember-ajax` is a wrapper\naround jQuery's method, and can be configured in much the same way.\n\nIn general, you will use the `request(url, options)` method, where `url` is the\ndestination of the request and `options` is a configuration hash for\n[`jQuery.ajax`](http://api.jquery.com/jQuery.ajax/#jQuery-ajax-settings).\n\n```javascript\nimport Ember from 'ember';\n\nexport default Ember.Controller.extend({\n  ajax: Ember.inject.service(),\n  actions: {\n    sendRequest() {\n      return this.get('ajax').request('/posts', {\n        method: 'POST',\n        data: {\n          foo: 'bar'\n        }\n      });\n    }\n  }\n});\n```\n\nIn this example, `this.get('ajax').request()` will return a promise with the\nresult of the request. Your handler code inside `.then` or `.catch` will\nautomatically be wrapped in an Ember run loop for maximum compatibility with\nEmber, right out of the box.\n\n### HTTP-verbed methods\n\nYou can skip setting the `method` or `type` keys in your `options` object when\ncalling `request(url, options)` by instead calling `post(url, options)`,\n`put(url, options)`, `patch(url, options)` or `del(url, options)`.\n\n```js\npost('/posts', { data: { title: 'Ember' } }); // Makes a POST request to /posts\nput('/posts/1', { data: { title: 'Ember' } }); // Makes a PUT request to /posts/1\npatch('/posts/1', { data: { title: 'Ember' } }); // Makes a PATCH request to /posts/1\ndel('/posts/1'); // Makes a DELETE request to /posts/1\n```\n\n### Custom Request Headers\n\n`ember-ajax` allows you to specify headers to be used with a request. This is\nespecially helpful when you have a session service that provides an auth token\nthat you have to include with the requests to authorize your requests.\n\nTo include custom headers to be used with your requests, you can specify\n`headers` hash on the `Ajax Service`.\n\n```js\n// app/services/ajax.js\n\nimport Ember from 'ember';\nimport AjaxService from 'ember-ajax/services/ajax';\n\nexport default AjaxService.extend({\n  session: Ember.inject.service(),\n  headers: Ember.computed('session.authToken', {\n    get() {\n      let headers = {};\n      const authToken = this.get('session.authToken');\n      if (authToken) {\n        headers['auth-token'] = authToken;\n      }\n      return headers;\n    }\n  })\n});\n```\n\nHeaders by default are only passed if the hosts match, or the request is a relative path.\nYou can overwrite this behavior by either passing a host in with the request, setting the\nhost for the ajax service, or by setting an array of `trustedHosts` that can be either\nan array of strings or regexes.\n\n```js\n// app/services/ajax.js\n\nimport Ember from 'ember';\nimport AjaxService from 'ember-ajax/services/ajax';\n\nexport default AjaxService.extend({\n  trustedHosts: [/\\.example\\./, 'foo.bar.com']\n});\n```\n\n### Custom Endpoint Path\n\nThe `namespace` property can be used to prefix requests with a specific url namespace.\n\n```js\n// app/services/ajax.js\nimport Ember from 'ember';\nimport AjaxService from 'ember-ajax/services/ajax';\n\nexport default AjaxService.extend({\n  namespace: '/api/v1'\n});\n```\n\n`request('/users/me')` would now target `/api/v1/users/me`\n\nIf you need to override the namespace for a custom request, use the `namespace` as an option to the request methods.\n\n```js\n// GET /api/legacy/users/me\nrequest('/users/me', { namespace: '/api/legacy' });\n```\n\n### Custom Host\n\n`ember-ajax` allows you to specify a host to be used with a request. This is\nespecially helpful so you don't have to continually pass in the host along\nwith the path, makes `request()` a bit cleaner.\n\nTo include a custom host to be used with your requests, you can specify `host`\nproperty on the `Ajax Service`.\n\n```js\n// app/services/ajax.js\n\nimport Ember from 'ember';\nimport AjaxService from 'ember-ajax/services/ajax';\n\nexport default AjaxService.extend({\n  host: 'http://api.example.com'\n});\n```\n\nThat allows you to only have to make a call to `request()` as such:\n\n```js\n// GET http://api.example.com/users/me\nrequest('/users/me');\n```\n\n### Custom Content-Type\n\n`ember-ajax` allows you to specify a default [Content-Type](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Type) header to be used with a request.\n\nTo include a custom Content-Type you can specify `contentType` property on the `Ajax Service`.\n\n```js\n// app/services/ajax.js\n\nimport Ember from 'ember';\nimport AjaxService from 'ember-ajax/services/ajax';\n\nexport default AjaxService.extend({\n  contentType: 'application/json; charset=utf-8'\n});\n```\n\nYou can also override the Content-Type per `request` with the `options` parameter.\n\n#### Customize isSuccess\n\nSome APIs respond with status code 200, even though an error has occurred and\nprovide a status code in the payload. With the service, you can easily account\nfor this behaviour by overwriting the `isSuccess` method.\n\n```js\n// app/services/ajax.js\n\nimport AjaxService from 'ember-ajax/services/ajax';\n\nexport default AjaxService.extend({\n  isSuccess(status, headers, payload) {\n    let isSuccess = this._super(...arguments);\n    if (isSuccess \u0026\u0026 payload.status) {\n      // when status === 200 and payload has status property,\n      // check that payload.status is also considered a success request\n      return this._super(payload.status);\n    }\n    return isSuccess;\n  }\n});\n```\n\n### Error handling\n\n`ember-ajax` provides built in error classes that you can use to check the error\nthat was returned by the response. This allows you to restrict determination of\nerror result to the service instead of sprinkling it around your code.\n\n#### Built in error types\n\n`ember-ajax` has built-in error types that will be returned from the service in the event of an error:\n\n- `BadRequestError` (400)\n- `UnauthorizedError`(401)\n- `ForbiddenError`(403)\n- `NotFoundError` (404)\n- `InvalidError`(422)\n- `ServerError` (5XX)\n- `AbortError`\n- `TimeoutError`\n\nAll of the above errors are subtypes of `AjaxError`.\n\n#### Error detection helpers\n\n`ember-ajax` comes with helper functions for matching response errors to their respective `ember-ajax` error type. Each of the errors listed above has a corresponding `is*` function (e.g., `isBadRequestError`).\n\nUse of these functions is **strongly encouraged** to help eliminate the need for boilerplate error detection code.\n\n```js\nimport Ember from 'ember';\nimport {\n  isAjaxError,\n  isNotFoundError,\n  isForbiddenError\n} from 'ember-ajax/errors';\n\nexport default Ember.Route.extend({\n  ajax: Ember.inject.service(),\n  model() {\n    const ajax = this.get('ajax');\n\n    return ajax.request('/user/doesnotexist').catch(function(error) {\n      if (isNotFoundError(error)) {\n        // handle 404 errors here\n        return;\n      }\n\n      if (isForbiddenError(error)) {\n        // handle 403 errors here\n        return;\n      }\n\n      if (isAjaxError(error)) {\n        // handle all other AjaxErrors here\n        return;\n      }\n\n      // other errors are handled elsewhere\n      throw error;\n    });\n  }\n});\n```\n\nIf your errors aren't standard, the helper function for that error type can be used as the base to build your custom detection function.\n\n#### Access the response in case of error\n\nIf you need to access the json response of a request that failed, you can use the `raw` method instead of `request`.\n\n```js\nthis.get('ajax')\n  .raw(url, options)\n  .then(({ response }) =\u003e this.handleSuccess(response))\n  .catch(({ response, jqXHR, payload }) =\u003e this.handleError(response));\n```\n\nNote that in this use case there's no access to the error object. You can inspect the `jqXHR` object for additional information about the failed request. In particular `jqXHR.status` returns the relevant HTTP error code.\n\n## Usage with Ember Data\n\nEmber AJAX provides a mixin that can be used in an Ember Data Adapter to avoid the networking code provided by Ember Data and rely on Ember AJAX instead. This serves as a first step toward true integration of Ember AJAX into Ember Data.\n\nTo use the mixin, you can include the mixin into an Adapter, like so:\n\n```javascript\n// app/adapters/application.js\nimport DS from 'ember-data';\nimport AjaxServiceSupport from 'ember-ajax/mixins/ajax-support';\n\nexport default DS.JSONAPIAdapter.extend(AjaxServiceSupport);\n```\n\nThat's all the configuration required! If you want to customize the adapter, such as using an alternative AJAX service (like one you extended yourself), hooks to do so are provided; check out the mixin's implementation for details.\n\nNote that instead of using the Ember Data error checking code in your application, you should use the ones provided by Ember AJAX.\n\n## Stand-Alone Usage\n\nIf you aren't using Ember Data and do not have access to services, you\ncan import the ajax utility like so:\n\n```js\nimport request from 'ember-ajax/request';\n\nexport default function someUtility(url) {\n  var options = {\n    // request options\n  };\n\n  return request(url, options).then(response =\u003e {\n    // `response` is the data from the server\n    return response;\n  });\n}\n```\n\nWhich will have the same API as the `ajax` service. If you want the raw jQuery XHR object\nthen you can use the `raw` method instead:\n\n```js\nimport raw from 'ember-ajax/raw';\n\nexport default function someOtherUtility(url) {\n  var options = {\n    // raw options\n  };\n\n  return raw(url, options).then(result =\u003e {\n    // `result` is an object containing `response` and `jqXHR`, among other items\n    return result;\n  });\n}\n```\n\n## Local Development\n\nThis information is only relevant if you're looking to contribute to `ember-ajax`.\n\n### Compatibility\n\n- Node.js 6 or above\n- Ember CLI v2.13 or above\n\n### Installation\n\n- `git clone` this repository\n- `npm install`\n\n### Running\n\n- `ember server`\n- Visit your app at http://localhost:4200.\n\n### Running Tests\n\n- `ember test`\n- `ember test --server`\n\n### Building\n\n- `ember build`\n\nFor more information on using ember-cli, visit [http://www.ember-cli.com/](http://www.ember-cli.com/).\n","funding_links":[],"categories":["Packages"],"sub_categories":["HTTP"],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fember-cli%2Fember-ajax","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fember-cli%2Fember-ajax","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fember-cli%2Fember-ajax/lists"}