Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Chrome scrolling to the top of the page after a remote form request

Rails version: 5.2.2

Chrome version: 78.0.3904.87

While testing my website on Chrome today, I noticed that it scrolls to the top of the page whenever I submit an AJAX request. This behavior is undesirable and does not happen on other browsers, such as Firefox. I've tried debugging the issue but couldn't figure out what's wrong.

Here's what my form looks like:

<div id="container">
  <%= form_for(obj, method: :post, url: url, remote: true) do |f| %>
    <button id="obj-<%= obj.id %>-btn" type="button" class="btn btn-primary obj-btn" title="Add" data-toggle="tooltip" data-placement="left">
      Add
    </button>
  <% end %>
</div>

Here's my JavaScript for submitting the form:

$("#container").on("click", "form > .obj-btn", function(e)
{
  $(this).tooltip('hide');

  var form = $(this).parent();

  form.submit();
});

After the request is sent to the server, the controller runs JavaScript in a create.js.erb file.

I looked at other threads that suggested adding e.preventDefault() or return false; in the submit handler, but none of them worked for me.

What could be the problem? Thanks in advance for any help.

like image 455
Alexander Avatar asked Nov 03 '19 06:11

Alexander


2 Answers

You should be listening for and catching the submit event on your form, not the button click event. If you use e.preventDefault() in that case, you should be able to preclude the default submission behavior causing your page to refresh. So your approach would resemble something to this effect, roughly:

$(document).ready(function () {
  // ***** Listen to submit event on the form itself ***** //
  $('#form').submit(function (e) {

    e.preventDefault();

    // Capture data from form 
    // and manually submit by AJAX here

  });
});
like image 59
Greg Brodzik Avatar answered Oct 20 '22 04:10

Greg Brodzik


If you are using e.preventDefault(), the page wouldn't refresh at all after the AJAX request is successful. So you need to refresh the page in the javascript with window.location.reload()

like image 20
Ezenwa Avatar answered Oct 20 '22 05:10

Ezenwa