1

I'm trying to auto submit a form when the page loads using the jQuery code below:

$(document).ready(function(){
  $("#finds_expense").submit();
});

The form submission requires the parameters as JS. When I submit the form manually, it works perfectly, but when I use jQuery's (document).ready, somehow the parameters are passed as HTML, not JS. I appreciate any help on this. Had been stucked with this problem for quite some time. TQ.

Below is the code for finds_expense:

<div id="month-lookup"> 
<%= form_tag search_expense_path, remote: true, method: :get, id: "finds_expense" do %>
    <div class="form-group row no-padding text-center col-md-8">
        <div class="col-md-4">
            <%= text_field_tag :month,  params[:month], 
                placeholder: "month", 
                autofocus: true,  
                class: "form-control search-box input-lg" %>
        </div>
        <div class="col-md-4">
            <%= text_field_tag :year, params[:year], 
                placeholder: "year", 
                autofocus: true,  
                class: "form-control search-box input-lg" %>
        </div>
        <div class="col-md-2">
            <%= button_tag(type: :submit, class: "btn btn-lg btn-success", id: "submit_expense") do %>
                <i class="fa fa-search"></i> Send
            <% end %>
        </div>
    </div>
<%end%>

7
  • Try the second answer in the duplicate tag post. If it didn't work, i will reopen the question. Commented Sep 24, 2018 at 13:15
  • The solution did not work for me. I already try changing from .submit() to trigger('submit.rails'), but the parameters are still being passed as HTML, not JS. Appreciate to reopen the question. TQ Commented Sep 24, 2018 at 13:24
  • Ok, I reopened it :) Commented Sep 24, 2018 at 13:25
  • 1
    Do you have remote: true in your form ? <%= form_tag XXXX, remote: true%> Commented Sep 24, 2018 at 13:34
  • 1
    Can you share the finds_expense form code? Commented Sep 24, 2018 at 14:00

1 Answer 1

0

If you call the .submit() method in the form object the remote: true option won't work.

An option is to trigger the form using the .trigger('submit').

Another solution might be something like this:

$(document).ready(function(){
  var formData = $("#finds_expense").serialize();
  $.ajax({
   url: '...',
   data: formData,
   type: 'POST',
   contentType: 'apploication/script'
  });
});
Sign up to request clarification or add additional context in comments.

1 Comment

It works!. Thanks a lot @Rodrigo. I just changed the type from 'POST' to 'GET'. Many thanks!!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.