Ajax callback else login and try again
A test for voting system. Make an ajax request if successful do success callback else do fail callback and then automatically try again.
by moob
HTML
<a href="/echo/json/" data-ajax-action="voteyes">click me</a>
JavaScript
function doAjaxAction(event) {
event.preventDefault();
var $this = $(this);
var options = {
$el: $this,
url: $(this).attr("href"),
data: "hmm",
success: function(response, status) {
alert("SUCCESS! I'm the onSuccess callback.");
console.log(response);
},
error: function(response, status) {
alert("ERROR! Unable to make ajax request. Aborted.");
console.log(response);
},
fail: function() {
alert("FAIL! Successfully made the ajax request but the response indicated youre not logged in (or rather my randomSuccess returned false.) Gonna launch the login modal...");
launchLoginModal({
success: function(){doAjax(options);},
fail: function(){alert("FAILED LOGIN. I'M DONE TRYING!");}
})
}
};
var tryAjax = doAjax(options);
function doAjax(settings) {
console.log("doajax");
//make an ajax request to options.requestUrl
$.ajax({
type: "json",
url: settings.url,
data: settings.data,
error: settings.error,
success: function(response, status) {
var randomSuccess = (Math.random() >= 0.5);
if (randomSuccess) {
settings.success.call(response, status);
} else {
settings.fail.call();
}
}
});
};
function launchLoginModal(opts) {
if (window.confirm("I'm the login modal. Pretend to log in and try again?")) {
opts.success.call();
} else {
opts.fail.call();
}
};
};
$(document).on("click", "a[data-ajax-action]", doAjaxAction);