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.

6
  • Form submission works using submit() function of form as w3schools.com/jsref/met_form_submit.asp Commented Jan 27, 2018 at 1:50
  • Please post the rest of the JS and the Html. There isn't enough here to make sense of it. Commented Jan 27, 2018 at 1:52
  • Just make sure the submit function returns false as in the post stackoverflow.com/a/48454059/4148965 to prevent window level form submit Commented Jan 27, 2018 at 1: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 Commented Jan 27, 2018 at 1:54
  • For that I added another comment, so that form submit can be prevented in window. Hope that helps Commented Jan 27, 2018 at 1:55

2 Answers 2

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 } }) })` 
Sign up to request clarification or add additional context in comments.

1 Comment

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
0

try to use trigger, like this

jQuery('#FormSubmit').trigger("click"); 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.