Ajax callback concept for SAYG
by moob
HTML
<p>
The following are actions that are performed via an ajax request to a service (that may or may not require you to be logged in)
</p>
<a href="/echo/json/" data-ajax-action="favourite">Favourite</a><br/>
<a href="/echo/json/" data-ajax-action="hmm">No login required</a><br/>
<a href="/echo/json/" data-ajax-action="vote">Vote</a>
<div id="login-modal">
<form>
<input type="text" name="usn" />
<input type="password" name="pwd" />
<button>
login
</button>
</form>
</div>
CSS
#login-modal {
display: none;
background: rgba(0, 0, 0, 0.8);
position: absolute;
top: 0;
right: 0;
bottom: 0;
left: 0;
padding: 40px;
font-size:2em;
}
JavaScript
function doAjaxAction(event) {
event.preventDefault();
var $this = $(this); //The clicked item
//default options and callbacks
var options = {
$el: $this,
url: $(this).attr("href"),
data: "hmm",
success: function(response, status) {
alert("DEFAULT SUCCESS!");
console.log(response);
},
error: function(response, status) {
alert("DEFAULT ERROR! Unable to make ajax request. Aborted.");
console.log(response);
},
fail: function() {
alert("I have randomly decided that you are not logged in.");
launchLoginModal({
success: function() {
doAjax(options);
},
error: function() {
alert("LOGIN ERROR. Aborted!");
},
fail: function() {
alert("Randomly FAILED LOGIN. Retry.");
}
})
}
};
//non-default options and callbacks depending on the data-ajax-action
var action = $this.attr("data-ajax-action");
var actions = {
favourite : function(){
options.success = function(response, status) {
alert("Added to favourites.");
console.log(response);
}
},
vote : function(){
options.success = function(response, status) {
alert("Vote cast.");
console.log(response);
}
},
hmm : function(){
options.fail = function(response, status) {
alert("This randomly failed.");
console.log(response);
}
}
}
if(actions[action]){
actions[action]();
}
//init the ajax
var tryAjax = doAjax(options);
//The Ajax Function
//Makes an ajax request based on the...