Success function does not occur until AJAX completes

I am trying to use the jQuery dialog beforeClose . I check if the user form data is formatted correctly, and if not, returning false in beforeClose so that the user can re-enter the information.

Dialog code calls the submituserupdateform function in beforeClose :

 .dialog({beforeClose: function () { formresult=submituserupdateform($('#myaccountdialog').find('form')); if (formresult !="okay"){ return false; } }}) 

The submituserupdateform function checks 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 searched and found https://stackoverflow.com/questions/1632039/return-value-from-ajax-call , but I already set myresult inside my callback. I also tried ajaxComplete , ajaxSuccess , .done . According to the console, nothing I tried installs myresult ; I always get:

Uncaught ReferenceError: myresult is not defined

It should be a simple mistake, please help me if you see my mistake!

+1
source share
4 answers

Asynchronous ajax behavior will make your function return before the ajax-success callback (this is what you don't want)

You can add async : false

  var myresult ="": $.ajax({ type: "POST", url: url, data: $tgt.serialize(), async:false, success: function(data){ 
+1
source

This is because myresult bound only to a success block. Declare it out

 function submituserupdateform($tgt){ var url='./includes/admin/user/myaccount.php'; var myresult; $.ajax({ type: "POST", url: url, data: $tgt.serialize(), success: function(data){ $("#myaccountdialog").html(data); if ($('.error').length){ myresult= "notokay"; } else { myresult ="okay"; } return myresult; }, dataType: "html" }); } 

And also, as @Mohammad Adil noted, there is a chance that the code below to execute before formResult will be assigned a value from AJAX

 if (formresult !="okay"){ return false; } 

In this case, you can go with async = false , as suggested to him. Since your code always works, you should add this too

+1
source

Your

 var myresult 

not available globally for a function declaring it as follows

 function submituserupdateform($tgt){ var myresult; 
0
source

$. ajax is asynchronous, which means it will send a request and return immediately. Normal script execution continues while an ajax request is running in the background.

What you need to do is show a wait icon when an ajax request is executed in the background save dialog box. After returning the ajax request, process the result using ajax event handlers and depending on the result, close the dialog box or keep it open, showing an error message.

0
source

Source: https://habr.com/ru/post/1480984/


All Articles