Skip to content

Instantly share code, notes, and snippets.

@bennadel
Created February 13, 2012 16:01
Show Gist options
  • Save bennadel/1817857 to your computer and use it in GitHub Desktop.
Save bennadel/1817857 to your computer and use it in GitHub Desktop.
Using jQuery.whenSync() For Asynchronous Form Validation And Processing
<!DOCTYPE html>
<html>
<head>
<title>Using jQuery $.whenSync() For Asynchronous Form Processing</title>
<!-- Include jQuery and the whenSync() plugin. -->
<script type="text/javascript" src="../jquery-1.7.1.js"></script>
<script type="text/javascript" src="./jquery.whensync.js"></script>
<script type="text/javascript">
// Create a fake data post (to validate and process).
var form = {
id: 4,
name: "Tricia",
age: 42
};
// -------------------------------------------------- //
// -------------------------------------------------- //
// -------------------------------------------------- //
// -------------------------------------------------- //
// Create a demo API response to explore the use of
// whenSync() to handle validation in an asynchronous
// fashion.
var apiResponse = {
statusCode: 200,
statusText: "OK",
data: "",
error: ""
};
// Var values that will be produced *during* the asynchronous
// validation process. This way, as they get set during the
// validation, they can later be used during the always()
// set of callbacks.
var user = null;
// Perform our asynchronous API processing workflow.
var process = $.whenSync(
// Validate the user ID.
function( deferred ){
// Check to see if the ID can be found in our
// database -- Clearly, this is just for DEMO!!!
if (form.id !== 4){
// Not found!
return(
deferred.reject(
"NotFound",
"The record could not be found."
)
);
}
// If we made it this far, the user was found -
// store a reference for later use.
user = {
id: 4,
name: "Sarah",
age: 37
};
// Resolve the validation step.
deferred.resolve();
},
// Validate then user name.
function( deferred ){
// Check to see if there was a length provided.
if (form.name.length === 0){
// Name is required.
return(
deferred.reject(
"BadRequest",
"The name value is required."
)
);
}
// If we made it this far, name is valid.
deferred.resolve();
},
// Validate the user age.
function( deferred ){
// Check for a valid number.
if (
isNaN( form.age ) ||
(form.age < 0)
){
// Age is invalid.
return(
deferred.reject(
"BadRequest",
"The age value must be a positive number."
)
);
}
// If we made it this far, age is valid.
deferred.resolve();
},
// Once the validation is done, if everything went
// according to plan, then we should be able to process
// the request further.
//
// NOTE: We are performing this as part of the whenSync()
// callback list *rather* than the DONE() callback since
// there is a possibility that this part of the process
// will ALSO create exceptions.
function( deferred ){
// Update the user record with the valid data.
user.name = form.name;
user.age = form.age;
// Resolve the entire validate process.
deferred.resolve();
}
);
// If the entire validation and subsequent processing (last
// step in the above workflow) has gone correctly, then our
// API response should be successful.
process.done(
function(){
// Adjust the API response.
apiResponse.data = {
id: user.id,
name: user.name,
age: user.age
};
}
);
// Once the processing is done, we can try to "Catch" any
// errors that were rejected during the validation phase.
process.fail(
function( type, message ){
// Check to see which type of error we are "Catching."
switch( type ){
case "NotFound":
// Adjust the API response.
apiResponse.statusCode = 404;
apiResponse.statusText = "Not Found";
apiResponse.error = message;
break;
case "BadRequest":
// Adjust the API response.
apiResponse.statusCode = 400;
apiResponse.statusText = "Bad Request";
apiResponse.error = message;
break;
// If none of the other case statements caught
// the erorr, then something unexpected must
// have happened.
default:
// Adjust the API response.
apiResponse.statusCode = 500;
apiResponse.statusText = "Server Error";
apiResponse.error = "Ooops! Not good!";
break;
}
}
);
// At this point, whether the validation and form processing
// was SUCCESSFUL or a FAILURE, we should have an updated API
// response object. Now, all we need to do is stream it back
// to the client.
process.always(
function(){
// When creawting the HTTP response body, we need to
// check to see if we are returning an error or a
// success.
if (apiResponse.error){
// Fail.
var responseData = {
code: apiResponse.statusCode,
error: apiResponse.error
};
} else {
// Success.
var responseData = apiResponse.data;
}
// Serialize the response for streaming to client.
var responseBody = JSON.stringify( responseData );
// Build the HTTP response content.
console.log( "StatusCode:", apiResponse.statusCode );
console.log( "StatusText:", apiResponse.statusText );
console.log( "Content-Type:", "application/json" );
console.log( "Content-Length:", responseBody.length );
console.log( "Body:", responseBody );
}
);
</script>
</head>
<body>
<!-- Left intentionally blank. -->
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment