Marco Tapia

my way to blog about development

Prototype Ajax.Response with Rails Json

| 1 Comment

Json is just way faster than updating partials with Rails, so why didn’t I use it before?
Well, basically I was just new to the Rails thing and it’s just easy to update with a partial. But I was presented with a choice recently, I had to update a resource intensive Google Map part of the page with an textfield keyup event.
At first glance it was cake, just observe the keyup event and send an Ajax call to update the partial. That got really slow since I had to create the map object everytime.
The other answer that you might be thinking is why didn’t he just update it with the page element in rails from the controller.
Is not that simple, I wanted to write this as separated from the backend as possible as I want to share this as an API in the future, so having view updates in the backend or in a partial was not going to cut it.
The task was simple, it was just moving the map location and setting a marker, it’s literally two lines of code so why not just pass a Json response from the rails backend and update the map.
Seems easy until I found that I couldn’t do the following:

				new Ajax.Request(url, {
					parameters: {query: this.getValue()},
					method: 'get',
					onSuccess: function(transport,){
						var response = transport.responseText;
						alert(response.somevalue);
					}
				});

I will always get the somevalue undefined. I also found that it was because even though I would send the response as json, for some reason it was in json format but not an actual json object.

This was my rendering line:

     render :json => "{somevalue:#{my_value.to_json}}"

I found that I only needed to change this line:

     var response = transport.responseText.evalJSON();

And that was how I got my Json working after an hour of googling. I found it on the prototype api documentation.
Read the manual kids!!!
Firebait

One Comment

  1. nice article, keep the posts coming

Leave a Reply

Required fields are marked *.

*