S
S
Secret732018-06-07 16:21:00
AJAX
Secret73, 2018-06-07 16:21:00

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

4 answer(s)
V
Victor P., 2018-06-07
@Secret73

<...>
var msg = $(this).serialize();
if(!msg.name || !msg.email) return;
$.ajax({
<...>

upd: the problem is in serialize(), here you need to use
var msg = $(this).serializeArray();

L
leni_m, 2018-06-07
@leni_m

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);
      }
    });
}
  });

W
Web Dentist, 2018-06-07
@kgb_zor

if(msg)

T
tyzberd, 2018-06-07
@tyzberd

dontforget.pro/javascript/primer-ajax-otpravki-for...
https://formden.com/blog/validate-contact-form-jquery
https://codepen.io/SitePoint/pen/akPoad
https:// codepen.io/Gix075/pen/ZYMBzO

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question