Need JS to wait until the ajax completes(i.e. ajax success function executes), but Ajax is executing after the calling function completes. Added a callback but did not help. Log statements are inserted in the code to record the order. Currently, the order is:
- 1: 11ms
- 2: 3ms
- 3: 10ms
- 5: 32ms
- 7: 13ms
- 4: 23ms
- 6: 5ms
Need it to execute in numeric sequential order "1 to 7".
HTML:
<script>
$(document).ready(function(){
$('#btn').click(function() {
console.log('1');
callAjaxfunc();
console.log('7');
});
});
</script>
<button id="btn">Call Ajax!</button>
<div id="log"></div>
<div id="info"></div>
JS:
function callAjaxfunc() {
console.log('2');
callingAjaxfunc(function() {
console.log('6');
});
}
function callingAjaxfunc(callback) {
console.log('3');
$.ajax({
url: 'https://api.joind.in/v2.1/talks/10889',
data: {
format: 'json'
},
error: function() {
$('#info').html('<p>An error has occurred</p>');
},
dataType: 'jsonp',
success: function(data) {
var $title = $('<h1>').text(data.talks[0].talk_title);
var $description =
$('<p>').text(data.talks[0].talk_description);
console.log('4');
callback();
$('#info')
.append($title)
.append($description);
},
type: 'GET'
});
console.log('5');
}