Trying to implement form validation using AJAX and PHP, but encountering issues with the typeof
operator.
The validation works smoothly except when receiving an empty response, indicating that all fields have passed. In this scenario, the last input retains error classes, and the Cart div
fails to transition to the Success div
as expected upon successful submission.
A typical JSON response would look like this:
{
last_name: "The Last name is required",
email: "The Email is required",
city: "The City is required",
np_branch: "The Np branch is required"
}
Notably, values that pass through PHP validation are not added to the array. Additionally, error messages can vary for each key, making it impractical to check for specific error messages.
Code snippet:
// AJAX request
$.ajax({
type: "POST",
dataType:"json",
data: {
last_name: l_name.val(),
email: email.val(),
city: city.val(),
np_branch: np_branch.val()
},
success: function(data) {
console.log(data);
// If all fields pass validation, hide Cart div and display Success div
if (typeof(data['last_name']) == "undefined" && typeof(data['email']) == "undefined" && typeof(data['city']) == "undefined" && typeof(data['np_branch']) == "undefined") {
$('.cart').css({ "display":"none" });
$('.success').css({ "display":"block" });
}
// Handle 'last_name' error
if (typeof(data['last_name']) != "undefined" && data['last_name'] !== null) {
l_name.addClass("error");
$('#l_name-err').css({ "display":"block" });
} else if (l_name.hasClass('error')) {
l_name.removeClass("error");
$('#l_name-err').css({ "display":"none" });
}
// Repeat similar error handling for 'email', 'city', and 'np_branch'
}
});
Is there a more efficient approach to achieve this form validation?