Basic AJAX with Promise
http://stackoverflow.com/questions/24805544
by klenwell
HTML
<div id="parent-panel">
<div id="original-panel" class="panel">Original Panel</div>
</div>
CSS
.panel {
padding: 1em;
border: 1px solid #ccc;
}
JavaScript
var dfd = $.Deferred();
function loadPanel(url) {
// Randomly redirect 2/3 of the time (this code is used to simulate the
// response from http://httpbin.org)
var redirect = ( Math.random() < 0.666 ) ? url : false;
var ajaxParams = {
type: 'GET',
url: url,
dataType: 'json',
data: {redirected: redirect}
};
$.ajax(ajaxParams)
.done(function(data) {
var redirected = data.args.redirected;
if ( redirected === 'false' ) {
var $newPanel = $('<div />')
.attr('id', 'new-panel')
.addClass('panel')
.text("My new panel");
$('#parent-panel').append($newPanel);
dfd.resolve('new panel loaded');
}
else {
dfd = loadPanel(redirected);
console.debug("got redirected, let's keep trying", dfd.state());
}
})
.fail(function(data) {
console.error('request failed:', data);
dfd.reject('unable to load new panel');
});
return dfd;
}
var panelLoaded = loadPanel('http://httpbin.org/get').promise();
$.when( panelLoaded )
.done(function(status) {
console.debug('done status', status);
$('#original-panel').html('New panel loaded: see below');
})
.fail(function(status) {
console.debug('fail status', status);
$('#original-panel').html(status);
});