AJAX - Form submit requires two clicks to take effect

Viewed 47

I tried changing the .click to .on('click' ....) and .submit

also tried to add async: false

but it takes a second click to call success

Is there anyone who can help? I would be very grateful!

Button (Ajax Trigger)

  <p>
    <%= submit_tag l(:button_save), :name => nil, :id => 'time_entry_submit' %>
    <%= link_to_function(l(:button_cancel), "$('#new_time_entry_form').toggle();$('#report_menu_options').toggle();".html_safe) %>
  </p>

js.erb

$('#time_entry_submit').click(function(evt){
  evt.stopPropagation();
  evt.preventDefault();
  var url = $(this).parents('form:eq(0)').attr('action');

  $.ajax({
    url: url,
    method: 'POST',
    datatype: 'json',
    success: function(response) {
      window.alert(response);
      location.reload();
    }

  })
  return false;
})

When I click a second time alert shows

var flashNotice = $("#flash_notice");
flashNotice.remove();
$("#flash_error").remove();

and I put the console.log inside the .click, and it appears on the second click

1 Answers

you're using UJS so the js code come from js.erb will be send to client when the first time you click the submit button, but that js code is just setup the click function to call ajax, it's not triggered, so in the first time it'll not do anything else.

now you could trigger your js code immediately as below

// setup
$('#time_entry_submit').click(function(evt){
  // your code
});

// trigger
$("#time_entry_submit").trigger( "click" );

you should not use UJS in this case, your js code will be send to client everytime you click the submit button.

you could move your js code into a .js file that will be packed into application.js by webpack, then your js code will be setup immediately as you load webpage, so it's just only loaded one time.

Related