HTML5 and CSS3, Second Edition

(singke) #1
url:"/login",
type:"POST",
data:form.serialize(),
dataType:"json"
});
request.done=function(){
// Do whatyou do whenthe loginworks.
};
return(request);
};

This function has two parameters; a jQuery object containing the form that
should be submitted, and the event. We prevent the event’s default behavior,
and then we build the Ajax request, passing the serialized form as the data.

We’re using jQuery’s support for promises to define what happens when we
have a successful response from the server. Promises let us write asyn-
chronous code without resorting to nested callbacks.

jQuery’s $.ajax() method returns an object that implements the Promise inter-
face. Instead of defining the success() callback inside of the $.ajax() method, we
can define done() and fail() callbacks on the object returned from $.ajax(). Those
callbacks will get executed once the Ajax request is completed, or immediately
if the request has already completed. This lets us define callbacks on
promises programmatically, even in other parts of our program. It also lets
us separate our code into smaller chunks instead of one big ball of unman-
ageable callbacks. You should read Trevor Burnham’s book Async JavaScript:
Build More Responsive Apps with Less Code [Bur12] to learn about promises
in greater detail.

We’ve already defined the done() callback inside of this processLogin() function.
To make the form shake when the login fails, we need to create two event
listeners. The first listener handles the form submit event and calls the process-
Login() function we just wrote. That function returns the request, and since
request implements the Promise interface, we can now define the fail() callback,
where we apply the shake class to the form.

css3_animation/javascripts/form.js
varaddFormSubmitWithCSSAnimation=function(){
$(".login").submit(function(event){
varform= $(this);
request= processLogin(form,event);
request.fail(function(){
form.addClass("shake");
});
});
};

report erratum • discuss

Making Things Move with Transitions and Animations • 175


Download from Wow! eBook <www.wowebook.com>

Free download pdf