Requests

Your app will likely want to make AJAX calls to other places such as your backend, another web app or service, etc. We do this in apps by way of "requests."

The basics

If you've never had to make web requests before, we strongly recommend getting familiar with AJAX. For further reading, we also recommend taking a look at jQuery.ajax, as there are strong similarities between web requests in Apps and AJAX in jQuery.

Requests in our framework are simple AJAX calls, with support for GET and POST requests, and for data types such as XML, JSON or JSONP. (Support for PUT and DELETE requests will be forthcoming.)

An example

Let's take a look at a simple GET request:

requests: {
  fetchBookmarks: {
    url: '/api/v1/bookmarks.json',
    type: 'GET'
  },
  ...
}

We give our request a name -- fetchBookmarks in this case -- and call it in the app by its name: this.ajax('fetchBookmarks');.

This particular request is simply making a GET request to /api/v1/bookmarks.json and nothing more. You can subscribe to events that will fire once this request completes:

'addBookmark.done': function() {
  services.notify('Bookmark Added');
},

See Events for more details

More in depth

Let's take a look at a slightly more complex example

requests: {
  addBookmark: function() {
    return {
      url: '/api/v1/bookmarks.json',
      type: 'POST',
      data: {
        ticket_id: this.ticket().id()
      }
    };
  }
},
...

This is a little more complex, because we're going to be passing in some options with our AJAX call, so let's step through the entire example:

  • addBookmark: function() we wrap a function around our request, this can allow you to pass in parameters from this.ajax() later in your app.js
  • return {} the object you return{} from this function will be passed on to jQuery.ajax. This means you can use any setting that jQuery.ajax can support
  • type: 'POST' the request type that we want to make
  • data: a hash of the parameters we want to send with our request - these should be in key: value pairs

Although it looks a little more complex than a simple GET request, it's just as easy in practise. You can even use this pattern for GET requests too.

Using a function for your request is useful if the URL you need to make a request to, or the data that you need to send in the request is dynamic and depends on user input or some ticket data.

Next Step: Lifecycle →