I recently upgraded co.mments to use Rails 1.1.2. One of my favorite new features is RJS.
Debugging with AJAX is harder than plain HTML. When you make an HTML request and get an error, it shows up in the browser. When you make an AJAX request and get an error, most of the time nothing interesting happens. But it doesnâ€™t have to be painful if you use the right combination of tools.
Here are a few tips I collected for debugging RJS code.
- To RJS or not RJS. RJS is great when the user clicks a button and a lot of stuff happen on the page. Itâ€™s an overkill for updating one piece of content. Using Rails to return a piece of HTML and prototype.js to update is easier, and you get a UI that is also an API. My rule of thumb: only RJS if clicking a button causes more than one action.
- One eye on the console. I run the server as a separate command line window, showing requests and errors as they happen. Itâ€™s easier than reloading the log file in a text editor. Half my bugs are errors in Ruby code that show up as stack traces in the console. Thatâ€™s the first place I look at when something goes wrong.
- View live source. Using View Source with AJAX is like driving with blinds on. It shows the page loaded by the browser but not any changes since. FireBug and Web Developer both have a DOM inspector, but they use trees which require a handful of clicks before you can find what you want. Itâ€™s quicker to navigate with View Source Chart using the page up/down keys.
- XHR 404/500. Requests that hit the wrong controller/action, or cause an exception in the Rails code, result in HTML pages that do nothing interesting on the client. Non-responsive AJAX can be annoying. I found an easy solution for that by forcing 404/500 errors to redirect to an error page using page.redirect_to.