0

Simple Ajax popup with a form collecting 3 fields of data, and a submit button. I can't programatically trigger the submit button though.

jQuery('#FormSubmit').click() 

doesn't work. Neither does

jQuery('#FormSubmit').mousedown()

nor

document.getElementById("FormSubmit").click();

A real mouse click on the button works, but programmatically triggering it doesn't. It either posts the form in a non-AJAX way (page reload with post data appended to the url) or does nothing.

Anyone know the reasons why? Is there something specific to Ajax to prevent this?

Edit: Just tested triggering the submit event on the form instead, and that also posts the form in a non-AJAX way.

Steve Price
  • 600
  • 10
  • 28
  • Form submission works using `submit()` function of form as https://www.w3schools.com/jsref/met_form_submit.asp – Kamal Singh Jan 27 '18 at 01:50
  • Please post the rest of the JS and the Html. There isn't enough here to make sense of it. – npearson Jan 27 '18 at 01:52
  • Just make sure the submit function returns `false` as in the post https://stackoverflow.com/a/48454059/4148965 to prevent window level form submit – Kamal Singh Jan 27 '18 at 01:52
  • @KamalSingh I was just trying that as you added your comment. It doesn't work correctly as it still posts the form non- AJAX with a page reload and appended url – Steve Price Jan 27 '18 at 01:54
  • For that I added another comment, so that form submit can be prevented in window. Hope that helps – Kamal Singh Jan 27 '18 at 01:55
  • Post your html and existing js code. – Eddie Jan 27 '18 at 02:09

2 Answers2

0

You need to use submit, or if you want you can write something like this:

`$('#formSubmit').on('click', function (event) {
    event.preventDefault();
    var input1 = $('#someInput1').val().trim();
    var input2 = $('#someInput2').val().trim();
    $.ajax({
       url: 'someUrl',
       type: 'POST',
       success: function (result) {
         //do something with the result
       }
    })
})`
Marco Principio
  • 475
  • 3
  • 9
  • The event.preventDefault() stops the default behavior of the form submit button. Namely, it's default behavior is to submit the form and reload the page. Adding the prevent default will stop that and allow your ajax call to work – Marco Principio Jan 27 '18 at 01:59
0

try to use trigger, like this

jQuery('#FormSubmit').trigger("click");
Shridhar Sharma
  • 2,337
  • 1
  • 9
  • 13