• This repository has been archived on 30/Jan/2023
  • Stars
    star
    213
  • Rank 185,410 (Top 4 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created over 9 years ago
  • Updated almost 2 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Service for making AJAX requests in Ember applications

ember-ajax

npm version Travis CI Build Status Ember Observer Score

Service for making AJAX requests in Ember applications.

  • customizable service
  • returns RSVP promises
  • improved error handling
  • ability to specify request headers

⚠️ Deprecated

ember-ajax is now deprecated. Please consider using ember-fetch, or ember-ajax-fetch as a more direct replacement.

Getting started

If 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:

ember install ember-ajax

To use the ajax service, inject the ajax service into your route or component.

import Ember from 'ember';

export default Ember.Route.extend({
  ajax: Ember.inject.service(),
  model() {
    return this.get('ajax').request('/posts');
  }
});

Ajax Service

Basic Usage

The AJAX service provides methods to be used to make AJAX requests, similar to the way that you would use jQuery.ajax. In fact, ember-ajax is a wrapper around jQuery's method, and can be configured in much the same way.

In general, you will use the request(url, options) method, where url is the destination of the request and options is a configuration hash for jQuery.ajax.

import Ember from 'ember';

export default Ember.Controller.extend({
  ajax: Ember.inject.service(),
  actions: {
    sendRequest() {
      return this.get('ajax').request('/posts', {
        method: 'POST',
        data: {
          foo: 'bar'
        }
      });
    }
  }
});

In this example, this.get('ajax').request() will return a promise with the result of the request. Your handler code inside .then or .catch will automatically be wrapped in an Ember run loop for maximum compatibility with Ember, right out of the box.

HTTP-verbed methods

You can skip setting the method or type keys in your options object when calling request(url, options) by instead calling post(url, options), put(url, options), patch(url, options) or del(url, options).

post('/posts', { data: { title: 'Ember' } }); // Makes a POST request to /posts
put('/posts/1', { data: { title: 'Ember' } }); // Makes a PUT request to /posts/1
patch('/posts/1', { data: { title: 'Ember' } }); // Makes a PATCH request to /posts/1
del('/posts/1'); // Makes a DELETE request to /posts/1

Custom Request Headers

ember-ajax allows you to specify headers to be used with a request. This is especially helpful when you have a session service that provides an auth token that you have to include with the requests to authorize your requests.

To include custom headers to be used with your requests, you can specify headers hash on the Ajax Service.

// app/services/ajax.js

import Ember from 'ember';
import AjaxService from 'ember-ajax/services/ajax';

export default AjaxService.extend({
  session: Ember.inject.service(),
  headers: Ember.computed('session.authToken', {
    get() {
      let headers = {};
      const authToken = this.get('session.authToken');
      if (authToken) {
        headers['auth-token'] = authToken;
      }
      return headers;
    }
  })
});

Headers by default are only passed if the hosts match, or the request is a relative path. You can overwrite this behavior by either passing a host in with the request, setting the host for the ajax service, or by setting an array of trustedHosts that can be either an array of strings or regexes.

// app/services/ajax.js

import Ember from 'ember';
import AjaxService from 'ember-ajax/services/ajax';

export default AjaxService.extend({
  trustedHosts: [/\.example\./, 'foo.bar.com']
});

Custom Endpoint Path

The namespace property can be used to prefix requests with a specific url namespace.

// app/services/ajax.js
import Ember from 'ember';
import AjaxService from 'ember-ajax/services/ajax';

export default AjaxService.extend({
  namespace: '/api/v1'
});

request('/users/me') would now target /api/v1/users/me

If you need to override the namespace for a custom request, use the namespace as an option to the request methods.

// GET /api/legacy/users/me
request('/users/me', { namespace: '/api/legacy' });

Custom Host

ember-ajax allows you to specify a host to be used with a request. This is especially helpful so you don't have to continually pass in the host along with the path, makes request() a bit cleaner.

To include a custom host to be used with your requests, you can specify host property on the Ajax Service.

// app/services/ajax.js

import Ember from 'ember';
import AjaxService from 'ember-ajax/services/ajax';

export default AjaxService.extend({
  host: 'http://api.example.com'
});

That allows you to only have to make a call to request() as such:

// GET http://api.example.com/users/me
request('/users/me');

Custom Content-Type

ember-ajax allows you to specify a default Content-Type header to be used with a request.

To include a custom Content-Type you can specify contentType property on the Ajax Service.

// app/services/ajax.js

import Ember from 'ember';
import AjaxService from 'ember-ajax/services/ajax';

export default AjaxService.extend({
  contentType: 'application/json; charset=utf-8'
});

You can also override the Content-Type per request with the options parameter.

Customize isSuccess

Some APIs respond with status code 200, even though an error has occurred and provide a status code in the payload. With the service, you can easily account for this behaviour by overwriting the isSuccess method.

// app/services/ajax.js

import AjaxService from 'ember-ajax/services/ajax';

export default AjaxService.extend({
  isSuccess(status, headers, payload) {
    let isSuccess = this._super(...arguments);
    if (isSuccess && payload.status) {
      // when status === 200 and payload has status property,
      // check that payload.status is also considered a success request
      return this._super(payload.status);
    }
    return isSuccess;
  }
});

Error handling

ember-ajax provides built in error classes that you can use to check the error that was returned by the response. This allows you to restrict determination of error result to the service instead of sprinkling it around your code.

Built in error types

ember-ajax has built-in error types that will be returned from the service in the event of an error:

  • BadRequestError (400)
  • UnauthorizedError(401)
  • ForbiddenError(403)
  • NotFoundError (404)
  • InvalidError(422)
  • ServerError (5XX)
  • AbortError
  • TimeoutError

All of the above errors are subtypes of AjaxError.

Error detection helpers

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).

