<%= lab...">

Rails form_tag remote example

I have this incredible simple form:

<%= form_tag("/portal/search", method: 'get', remote: true ) do %>

  <%= label_tag(:query, 'Search for:') %>
  <%= text_field_tag(:query) %>
  <%= submit_tag("Find") %>

<% end %>
<div id="results"></div> 

I know from the documentation, I can use AJAX through the remote option:

<%= form_tag("/portal/search", method: 'get', remote: true ) do %>

Then I'm stuck. I know how to generate results in a / partial view, but how do I get this partial inside a div element? I know a bit of jQuery, so I can select an element. I found many results, but they seem to have missed this moment of light bulbs for me. I am using Rails 4.1.6

My results are just simple entries from the model, such as Book (title, author)

Thanks for the help!

EDIT

I won the cup for missing this moment with a long shot. I had to add search.js.erb to the view folder instead of assets.

+4
3

, @results .

:

respond_to do |format|
  format.html {render or redirect_to wherever you need it}
  format.js 
end

search.js.erb js . :

$('#results_div').html("<%= j @results.pluck(:title).join('<br/>') %>")
+7

remote: true jquery-ujs ajax ( javascript lib app/assets/JavaScripts/application.js).

Ajax- "text/javascript". :

# action
def search_query
  respond_to do |format|
    format.js { 
      # additional code
    }
  end
end

(search_query.js.erb) javascript, . $('#my_div_id').html('my html text'), div HTML.

- json, :

form_tag("/jquery_ujs/search_query", remote: true, 'data-type' => :json) do
  # ....
end

:

# action
def search_query
  respond_to do |format|
    format.json { render json:  @my_object }
  end
end

:

<script>
  $(document).ready(function(){
    $("form#my_form").on('ajax:success', function(event, data, status, xhr) {
      console.log("Great!");

      // use data to access to your json data structure
    });

    $("form#my_form").on('ajax:error', function(event, xhr, status, error) {
      console.log("sorry mate!");
    });

    // ....
  })
</script>

html- ( , , , ), :'data-type' => :html format.html { render layout: false }

+3

Ajax

-, Rails UJS ( javascript) "" ajax . , , Ajax , Rails UJS Ajax

, response Ajax - ,

: -

#app/assets/javascripts/application.js
$(document).on("ajax:success", ".element", function(status, data, xhr) {
   // do something here
});

#app/controllers/portal_controller.rb
class PortalController < ApplicationController 
  def search
     respond_to do |format|
        format.js #-> app/views/portal/search.js.erb
        format.html
     end
  end
end

#app/views/portal/search.js.erb
//something here

Fix

div

JS:

#app/controllers/portal_controller.rb
class PortalController < ApplicationController
   def search
      @results = ...
      respond_to do |format|
         format.js
         format.html
      end
   end
end

#app/views/portal/search.js.erb
$(".div").html("<%=j render @results %>");
+1
source

All Articles