Skip to content

Instantly share code, notes, and snippets.

@adammcarth
Last active December 25, 2015 16:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save adammcarth/7003472 to your computer and use it in GitHub Desktop.
Save adammcarth/7003472 to your computer and use it in GitHub Desktop.
Ajax post request in jQuery
var commentForm = $("form#newComment");
commentForm.submit(function() {
event.preventDefault();
$("#commentName").attr("disabled", true);
$("#commentGravatar").attr("disabled", true);
$("#commentWebsite").attr("disabled", true);
$("#commentBody").attr("disabled", true);
$("#createComment").attr("disabled", true);
$(this).fadeTo(230, 0.5);
$("#newCommentAvatar").fadeTo(230, 0.5);
$.ajax({
type: commentForm.attr("method"),
url: commentForm.attr("action"),
data: commentForm.serialize(),
success: determineStatus,
error: broken,
complete: function() {
$("#commentName").attr("disabled", false);
$("#commentGravatar").attr("disabled", false);
$("#commentWebsite").attr("disabled", false);
$("#commentBody").attr("disabled", false);
$("#createComment").attr("disabled", false);
$(this).fadeTo(1, 1);
$("#newCommentAvatar").fadeTo(1, 1);
}
});
});
function determineStatus(data) {
// Work with the json response here
}
function broken(xhr, status, error) {
// Throw an error, becuase something went drastically wrong.
}
{
"status": 1,
"message": "Thanks Adam! Your comment has been added.",
"comment": {
"id": 1,
"post_id": 1,
"name": "Adam McArthur",
"avatar": "/uploads/default.jpg",
"website": "http://example.com",
"created_at": "7 Aug, 2013 at 10:57pm"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment