Mau Ruiz
Mau Ruiz

Reputation: 777

How to render the AJAX response in RAILS

Ok, pretty simple question, I have working an AJAX method, what it does is that it searches in the database for specific information with a query. I can see in the Console that the query is being made, I can even see the "Post" in the Chrome Developer Console, when I click it I can see the HTML that I want to show, but i have no effing idea on how to render ir in the page.enter image description here

the :3000/ already has the html I want to show, but how do I update it??

The way I am showing it is this...

<%if not @itemsok.nil? 
  @itemsok.each do |searches|
%>
<table>
<tr>
  <td style="width:100px;"><%= searches.first_item.description %>  </td>
  <td style="width:150px; font-size:30px;"><%= searches.first_item_grade %>  </td>


  <td style="width:150px;"><%= searches.second_item.description %> </td>
  <td style="width:150px; font-size:30px;"><%= searches.second_item_grade %>  </td>
  <td style="width:150px; font-size:18px;"><a href="<%= contribution_path(searches.id) %>">Show</a>  </td>


</tr>
</table>

@itemsok is the variable where I save the items from the query.

Thanks, I think I'm missing something very silly here. Sorry for my terrible english.

UPDATE: The controller looks like this:

def index
    size1 = params[:size1]
    number1 = params[:number1]
    number2 = params[:number2]
    quiero = params[:quiero]
    tengo = params[:tengo]

    if (not number1.nil?) and (number1 != "")
      item1 = Item.find(number1)
    elsif not quiero.nil?
      quiero.strip!
      item1 = Item.find(:first, :conditions => ['lower(description) LIKE ?', "%#{quiero.downcase}%"])
    end

    if (not number2.nil?) and (number2 != "")
      item2 = Item.find(number2)
    elsif not tengo.nil?
      tengo.strip!
      item2 = Item.find(:first, :conditions => ['lower(description) LIKE ?', "%#{tengo.downcase}%"])
    end

    if (item1 and item2)

      @itemsok = Contribution.where("first_item_id = ?",item1.id).where("second_item_id = ?",item2.id).where("second_item_grade = ?",size1)


      respond_to do |format|
       format.html
       format.js

      end
    end

Upvotes: 1

Views: 3462

Answers (1)

josephrider
josephrider

Reputation: 943

In your respond_to block put format.js above format.html.

Make sure you have index.js.erb in your view folder for the controller. This index.js.erb(comes from the action name) should have a jQuery statement like the following if you're using rails 3.1+:

$('#DOMelementToPlaceContent').html(<%= escape_javascript(render :partial => "partial/location") %>);

This will replace the content of the DOM element with ID DOMelementToPlaceContent with the content in the specified partial.

Also, you should think about moving the logic for your search to a search action in the same controller in which case you'll need a search.js.erb file in the view folder for the controller.

Upvotes: 2

Related Questions