简体   繁体   中英

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.

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!");
    });
});

It does'nt really work like that, checkIndex is asynchronous, so by the time it returns anything, the form is submitted, and the return statements are in a different scope as well, try something more like this:

$("#methodForm").submit(function(e){
    e.preventDefault(); //prevent submit
    var self = this;
    checkIndex('upload/segments.gen').done(function() {
        self.submit(); //submit if ajax OK
    }).fail(function () {
        alert("No index present!");
   });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM