Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

Rails and xmlhttprequests


Published on

For more information:

Published in: Technology
  • Be the first to comment

  • Be the first to like this

Rails and xmlhttprequests

  1. 1. Rails and XMLHttpRequests •
  2. 2. Rails and XMLHttpRequests• Rails provides multiple ways to handle the actual response building from re-rendering the html to simply rendering json/xml/whatever-serialized.• It also provides a handy way to specify some link or a form that has an ajax action.• Adding :remote => true to i.e. a link_to-helper will transform the link to fire an XMLHttpRequest instead of following the link.• This allows pure Rails applications to be built in a way that degrades gracefully if the client doesn’t have JavaScript enabled. •
  3. 3. Handling the request• Rails provides a lot of control over how to handle MLHttpRequests: – It’s possible render a partial view and return that using some logic already defined on the client to update the DOM, render JSON and parse it into the DOM on the client, – or return JavaScript containing all the logic required to update the currently visible page on the client. •
  4. 4. Handling the request• To check whether the request is an XHR one Rails provides a helper called request.xhr? – It checks the request for ‘X-Request-With’ = ‘XMLHttpRequest’ header. So if your application handles ajax for example by re-rendering a partial view you could use request.xhr? to check whether the whole page should be rendered or not.• A bit cleaner way is to use respond_to with format. By default XHR-requests made using the Rails helpers with :remote => true can be handled using format.js. •
  5. 5. Handling the response• Apart from returning JavaScript that updates the DOM straight from server the response can be handled using events .• Requests that happen using the Rails unobtrusive JavaScript (ie. :remote => true) fire events (ajax:beforeSend, ajax:complete, ajax:success , ajax:error) allows you to use for example, jQuery to bind to them, updating the DOM based on the request status. •
  6. 6. Handling the response• Rails also allows you to return JavaScript that’s executed on response, allowing you to write code for updating the DOM to be returned with the changed data.• Handling XHR this way probably won’t scale too far as the response is always created on the server side and requires more data to be sent over the wire in comparison to serialized json/xml and client side rendering. •