Wednesday, March 12, 2014

Ajax and other things

After going through what felt like half of stackoverflow.com and several tutorials on using ajax with jQuery and Rails, I finally figured out how to use ajax to pass an updated instance variable from a controller method to jQuery code in a view. It is so simple I can't believe I didn't figure it out before, but most of the information I found had to do with requesting http, javascript, and json, which was not what I wanted.

Prior to figuring this out, I had been using a hack to get around the fact that the instance variables were only updating on page loads. This was causing issues with the progress bar display because the code could save the updated progress (via ajax) but not access it. Hence I was storing the updated value locally (using an attribute of the progress bar) so that the Success button could be clicked repeatedly and the progress bar would fill up to 100% (which is what we need to demo for the client meeting on Friday). This worked but it wasn't really the right way to it.

Now, using ajax, jQuery can send a GET request to a controller method where the instance variable will be updated from the database and passed back to the jQuery code. Of course, a route also has to be added to the routes.db table so that the url that is given in the ajax call is valid. In the controller method, after getting the desired data from the database, the following render call is made:


render text: @instance_variable

This sends the instance variable back to the calling ajax code where the ajax success property is given a function that gets the requested data and sets it into a jQuery variable:

success: function(data){
    $jquery_var = data;
}

Since the render function in the controller method is passing back text, the data will have to parsed to a float or integer if the value needs to be in a numerical format. However, with just a few lines of code, you can really quickly get updated instance variables from a controller to jQuery code without having to reload the page. This feature is also really helpful to Fernando and I since we will be using timestamps from past user checkins to determine if they are staying "on-track" and will have to get updated information in order to test our code.

As a final note, I had to set "async: false" in the ajax call because ajax (being normally asynchronous) will update the database in the background and the next ajax request in the code to get the updated value might not get the latest version of the value. Thus I set all the ajax calls to be synchronous so that this problem would not happen.


No comments:

Post a Comment