Friday, May 17, 2024
 Popular · Latest · Hot · Upcoming
114
rated 0 times [  121] [ 7]  / answers: 1 / hits: 23689  / 13 Years ago, fri, june 3, 2011, 12:00:00

It appears that my script does not want to wait for the $.post call to finish. Thats a problem. Here is some pseudo code:



<script type=text/javascript language=javascript>
$(document).ready(function(){
// Global var, to be used everywhere in the ready scope
// Note its default value!
var test = false;
$.post('test.php',{},function(result){
if(result=='yes')
{
// This gets executed!
alert('Its true! Hurraaay!');
test = true;
}
else
{
test = false;
}
}

if(test==false)
{
// THIS gets executed, despite the fact that we set test to true!
alert('Awww....');
}
// it reaches this, showing us that there was no error!
alert('Im alive!!!');
// and a whoooole bunch of other code here...
}
</script>


What is the best way to make sure that my Post call is finished before continuing, without hanging the browser? Hoping for something that is not too messy. :)


More From » jquery

 Answers
58

Not too messy is using callbacks properly.



Just create some function outside the .post() call and call it inside .post() when you think it is appropriate. You make many callbacks and use them inside the AJAX calls in a really flexible way.



In your case, because you only call alert(), there is no need to create additional functions - just call alert() inside .post() call. If your code gets bigger, consider creating separate functions.



This is how JavaScript and asynchronous calls work. Get used to it and use its power to write very clean and maintainable code.


[#91875] Thursday, June 2, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
isham

Total Points: 69
Total Questions: 86
Total Answers: 86

Location: Anguilla
Member since Sun, Jan 29, 2023
1 Year ago
;