Use of these functions is strongly encouraged to help eliminate the need for boilerplate error detection code.

import Ember from 'ember';
import {
  isAjaxError,
  isNotFoundError,
  isForbiddenError
} from 'ember-ajax/errors';

export default Ember.Route.extend({
  ajax: Ember.inject.service(),
  model() {
    const ajax = this.get('ajax');

    return ajax.request('/user/doesnotexist').catch(function(error) {
      if (isNotFoundError(error)) {
        // handle 404 errors here
        return;
      }

      if (isForbiddenError(error)) {
        // handle 403 errors here
        return;
      }

      if (isAjaxError(error)) {
        // handle all other AjaxErrors here
        return;
      }

      // other errors are handled elsewhere
      throw error;
    });
  }
});

If your errors aren't standard, the helper function for that error type can be used as the base to build your custom detection function.

Access the response in case of error

If you need to access the json response of a request that failed, you can use the raw method instead of request.

this.get('ajax')
  .raw(url, options)
  .then(({ response }) => this.handleSuccess(response))
  .catch(({ response, jqXHR, payload }) => this.handleError(response));

Note 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.

Usage with Ember Data

Ember 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.

To use the mixin, you can include the mixin into an Adapter, like so:

// app/adapters/application.js
import DS from 'ember-data';
import AjaxServiceSupport from 'ember-ajax/mixins/ajax-support';

export default DS.JSONAPIAdapter.extend(AjaxServiceSupport);

That'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.

Note that instead of using the Ember Data error checking code in your application, you should use the ones provided by Ember AJAX.

Stand-Alone Usage

If you aren't using Ember Data and do not have access to services, you can import the ajax utility like so:

import request from 'ember-ajax/request';

export default function someUtility(url) {
  var options = {
    // request options
  };

  return request(url, options).then(response => {
    // `response` is the data from the server
    return response;
  });
}

Which will have the same API as the ajax service. If you want the raw jQuery XHR object then you can use the raw method instead:

import raw from 'ember-ajax/raw';

export default function someOtherUtility(url) {
  var options = {
    // raw options
  };

  return raw(url, options).then(result => {
    // `result` is an object containing `response` and `jqXHR`, among other items
    return result;
  });
}

