troll troll - 2 months ago 6
Ruby Question

Showing whole page after ajax request in Ruby on Rails

I'm creating one web application using RoR, but now I'm facing some issues like one I have used ajax now if request sent he return whole page, below my code

home_controller

def index
@post = Post.paginate(page: params[:recent], :per_page => 10).order('post_id DESC').joins("LEFT JOIN cities ON cities.city_name = city_name AND cities.city_id = post.city_id").where(["city_name LIKE ? ", "%#{params[:city_name]}%"])
end


View

<form action="<% home_path %>" method="get">
<select name="city_name" class="form-control form-down" id="mySelect">
<option selected>Sort By</option>
<option value="Berlin">Berlin</option>
<option value="Tokyo">Tokyo</option>
</select>
</form>

<div id="mySelectedArea">
<% @post.each do |p| %>
<%= p.title %>
<%= p.location%>
<% end %>
</div>


Ajax

<script type="text/javascript">
jQuery(function($) {
$("#mySelect").change(function() {
var city_name = $('select#mySelect :selected').val();
if(city_name == "") city_name="0";
$.ajax({
type: 'GET',
url: '<%= home_path %>',
data: 'city_name=' + city_name,
success: function(data) {
$("#mySelectedArea").html(data);
},
})
return false;
});
})
</script>

Answer

I think you did not understand what actually you need, my solution is at first you create a method like below:

def query_method
  #-> create functionality what you need
end

then your html options

<select name="city_name" class="form-control form-down" id="mySelect">
  <option selected>Sort By</option>
  <option value="Berlin">Berlin</option>
  <option value="Tokyo">Tokyo</option>
</select>

Then call to ajax

<script type="text/javascript">
  jQuery(function($) {
    $("#mySelect").change(function() {
       var city_name = $('select#mySelect :selected').val();
       $.ajax({
       type: 'GET',
       url: '<%= query_data_path %>', #-> call to your controller/action which newly created
       data: 'city_name=' + city_name,
       success: function(data) {
           $("#mySelectedArea").html(data);
       },
    })
    return false;
   });
 })
 </script>

And finally where you need to show data just like this

<div id="mySelectedArea"></div>