Answer the question
In order to leave comments, you need to log in
How to check if a variable is empty in ajax form?
Hello. I use the following form to send messages via ajax. The form is taken from the public domain. Please tell me how can I check the msg variable for emptiness?
$('.email-form').submit(function (e) {
e.preventDefault();
var msg = $(this).serialize();
$.ajax({
type: 'POST',
url: 'send.php',
data: msg,
success: function(data) {
$('.results').html(data);
window.setTimeout(function () {
$('.results').hide();
$('.modal').modal('hide');
}, 5000);
},
error: function(xhr, str){
alert('Возникла ошибка: ' + xhr.responseCode);
}
});
});
Answer the question
In order to leave comments, you need to log in
<...>
var msg = $(this).serialize();
if(!msg.name || !msg.email) return;
$.ajax({
<...>
var msg = $(this).serializeArray();
in general you can do this:
<input id="name" name="name" />
<input id="email" name="email" />
$('.email-form').submit(function (e) {
if ($("#name").val().length !== 0 && $("#email").val().length !== 0) {
e.preventDefault();
var msg = $(this).serialize();
$.ajax({
type: 'POST',
url: 'send.php',
data: msg,
success: function(data) {
$('.results').html(data);
window.setTimeout(function () {
$('.results').hide();
$('.modal').modal('hide');
}, 5000);
},
error: function(xhr, str){
alert('Возникла ошибка: ' + xhr.responseCode);
}
});
}
});
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question