jquery - entire page get posted back even with ajax [rails] -


what i'm doing should pretty simple, have page display records if request http , recrods between dates if ajax. here how page looks

this index.html.erb

<h1>jobs history</h1> <hr> <div class="form-inline">   <div class="col-md-12">     <div class="col-md-4">       <%= label_tag(:start_date) %>     <div class='input-group date' id='datetimepicker2'>       <%= text_field_tag :start_date , "", {class:'form-control'} %>       <span class="input-group-addon">                         <span class="glyphicon glyphicon-calendar"></span>                     </span>     </div>       </div>     <div class="col-md-4">       <%= label_tag(:end_date) %>     <div class='input-group date' id='datetimepicker1'>       <%= text_field_tag :end_date , "", {class:'form-control'} %>       <span class="input-group-addon">                         <span class="glyphicon glyphicon-calendar"></span>                     </span>     </div>       </div>     <a id="searchbtn" class="btn btn-skin btn-md"  href="#">search</a>   </div> </div> <div id="items_grid" > <%= render partial: 'histories', locals: {bookings: @bookings} %> </div>   <script>   $('#datetimepicker1').datetimepicker();   $('#datetimepicker2').datetimepicker();   $('a#searchbtn').click(function(){     $.ajax({       url: "<%= provider_history_index_path %>",       type: "get",       data: {start_date: $('#start_date').val(), end_date: $('#end_date').val()},       success: function(resp){ }     });   });  </script> 

pretty normal right , here controller:

   respond_to :html, :js   def index     if request.xhr?       respond_to |format|         @bookings = current_user.booking_providers.where(visit_end_date:     params[:start_date]..params[:end_date])         format.js       end     else       @bookings = current_user.booking_providers     end 

and here index.js.erb

$("#items_grid").html("<%= escape_javascript(render partial: 'histories', locals: { bookings: @bookings} ) %>"); 

the problem when fill dates , click on search, ajax fire , render partial new records after index called , full page postback happens overwrite new records. don't know why

i got answer reddit user jemminger, in case have similar problem

the reason because intercepting submit can perform ajax call, not preventing default behavior of form posting normally. every jquery click handler receives event. call preventdefault() on event.

$('a#searchbtn').click(function(evt){ /* <--- event object passed handler jquery */   evt.preventdefault();  /* <--- stop performing normal behavior */    $.ajax({     url: "<%= provider_history_index_path %>",     type: "get",     data: {start_date: $('#start_date').val(), end_date: $('#end_date').val()},     success: function(resp){ }   }); }); 

Comments

Popular posts from this blog

aws api gateway - SerializationException in posting new Records via Dynamodb Proxy Service in API -

asp.net - Problems sending emails from forum -