jQuery Tips
Use Firebug
If you've never used Firebug, or a similar tool, and you're still using alert('some debugging line'), Firebug will change your life for the better. To get started, just try a debug line in the middle of your code:
console.log('hello there', window, {some: 'data'});
The above line will spit out to the Firebug console (hit F12) three bits of data: a string, the window object and an object with a property called 'some' with a value of 'data'.
Check out Firebug's breakpointing as well, and its CSS / HTML manipulation is also awesome.
AJAX: the basic approach
This is an example AJAX request that sends a JavaScript object to a particular path (/cheeses). Don't worry about the 'new VisualCheese(data)' bit, as I'm just being silly. You can do whatever you want with the data that comes back.
var cheese = { name: 'Edam' };
$.ajax({
processData: false, // don't eval the response
type: 'POST', // careful with PUT and DELETE on crappy browsers
url: '/cheeses',
dataType: 'json', // the format of the response
data: JSON.stringify(cheese), // request body
success: function(data) { // 'data' is essentially the response body
new VisualCheese(data); // what to do on success
}
});
AJAX: HTTP codes are your friend
It turns out that HTTP codes are pretty useful. They provide a standard set of codes for efficiently communicating how a request went down at the server side. Since AJAX is all about speeding things up for the user, if you can get away with using response codes, your application will feel faster.
- The 2xx range says 'yay, your request worked'. It ought to be accompanied by a location header if it's a 201 Created, so you can go and fetch the new representation.
- The 3xx range says 'you want to go over there'. Avoid giving these responses to AJAX requests as e.g. 302 will cause jQuery's AJAX libraries to follow the redirect and cause unwanted requests to be made by the browser.
- The 4xx range means the user messed up. Kinda. You know about 404.
- The 5xx range means the server messed up. Tell the user, if you fancy being defensive.