-
Notifications
You must be signed in to change notification settings - Fork 3
jQuery AJAX Examples
Just 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.
- 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. Unfortunately there is no easy way around the problem, but here are two possible workarounds:
- Configure your web server (e.g. Apache) to act as a Reverse Proxy (try Googling that term if it's unfamiliar), and proxy through Rollcall requests to the Rollcall server.
- Use JSONP to make the requests. See jQuery AJAX Examples via JSONP.
- Some older browsers don't support the
PUT
andDELETE
methods. As a workaround, to simulatePUT
s andDELETE
s you can send aPOST
request with a_method
parameter specifying the method you actually want to use. For example aPOST
with_method=PUT
will be treated by Rollcall as aPUT
request.
These examples assume that you've set up your web server to proxy through requests to Rollcall (see the note above regarding Reverse Proxying ). If you'd rather go the JSONP route, see jQuery AJAX Examples via JSONP.
To retrieve a User with ID 5
, you would place a GET
call to /users/5.json
:
jQuery.ajax({
type: 'GET',
url: '/users/5.json',
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({
type: 'GET',
url: '/users/jsmith.json',
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({
type: 'POST',
url: '/users/jsmith.json',
data: {
user: {
username: 'jdoe',
display_name: 'John Doe',
kind: 'Instructor',
metadata: {
'hair colour': 'Brown'
}
}
}
success: function(data) {
alert("User "+data.user.username+" created!")
}
})
For detailed information on all of the available resource URLs and their parameters, have a look at the API Docs.