I am trying to use the jQuery dialog
box beforeClose
feature. I am checking to see if user form data is formatted properly and if not, returning false
to the beforeClose
, so the user can re-enter information.
The dialog box code calls the function submituserupdateform
in the beforeClose
:
.dialog({beforeClose: function () {
formresult=submituserupdateform($('#myaccountdialog').find('form'));
if (formresult !="okay"){
return false;
}
}})
The submituserupdateform
function checks to see if there was an error in the code:
function submituserupdateform($tgt){
var url='./includes/admin/user/myaccount.php';
$.ajax({
type: "POST",
url: url,
data: $tgt.serialize(),
success: function(data){
$("#myaccountdialog").html(data);
if ($('.error').length){
var myresult= "notokay";
} else {
var myresult ="okay";
}
},
dataType: "html"
});
return myresult;
}
I have searched, and found https://stackoverflow.com/questions/1632039/return-value-from-ajax-call, but I am already setting myresult
inside my success callback. I have also tried ajaxComplete
, ajaxSuccess
, .done
. According to the console, nothing I have tried sets myresult
; I always end up with an:
Uncaught ReferenceError: myresult is not defined
This must be a simple error, please help me if you see my mistake!
$.ajax is asynchronous which means it will post the request and return immediately. Normal script execution will continue while ajax request is running in the background.
What you should do is show some waiting icon while ajax request is running in the background keeping dialog open. Once ajax request returns, handle result using ajax event handlers and depending on the result close the dialog or keep it open showing error msg.
The asynchronous behaviour of ajax will make your function return before the ajax success callback- (that is what you don't want)
You can add
async
:false
That's because
myresult
is scoped only to success block. Declare it outsideAnd also, as @Mohammad Adil pointed out, there is a possibility that the below code to execute before
formResult
gets assigned with a value from AJAXIn this case, you can go with
async = false
as suggested by him. For your code works always, you should add this tooYour
is not globally available to the function declare it like this