Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

submit form does not stop in jquery ajax call

I got following code :

$.ajax({
    type: "POST",
    async: false,              
    url: "CheckIdExist",
    data: param,
    success: function(result) {
        if (result == true){
            return false;
        }                                 
    },
    error: function(error) {
        alert(error);
        return false;
    }
});

if ajax return value is true, form needs to stop submit.

but it does not stopping submit form.

any help please.

like image 785
Ray Avatar asked Apr 30 '09 00:04

Ray


2 Answers

I assume you have something like:

form.submit(function(event) {
    $.ajax(...);
});

You want to return false (or call event.preventDefault()) in the event handling function itself, and not in the AJAX call, such as:

form.submit(function(event) {
    event.preventDefault();
    $.ajax(...);
});
like image 156
DarkWulf Avatar answered Sep 22 '22 10:09

DarkWulf


A slight variation of this question is: I want to use jquery and ajax to present an error message to a user, but then to do normal processing if there is no error.

Suppose method "check" returns a response that is empty if there is no error, and has the error(s) in it if there are any.

Then you can do something like this in your ready function:

$("#theform").submit(function() {
    var data = { ... }
    $.get('/check', data,
        function(resp) {
            if (resp.length > 0) {
                $("#error").html(resp);
            } else {
                $("#theform").unbind('submit');
                $("#theform").submit();
            }
    });
    event.preventDefault();
});

So, how does it work? When the outer submit function is triggered, it builds the data needed for the AJAX call (here the higher level function get). The call is scheduled, and the main thread of operation immediately continues, but the submit is unconditionally stopped, so nothing apparent happens.

Some time passes, and the AJAX call returns the result of the request. If non-empty, the result is shown to the user.

If the response is empty, however, the submit function is unbound. This prevents the ssytem from making an extra call through the outer submit function. The inner submit function is called. This triggers an actual form submission to the form's target, and life goes on as expected.

like image 23
Jim Penny Avatar answered Sep 23 '22 10:09

Jim Penny