Can I preventDefault(); inside of an ajax callback?

I'm doing some form validation, and I'm having trouble with what I'm trying to accomplish. I want to be able to validate my zip code on blur of the field, but also call the same function to validate zip on submit of the form, and prevent the form from being submitted if the zip code is invalid. My code (generically) goes something like this.

function validateZipCode(event){
    $.getJson(
        url,
        params,
        function(data){
            if(data.response === false){
                someError.show();
                event.preventDefault(); //stop the form from being submitted
            }    
        }
    );
}

$('#someForm').submit(function(event){
    validateZipCode(event);
});

$('#zipInput').blur(function(event){
    validateZipCode(event);
})

I've tried using the methods located in this jQuery pass more parameters into callback post, but I still can't seem to accomplish what I need. Any help is appreciated.

Answers:

Answer

No, by the time the callback from the AJAX event fires, the event will have already bubbled and the form submitted. One way you could accomplish this is cancel the form from submitting and then submit it manually if it passes the requirements from the AJAX request.

Answer

You need to prevent the event's default action before it's bubbled up and handled by the browser. $.getJson returns control and allows the validateZipCode function to finish first, so you need to do this:

function validateZipCode(event){
    event.preventDefault(); //stop the form from being submitted
    $.getJson(
        url,
        params,
        function(data){
            if(data.response === false){
                someError.show();
            }
        }
    );
}

$('#someForm').submit(function(event){
    validateZipCode(event);
});

$('#zipInput').blur(function(event){
    validateZipCode(event);
})
Answer

No, without using the ajax() method and setting async to false, you can't return anything from your ajax request.

A better idea would be to always prefent default on your submit, and then manually submit the form in the ajax callback.

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.