Vidar 01 February 2009
Ajax, JSON and Rails

I’ve heard about JSON for a long time, but I wasn’t really sure how and why to use it, I tried to as far as possible to avoid Ajax or javascript if I could, it’s too time consuming. But in my current project, I actually have a use case for it. Here is how I use Ajax to get a bunch of objects in JSON format and insert their data into the current DOM.


# In my controller I have this method
def get_data
  colors = Color.all
  respond_to do |format|
    format.js{ render :json => colors.to_json }
  end
end

# in my view I have this element hook
<div id="inventory" />

# in my javascript file I have this code (jQuery)
$.fn.fillSizes = function(){
  element = $(this);
  select = $('<select>')
    .addClass('color')
    .append("<option>Wait...</option>");
  element.prepend(select);
	  
  $.getJSON('/products/get_data', null, function(data){
    $.each(data, function(){
      select.append('<option value="' + this.color.id + '">' 
      + this.color.name + '</option>');
    });
    select.find("option:first").remove();
  });
    
  return element;
}

// Invoke the above function on this object
$('#inventory').fillSizes();

This will create a select box populated with the data from the JSON returned from the server. It will also display a “Wait…” message while loading the data. The cool thing about it is that it is compact. There is only data, no tags.

« Back to posts Write a new comment

Feed-icon 1 Comment

Adveweemi 6 months ago

Unadulterated words, some unadulterated words dude. Totally made my day!!

Textilized formatting

How to use the text area
_a phrase_ a phrase
*a phrase* a phrase
_*a phrase*_ a phrase
"Link":http://link.com Example link
Complete reference