I am submitting a form and getting JSON as a respond. My goal is to only submit the form if the received json.ok value equals true.
$("form").submit(function() {
var _this = $(this);
// send request to server, validate json, if ok return true
$.getJSON("/", ($(this).serialize()), function(json) {
if (json.ok == true) {
return true;
}
});
return false;
});
I know it wouldnt work like that because the return false is already fired before the asynchronous callback of the getJSON function gets fired, but I am trying to figure out a way to do it. I already tried to asign the return value to a var and returning that var to the mainfunction, but there is always the problem of the asynchronous function which the mainfunction is not waiting of.
Do you know of a good metho开发者_StackOverflowd to make this work?
you can't return true using an asynchronous call.
what you need to do is mostly there already - check the values, and then if ok, instead of "return true;", you just submit the form again.
you may need to unbind the onsubmit event before you submit it.
try replacing the "return true;" with "_this.unbind('submit').submit();"
What you want to do is to use the callback function to perform the submit.
// send request to server, validate json, if ok return true
$.getJSON("/", ($(this).serialize()), function(json) {
if (json.ok == true) {
$("form").submit();
}
});
精彩评论