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. 🙂
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 callalert()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.