Search code examples
javascriptruby-on-rails-4page-refresh

Rails form_tag submit data without reload the whole page


I have model called search for rendering data from database, Using index method I'm accessing data from 3 models, display it on index page. I'm using form_tag in index page itself,

            <%= form_tag(search_path, :method => "get", :remote => true, id: "search-form") do %>
            <label for="Longitude ">Lon</label>
              <%= text_field_tag :lng, params[:lng], :id => "longitude", placeholder: "Longitude" %>
            <label for="Latitude ">Lat</label>
              <%= text_field_tag :lat, params[:lat], :id => "latitude", placeholder: "Latitude" %>

              <button class="btn waves-effect waves-light" >Process</button>


        <% end %>

I haven't created any partial view for this.

I have added :remote => true in form_tag,I don't know where and how to call ajax for this? I'm searching data from tables and getting updated data using '<%= escape_javascript @center_lat.to_json %>'; in index.html.erb file

Any help would be appreciable.


Solution

  • Because the form's remote option is set to true, the request will be posted to your controller as an Ajax request, looking for JavaScript. In order to serve that request, the action of your controller would look like this:

    def MyController
    
      ...
    
      def my_action
        respond_to do |format|
          format.js { ... }
          format.html { ... }
        end
      end
      ...
    

    The format.js {... allows the controller to respond to your Ajax request. So you need to render a .js or a .js.erb.

    Take a look here, it will be more enlightening: http://guides.rubyonrails.org/working_with_javascript_in_rails.html