Waiting For $.post To Finish
Solution 1:
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.
Solution 2:
<scripttype="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;
// it reaches this, showing us that there was no error!alert('Im alive!!!');
// and a whoooole bunch of other code here...
}
else
{
test = false;
// THIS gets executed, despite the fact that we set test to true!alert('Awww....');
}
}
}
</script>
Solution 3:
Solution 4:
Too messy? If you indent more than one space everything is much more readable and still works fine.
var test = false; // NOW it's global// Just so we can use the method againfunctionpostSomething() {
$.post('test.php', {}, function(result) {
if(result === 'yes') {
alert('Its true! Hurraaay!');
test = true;
alert('Im alive!!!');
} else {
test = false;
alert('Awww....');
}
});
}
$(document).ready(function() {
postSomething();
});
Hideous though it is.
Solution 5:
The JQuery .post() method asynchronously connects to your server script. You utilize the callback feature in order for the program to make use of the data once the response is returned from the script.
Instead of attempting to processing the data synchronously after the call to post, process the data when the response is received. Utilize functions to make your code more readable.
$(function() {
postTest();
});
function postTest() {
$.post(
'test.php',
{},
function(response) {
if(response == 'yes') {
testSuccess();
} else {
testFailure();
}
}
);
}
function testSuccess() {
alert("Success");
}
function testFailure() {
alert("Failure");
}
Post a Comment for "Waiting For $.post To Finish"