Archive for February, 2010

json and rails

Posted in javascript, jquery, rails on February 20th, 2010 by paul – Be the first to comment

The following is one way to handle json responses from a rails application.
So, I have a ajax request in a script in my page. In this example I am using the jquery poll plugin to poll the status of a file import.

$("#<%=import.id%>").poll({
    url: "/mis_imports/import_state/<%=import.id%>",
    interval: 3000,
    type: "GET",
    success: function(data){
                   var return_data = eval('(' + data + ')');
                   $("#<%=import.id%>").attr("class","mis_import_state_"+return_data.state);
		   $("#<%=import.id%>_message").html(""+return_data.status+"");
		   $("#<%=import.id%>_timestamp").html(""+return_data.timestamp+"");
		   if (return_data.state == 1){
		     $(this).stop();
		   }
    }
});

And on the server, my rails action method looks like this:

def import_state
    import = MisImport.find(params[:id])
    render :text => {:state => import.state,:status => import.message,:timestamp => Time.now.strftime("%d:%b:%Y %H:%M:%S")}.to_json
  end

The key part to this working is line 6 of the javascript listing, where one ‘evals’ the data returned from the server.
This effectively rehydrates the data structure into a usable javascript object, and that’s the bit I keep forgetting!

There are probably smarter ways of doing this; I know there is a jQuery.getJSON() function, but in this case I couldn’t work out how to use that with jquery poll. Again, probably very simple…