Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
965 views
in Technique[技术] by (71.8m points)

ajax - Jquery form check returns true, but need to return false

I am running this form check when the form is submitted:

if((formData[4].value == 1 || formData[4].value == 2) && !formData[2].value) { 
    alert('Please fill out the key field');
    return false;
} else {
    $.ajax({
        url: "/ajax/key_check.php",
        cache: false,
        data: "key=" + formData[4].value,
        dataType: "html",
        success: function(data) {
            if(data == 1) {
                alert('Key already exists');
                return false;
            }
        }
    });

    return true;
}

The script works, it alerts key already exists if data does == 1, however the form still submits. I thought by returning false if data == 1 would stop the form from processing, however it continues and adds the key anyway and popups up key already exists message. How can I stop the form from submitting if data == 1? I tried even doing this:

if(data == 1) {
    alert('Key already exists');
    return false;
} else {
    return true;
}

Then removed the return true at the bottom of the script, but the same issue happens. Pop up comes up but the form still gets processed.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

A return in the callback returns from that callback, not the parent function like you want...however you can get the effect you want, like this:

if((formData[4].value == 1 || formData[4].value == 2) && !formData[2].value) { 
    alert('Please fill out the key field');
    return false;
} else {
    $.ajax({
        url: "/ajax/key_check.php",
        cache: false,
        data: "key=" + formData[4].value,
        dataType: "html",
        success: function(data) {
            if(data == 1) {
                alert('Key already exists');
            } else {
              $("#someForm")[0].submit();
            }
        }
    });
    return false;
}

What this does is never submit directly, but if the check is ok, calls the *native .submit() method, submitting the form and not running this handler again.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...