1

I am rendering a search form in Rails 5.2.2 and have logic that determines if the request should be an AJAX request or an HTML request. Here's what my form looks like:

<form id="form" action="/search" data-prev-query="test" data-remote="true" method="get">
  <input type="text" name="q" id="search_query" value="test">
</form>

If the search query is different than the data-prev-query attribute on the form, then I would like the form submission to be an HTML request so that it'd reload the page. Otherwise, I'd like the form submission to be an AJAX request. Here's my logic for removing the data-remote property from the form programmatically:

$("#form").find("#search_query").change(function(e)
{
  var theForm = $("#form");

  var currentSearchQuery = theForm.find("#search_query").val();
  var prevSearchQuery = theForm.data("prev-query");

  var isRemote = (currentSearchQuery === prevSearchQuery);

  if (isRemote === true)
    theForm.attr('data-remote', isRemote);
  else
    theForm.removeAttr('data-remote');
});

I've confirmed that this code removes or adds the data-remote attribute as expected. However, even though the data-remote attribute is removed, the form is still submitted as an AJAX request.

How can I get the form to submit as an HTML request? I am not using Turbolinks, by the way.

Alexander
  • 3,959
  • 2
  • 31
  • 58
  • 1
    https://stackoverflow.com/questions/9907183/use-js-to-change-form-from-remote-to-non-remote-in-rails-3-haml – chumakoff Mar 05 '19 at 10:52

1 Answers1

2

As @chumakoff shared in a comment, I found my answer on this SO post. I also had to call removeData('remote') to clear jQuery's internal cache. Below is my updated code that works. I put a comment next to the added lines.

$("#form").find("#search_query").change(function(e)
{
  var theForm = $("#form");

  var currentSearchQuery = theForm.find("#search_query").val();
  var prevSearchQuery = theForm.data("prev-query");

  var isRemote = (currentSearchQuery === prevSearchQuery);

  if (isRemote === true)
  {
    theForm.removeData('remote'); // ADDED LINE
    theForm.attr('data-remote', isRemote);
  }
  else
  {
    theForm.removeAttr('data-remote');
    theForm.removeData('remote'); // ADDED LINE
  }
});
Alexander
  • 3,959
  • 2
  • 31
  • 58