ruby rails JSON
Showing posts with label ruby rails JSON. Show all posts

Saturday, December 09, 2006

JSON data with ruby rails

My requirement is to fetch the JSON data from rails server and use it to update the place marks on a google map. I start with a view form that submits the user query. I am submitting this query form using the form_remote_tag

 

<%= form_remote_tag (:update =>; 'searchMapResults',:loading =>; "Element.show('spinner')",:complete =>; " Element.hide('spinner') ; ",
:id =>; 'searchMapForm' ,
:url =>; {:action =>; :searchMap}) %>;

Next, we go to the controller action that handles this request. searchMap action should fire a SQL query, load some data in instance variables and return part of data as JSON string to the UI. The controller action looks like




def searchMap
 # get the area and search token
 filter = params[:filter]
 binds = Hash.new 

 sql = { some sql ..... }
 @pmarks = Pmark.find_by_sql [sql, binds] payload = Hash.new
 points = Array.new

 @pmarks.each do |pmark|
 point = Hash.new
 point[:latitude] = pmark.latitude
 point[:longitude] = pmark.longitude
 point[:name] = pmark.name

 point[:description] = pmark.description 
 points.push(point)
 end
 payload[:markers] = points 
 @jsonData = payload.to_json
 logger.debug( " gloo : markers json data" + @jsonData);
 render(:layout => false )

end

We fire a SQL query and load the results. Next we create a Hash (payload) of arrays (markers) of hash (point). we convert this payload RUBY data structure to JSON string using the Active support JSON gem. I installed this gem using command


$gem install json

This gem provides a ready made to_json method. Next step is to use this JSON data string inside our view and javascript files. Our searchMap.html (view for this action looks like:)
 


<script>
loadPoints('<%= @jsonData %>');
</script>

And finally inside a loadPoints javascript function we evaluate the JSON data and use it.
 

function loadPoints(content){
 var jsonData = eval('(' + content + ')');
  for (var i=0; i<>
   alert(jsonData.markers[i].name);

  }
 }



© Life of a third world developer
Maira Gall