I want learn about jQuery AJAX using callbacks. So I create this as example.
<?php
sleep($_POST['sleep']);
echo 'sleep for '.$_POST['sleep'] .'sec';
?>
$(function () {
var timer = [5,2,3,1,4];
function sleep(timer) {
$.ajax({
url: 'ajax.php',
data: { sleep: timer },
type: 'post',
success: function(d){
console.log(d);
},
error: function(d){
console.log(d);
}
});
}
$('#ajax').click(function(){
$.each(timer, function(i, e) {
sleep(e);
})
});
});
Result: 1,2,3,4,5
What I want is : 5,2,3,1,4
(synchronous)
I know I can using async: false;
but this will hang up my browser and this is deprecated too. So I want to learn to doing sync using callback
Here is my fail script:
<script src="http://code.jquery.com/jquery-1.12.4.js" type="text/javascript"></script>
<script lang="javascript" type="text/javascript">
$(function () {
var timer = [5,2,3,1,4];
$.each(timer, function(i, e) {
sleep(e, function(d) {
console.log(d);
});
});
function sleep(sleepTimer, callback) {
$.ajax({
url: 'ajax.php',
data: { sleep: sleepTimer },
type: 'post',
success: callback,
error: function(data){
console.log(data);
}
});
}
});
</script>
Result: 1,2,3,4,5
instead 5,2,3,1,4
What am I doing wrong?
UPDATE: Thanks to people who remind me how bad is this. But i dont have any choice right now. My friends need my help to edit his drupal page. He only have admin previledge (not sysadmin). i only can edit view but cannot edit the controllers. why?
- only headquarters IT staff who allowed to do that.
- need bureaucracy and administration (user requirement, meeting, Quality Assurance [security testing + stress test). and the funny thing is, they check all the apps, not just the page which will affected by my script change only
- need time. 1 month is the fastest for non security change
hei.. this sounds funny right? even you just add 1 space, we need number 2 requirement that was they (headquarters staff) said. this true story. i know this because i'm in the same ministry with him.
the script is just download single file by click (of hundred), my friend wants me to add checkbox to allow his team to batch download. i can add checkbox, and download them by sequence (this is what i trying to do with synchronous ajax). but since this will hang up their browser, so i need the right way to doing this.
i have 2 choice here: using phantomjs (medium) or synchronous ajax (easy)
- 1st reason: since he will not pay me, ofc i choose the easy path.
- 2nd reason: i always avoid to use sync ajax as possible, but now i want to know how to doing sync ajax using callbacks.