← Back to Upcase

Load a page in Rails using Ajax


(Scott Hollinshead) #1

I wasn’t sure if this post belonged in JavaScript or Rails, so sorry if I have put it in the wrong place.

I have <%= link_to "Closed Calls", closedhelpdesks_path %>

When that link is clicked it will take you to a list of the closed calls and display a link to open calls.

In Rails how do I get it working using Ajax so that when you click the link it will load the page without reloading the window and the link change?

Thanks


(Chris Toomey) #2

Hello @scott, thanks for the question.

There are three main solutions that come to mind:

  1. The first is a technique known as unobtrusive javascript that allows you to cause
    links to use JS / AJAX. You can read about the technique, specifically with regard
    to links, in the Rails guide Working with JavaScript in Rails. Note, by default this will not update the URL in the address bar.
  2. Turbolinks is a gem that is included by default with any new Rails 4 app. It works by intercepting all clicks to links inside your app and instead of allowing the browser to navigate to the new page, turbolinks makes an AJAX call to the server and then replaces the body. This gets you most of the way there with very little effort on your part, but does have a few edge cases you would need to watch out for.
  3. The last option is to use a Javascript framework like Backbone, Ember, or Angular. These frameworks allow you to move much of your logic to the client side and allow for a much more interactive application, but they do introduce some additional complexity and code needed to bring your app to life.

Any of the above solutions would allow you to display new content via AJAX rather than navigating the page. That said, they all come with some drawbacks and I would very much recommend sticking to pure rails server side page rendering and traditional HTTP navigation for as long as possible, and only moving to JS tools like the ones listed above when your application truly needs it.

Hope this helps!

– Chris


(Scott Hollinshead) #3

Hi Chris,

thank you very much for your help, I think I will leave out the JS for a while then, the app doesn’t really need it.

Thanks