Skip to content

jQuery AJAX Examples

zuk edited this page Jan 20, 2011 · 15 revisions

Basically...

Send GET, POST, PUT, and DELETE requests via AJAX to the Rollcall server. These four HTTP request methods correspond to the four CRUD verbs (Create = POST, Retrieve = GET, Update = PUT, Delete = DELETE). The requests are made to Rollcall's resource collection URLs.

Have a look at the Wikipedia article on REST (Representational State Transfer) if you're not familiar with this style of web services.

But first, a major caveat!

Due to browser security constraints, you cannot easily fetch data via JavaScript from a URL on a different domain/port than the one the page is being served from. For example, if Rollcall is at http://rollcall.example.org/ and the web page with your JavaScript is on http://www.example.org/, the browser will block AJAX requests to the Rollcall URL. See http://en.wikipedia.org/wiki/Same_origin_policy for details.

As a workaround, the examples here use a technique (a hack, really) called JSONP. Since JSONP requests are always GETs, you must fake POST, PUT, and DELETE requests by specifying the request method you actually want to use in a special _method parameter.

For example, to make a POST request to http://rollcall.example.org/users.json, you would actually make a GET request to http://rollcall.example.org/users/users.json?_method=POST.

Another way to get around the Same Origin Policy is to set up a Reverse Proxy to funnel requests through to Rollcall (for example via Apache's mod_proxy). This is the preferred method, but the setup is too involved to explain here.

If you do go the Reverse Proxy route, you can omit the dataType and _method parameters from the examples shown here.

Examples

To retrieve a User with ID 5:

jQuery.ajax({
  url: 'http://rollcall.example.org/users/5.json',
  dataType: 'jsonp',
  success: function(data) {
    alert('User '+data.user.id+' is '+data.user.username+'!')
  }
})

You can also retrieve a User by their username, like this:

jQuery.ajax({
  url: 'http://rollcall.example.org/users/jsmith.json',
  dataType: 'jsonp',
  success: function(data) {
    // do something with the user data
  }
})

To create a new User, send a POST request along with the User's data:

jQuery.ajax({
  url: 'http://rollcall.example.org/users.json',
  dataType: 'jsonp',
  data: {
    _method: 'POST',
    user: {
      username: 'jdoe',
      display_name: 'John Doe',
      password: 'secret',
      kind: 'Instructor',
      metadata: {
        'hair colour': 'Brown'
      }
    }
  },
  success: function(data) {
    alert("User "+data.user.username+" created with ID "+data.user.id+"!")
  }
})

For detailed information on all of the available resource URLs and their parameters, have a look at the API Docs.

Clone this wiki locally