A bit late, but here is my contribution. In my experience, this $.ajaxis the preferred way to send an AJAX call, including forms, to the server. It has many features. To perform the verification indicated by @vincent, I add a regular submit button to the form and then bind to $(document).on("submit", "#myForm", .... In this case, I prevent the default send action ( e.preventDefault()if your event e), do my check and submit.
A simplified version of this will be as follows:
$(document).on("submit", "#login-form", function(e) {
e.preventDefault();
$("#login-submit-wrapper").addClass("hide");
$("#login-progress-wrapper").removeClass("hide");
if (!new RegExp(/^([A-Za-z0-9._-]){2,64}$/).test($("#login-username").val())) {
markInputInvalid($("#login-username"), "Invalid Username");
$("#login-submit-wrapper").removeClass("hide");
$("#login-progress-wrapper").addClass("hide");
return false;
}
var data = new FormData();
data.append("username", $("#login-username").val());
data.append("password", $("#login-password").val());
data.append("captcha", grecaptcha.getResponse());
$.ajax("handler.php", {
data: data,
processData: false,
contentType: false,
method: "POST"
}).done(function(response) {
}).fail(function(response) {
var data = JSON.parse(response.responseText);
switch (data.error_code) {
case 1:
markInputInvalid($("#login-username"), data.message);
return;
break;
case 2:
markInputInvalid($("#login-password"), data.message);
return;
break;
default:
alert(data.message);
return;
break;
}
}).always(function() {
$("#login-submit-wrapper").removeClass("hide");
$("#login-progress-wrapper").addClass("hide");
});
});
source
share