Local Development

This information is only relevant if you're looking to contribute to ember-ajax.

Compatibility

  • Node.js 6 or above
  • Ember CLI v2.13 or above

Installation

  • git clone this repository
  • npm install

Running

Running Tests

  • ember test
  • ember test --server

Building

  • ember build

For more information on using ember-cli, visit http://www.ember-cli.com/.

More Repositories

1

ember-cli

The Ember.js command line utility.
JavaScript
3,261
star
2

ember-exam

Run your tests with randomization, splitting, and parallelization for beautiful tests.
JavaScript
286
star
3

ember-cli-update

Update Ember CLI projects
JavaScript
277
star
4

ember-twiddle

JSFiddle type thing for ember-cli style code
JavaScript
268
star
5

eslint-plugin-ember

An ESLint plugin that provides set of rules for Ember applications based on commonly known good practices.
JavaScript
260
star
6

ember-page-title

Page title management for Ember.js Apps
JavaScript
188
star
7

ember-try

An ember-cli addon to test against multiple npm dependencies, such as ember and ember-data.
JavaScript
179
star
8

ember-fetch

HTML5 fetch polyfill from github wrapped and bundled for ember-cli users.
JavaScript
176
star
9

ember-cli-deprecation-workflow

JavaScript
165
star
10

ember-cli-mocha

Mocha and Chai tests for ember-cli applications
JavaScript
147
star
11

ember-cli-eslint

Ember CLI addon for linting Ember projects with ESLint
JavaScript
116
star
12

ember-new-output

Change history of new Ember-CLI apps
JavaScript
91
star
13

ember-resolver

JavaScript
87
star
14

broccoli-asset-rev

Broccoli plugin to add fingerprint checksums and CDN URLs to your assets
JavaScript
86
star
15

ember-rfc176-data

JSON data for Ember.js RFC #176
JavaScript
83
star
16

loader.js

minimal amd loader mostly stolen from wycats.
JavaScript
79
star
17

ember-cli-htmlbars

JavaScript
77
star
18

ember-template-imports

Template import support in Ember!
JavaScript
74
star
19

ember-cli-htmlbars-inline-precompile

📃 Precompile inline HTMLBars templates via ES6 tagged template strings
JavaScript
67
star
20

ember-cli-todos

JavaScript
67
star
21

babel-plugin-feature-flags

A babel transform for managing feature flags
JavaScript
57
star
22

ember-cli-app-version

Adds your app's version to Ember Inspector's Info tab
JavaScript
55
star
23

ember-cli-shims

DEPRECATED - ES6 import shims for Ember.js
JavaScript
46
star
24

ember-octane-blueprint

App and Addon blueprints for Ember Octane
JavaScript
46
star
25

rfcs

Archive of RFCs for changes to ember-cli (for current RFC repo see https://github.com/emberjs/rfcs)
45
star
26

ember-cli-babel-polyfills

Split-build polyfills for evergreen and legacy browsers
JavaScript
34
star
27

ember-cli-qunit

QUnit testing package for ember-cli applications
JavaScript
30
star
28

ember-compatibility-helpers

Helpers that allow you to write backwards compat Ember addons
JavaScript
24
star
29

ember-cli-version-checker

Dependency version checker for Ember CLI addons
JavaScript
24
star
30

broccoli-viz

library to read/parse and produce various visualizations of broccoli.
JavaScript
23
star
31

ember-cli-blueprint-test-helpers

Test helpers for testing ember-cli blueprints
JavaScript
23
star
32

ember-cli-terser

JavaScript minification for Ember-CLI
JavaScript
23
star
33

ember-cli-inject-live-reload

Ember CLI plugin that injects live-reload script into HTML content
JavaScript
22
star
34

ember-cli-chai

Chai assertions for Ember.js
JavaScript
21
star
35

babel-plugin-filter-imports

A babel transform for filtering out imports
JavaScript
18
star
36

broccoli-caching-writer

JavaScript
17
star
37

ember-addon-output

Change history of new Ember-CLI addons
JavaScript
16
star
38

core-object

JavaScript
16
star
39

babel-plugin-ember-modules-api-polyfill

Polyfill for Ember JS API
JavaScript
15
star
40

ember-load-initializers

JavaScript
14
star
41

console-ui

JavaScript
14
star
42

broccoli-es6modules

new es6 module transpiler
JavaScript
14
star
43

ember-export-application-global

JavaScript
14
star
44

babel-plugin-debug-macros

TypeScript
13
star
45

ember-cli.github.io

Our documentation site
SCSS
13
star
46

ember-router-generator

JavaScript
12
star
47

ember-welcome-page

Welcome page for Ember CLI applications
JavaScript
12
star
48

broccoli-terser-sourcemap

Broccoli filter to uglify with sourcemaps
JavaScript
10
star
49

broccoli-asset-rewrite

Broccoli plugin to rewrite a source tree from an asset map.
JavaScript
10
star
50

ember-cli-test-loader

JavaScript
10
star
51

ember-source-channel-url

JavaScript
10
star
52

stress-app

HTML
9
star
53

capture-exit

JavaScript
9
star
54

ember-next

A home for experiments that aim to become the defaults when running ember-new.
JavaScript
9
star
55

babel-plugin-htmlbars-inline-precompile

Babel plugin to replace tagged template strings with precompiled HTMLBars templates
JavaScript
9
star
56

broccoli-lint-eslint

Integrates JavaScript linting with ESLint as part of your Broccoli build pipeline.
JavaScript
8
star
57

blprnt

JavaScript
7
star
58

ember-cli-clean-css

CSS minification via clean-css for Ember CLI
JavaScript
6
star
59

exists-sync

Deprecated, please use fs.existsSync instead
JavaScript
6
star
60

ember-disable-prototype-extensions

Disables Ember's prototype extensions
JavaScript
6
star
61

silent-error

JavaScript
5
star
62

ember-cli-jshint

JSHint lint tests for your Ember CLI projects
JavaScript
5
star
63

create-ember-app

yarn create ember-app <name>
JavaScript
4
star
64

broccoli-middleware

Broccoli asset builder middleware
HTML
4
star
65

ember-cli-babili

JavaScript
4
star
66

ember-cli-update-codemods-manifest

Master list of codemods and their instructions used by ember-cli-update
JavaScript
4
star
67

amd-name-resolver

Algorithm for resolving AMD module names
JavaScript
3
star
68

ember-cli-string-utils

JavaScript
3
star
69

ember-cli-legacy-blueprints

Ember and Ember-Data specific blueprints for ember-cli projects not using the Ember and Ember-Data addons.
JavaScript
3
star
70

ember-cli-lodash-subset

JavaScript
2
star
71

ember-cli-default-packager

Default Packager for Ember CLI. More details in https://github.com/ember-cli/rfcs/pull/110.
TypeScript
2
star
72

codesandbox

Official Ember.js template for codesandbox.io
JavaScript
2
star
73

broccoli-amd-funnel

Funnel based on whether a module is AMD or not
JavaScript
1
star
74

broccoli-builder

JavaScript
1
star
75

calculate-cache-key-for-tree

ember-cli addon tree cache key builder
JavaScript
1
star
76

broccoli-funnel-reducer

JavaScript
1
star
77

app-blueprint-test

JavaScript
1
star
78

ember-cli-preprocess-registry

JavaScript
1
star
79

ember-cli-import-polyfill

Backports newer addon import API to older ember-cli versions.
JavaScript
1
star
80

node-modules-path

JavaScript
1
star
81

ember-build-utilities

A suite of build utilities for constructing Ember CLI build pipelines
JavaScript
1
star
82

ember-try-config

Config helper for ember-try
JavaScript
1
star
83

broccoli-config-replace

Simple templating using a config.json and regex patterns.
JavaScript
1
star
84

ember-cli-changelog

Tool used to generate changelogs for ember-cli.
JavaScript
1
star
85

create-ember-addon

yarn create ember-addon <name>
JavaScript
1
star