in Ruby on Rails

Simple AJAX and Rails Tutorial

It’s been a while since I’ve posted anything but I’ve been extremely busy coding my face off. The upside of that is I’ve been learning a ton of new stuff and I have a lot of things I want to write about.

Today I’m just going to go over a quick tutorial on how to use AJAX to send requests to functions in your Rails backend. The problem I kept running into was calling a function that is in a different controller than the view I’m calling it from.

I have a questions view and in the show.html.erb is where I want my AJAX to take place. The thing about it is I wanted to hit a function in my users_answers_controller.rb.

Onto the code!

The submit button looks like this.

The key thing here is the URL. The function is called checkAnswer and the controller is the user_answer. You also want to remember to add this to your routes. This is how I did it in my routes file.

The controller looks like this.

The params[:user_answer][‘userAnswerText’] is the field that I am submitting when clicking the submit button. You can see how I am returning the data I want to send back to the page in json format. Then I can use this in the success function. One key thing to remember about AJAX is it’s asynchronous, which means the rest of the page is going to load while your AJAX call finishes. In this case it’s ok, because I’m not doing anything with the AJAX until a user click. However, if you have other stuff in your javascript that relies on the data from your AJAX call you’ll need to also include that functionality in your success function.

The data from the form is submitted by using $(this).serialize and storing it in a variable. Don’t worry about the names that I am appending the data to but you can see how I am accessing different parts of the JSON.

You can see in the beginning I set the boolean to false. I change this to true when the form is submitted so that if the user clicks twice instantly the AJAX won’t make a second call to the checkAnswer function.

Hopefully this ends up being useful for someone because it took me quite a bit of time to get the correct syntax for making AJAX calls to different controllers in the latest version of Ruby on Rails.

Write a Comment

Comment