Я пытаюсь создать простую проверку формы с помощью AJAX и PHP, но использование typeof
работает не так, как ожидалось.
Он работает хорошо, если я не получаю пустой ответ, что означает, что все поля прошли проверку.
В этом случае ничего не происходит, и последний ввод остается со своими классами ошибок, а Cart div
не меняется на Success div
, как и предполагалось, после успешного запроса.
Типичный ответ в JSON:
{
last_name: "The Last name is required",
email: "The Email is required",
city: "The City is required",
np_branch: "The Np branch is required"
}
Очевидно, что если одно из значений прошло проверку PHP, оно не добавляется в массив. Обратите внимание, что значения ошибок могут изменяться для каждого ключа в зависимости от ошибки, поэтому проверка сообщения об ошибке не является вариантом.
Код:
$.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 passed validation we hide the Cart div and show the 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" });
}
// Checking whether the response contains a 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" });
}
// Checking whether the response contains a email error
if (typeof(data['email']) != "undefined" && data['email'] !== null) {
email.addClass("error");
$('#email-err').css({ "display":"block" });
} else if (email.hasClass('error')) {
email.removeClass("error");
$('#email-err').css({ "display":"none" });
}
// Checking whether the response contains a city error
if (typeof(data['city']) != "undefined" && data['city'] !== null) {
city.addClass("error");
$('#city-err').css({ "display":"block" });
} else if (city.hasClass('error')) {
city.removeClass("error");
$('#city-err').css({ "display":"none" });
}
// Checking whether the response contains a np_branch error
if (typeof(data['np_branch']) != "undefined" && data['np_branch'] !== null) {
np_branch.addClass("error");
$('#branch-err').css({ "display":"block" });
} else if (np_branch.hasClass('error')) {
np_branch.removeClass("error");
$('#branch-err').css({ "display":"none" });
}
}
});
Есть ли лучший способ сделать что?