Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

intercept form submit with jQuery

I want to intercept a submit via jQuery and first check if a file is present on the server. If it's present continue with the request, if not display a message and don't send the request. This is what I have:

$("#methodForm").submit(function(e){      checkIndex('upload/segments.gen').done(function() {         return true;     }).fail(function () {         e.preventDefault();         alert("No index present!");         return false;     }); }); 

this is the checkIndex():

function checkIndex(file){     return $.ajax({         url : file,         type:'HEAD'     }); } 

What happens is this: The file is present on the server, but the checkIndex returns with fail. First I see the alert popup and then it continues and sends the post request to the server.

I use the checkIndex() for other purposes as well where it works like expected so I'm pretty sure the error is somewhere in the submit routine. But I can't find out what's wrong with it.

like image 508
PogoMips Avatar asked Feb 14 '13 18:02

PogoMips


People also ask

How to submit a form by jQuery?

jQuery submit() Forms can be submitted either by clicking on the submit button or by pressing the enter button on the keyboard when that certain form elements have focus. When the submit event occurs, the submit() method attaches a function with it to run. It triggers the submit event for selected elements.

What is submit handler in jQuery?

jQuery submit() Method triggers the submit event when the form is submitted. The submit() method attaches an event handler function to the “form”, this event handler function executes when the submit event is triggered.

How can we submit a form without submit button?

The form can be submitted without using submit button by implementing a specific event attribute or by clicking the link. This task can be done by using the OnClick event attribute or by using the form. submit() method in Javascript.


1 Answers

You can't return out of a callback to an asynchronous method(such as ajax). Instead, prevent the submit all together, then submit it when you are ready.

$("#methodForm").submit(function(e){     e.preventDefault();     var form = this;     checkIndex('upload/segments.gen').done(function() {         form.submit(); // submit bypassing the jQuery bound event     }).fail(function () {         alert("No index present!");     }); }); 
like image 113
Kevin B Avatar answered Sep 28 '22 01:09

Kevin B