0

I have a HTML form that when posted fires an JQuery script to check a validation function before sending data to an ajax call to insert the data into a mySQL database.

It works as it should, except when it is running an ajax check to see if the posted email address already exists in the database.

I need the email_error var to return true if the response from the ajax call is not 'success'. My code:

function validate_add_relative() {
    var check_error = false;
    var email_error = false;
    var title = document.forms["add_relative_form"]["title"].value;
        if (title == null || title == "") {
             check_error =  true;
        }
    var first_name = document.forms["add_relative_form"]["first_name"].value;
        if (first_name == null || first_name == "") {
             check_error =  true;
        }
    var surname = document.forms["add_relative_form"]["surname"].value;
        if (surname == null || surname == "") {
             check_error =  true;
        }
    var phone = document.forms["add_relative_form"]["phone"].value;
        if (phone == null || phone == "") {
             check_error =  true;
        }
    var email = document.forms["add_relative_form"]["email"].value;
        if (email == null || email == "") {
             check_error =  true;
        }
    var address = document.forms["add_relative_form"]["address"].value;
        if (address == null || address == "") {
             check_error =  true;
        }
    var postData = $(this).serializeArray();
    $.ajax(
    {
        url : '<?php echo WEB_URL . 'controllers/ajax/check_relative_email.php'; ?>',
        type: "POST",
        data : postData,
        success:function(data, textStatus, jqXHR) {
          if(data == 'success') {
            email_error = false;
            return true;
          }
          else {
            alert('test');
            email_error = true;
            $('.relative_email_error').removeClass('hidden');
            $('.relative_email_error').html('Email is already in use. Please choose another.');

          }
        },
        error: function(jqXHR, textStatus, errorThrown)
        {
          $('.relative_email_error').removeClass('hidden');
          $('.relative_email_error').html('Error. Please try again later.');
          email_error = true;
        }
    });

    if (email_error == true) {
            alert("Please choose another email address, that one is already in use.");
            return false;
        }   
        if (check_error == true) {
            alert("Please ensure you fill in all mandatory fields.");
            return false;
        }
        if (email_error == false && check_error == false) {
            return true;
    }
}

$('.add_relative_form').submit(function(e) {
    e.preventDefault();
    if(validate_add_relative()) {
        var ajaxurl = '<?php echo WEB_URL; ?>controllers/ajax/add_relative.php',
        form_data = $('.add_relative_form').serialize();
        $.post(ajaxurl, form_data, function (response) {
            //location.reload();
        });
    }
});

When running the above code, the first part (Form validation) works as it should, and it also gives the alert and does the class hiding after. But it carries on and is not catching the fact that email_error is set to true after the alert line. So it continues through the code and adds the entry through the last ajax post controllers/ajax/add_relative.php

Pete Naylor
  • 776
  • 2
  • 14
  • 33
  • in your `$('.add_relative_form').submit`, what do you get if you alert/console.log `validate_add_relative()`? – ad_on_is May 18 '17 at 10:24
  • Possible duplicate of [How do I return the response from an asynchronous call?](http://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – CBroe May 18 '17 at 10:27
  • why don't you use `.blur` and check if email exists then if does you disable the submit button? – Junius L May 18 '17 at 11:16

3 Answers3

0

add complete function after error and write your code inside that function

complete:function(data, textStatus, jqXHR) {
      if(data == 'success') {
        email_error = false;
        return true;
      }
      else {
        alert('test');
        email_error = true;
        $('.relative_email_error').removeClass('hidden');
        $('.relative_email_error').html('Email is already in use. Please choose another.');

      }
    },
Bhavik
  • 495
  • 2
  • 10
0

JavaScript is asynchronous in the sense that it can make, for example, Ajax calls. Hence your outer conditions will get mislead. Try to add return statement inside AJAX response for expected result.

Please try following solution

function validate_add_relative() {
    var check_error = false;
    var email_error = false;
    var title = document.forms["add_relative_form"]["title"].value;
        if (title == null || title == "") {
            check_error =  true;
        }
    var first_name = document.forms["add_relative_form"]["first_name"].value;
        if (first_name == null || first_name == "") {
            check_error =  true;
        }
    var surname = document.forms["add_relative_form"]["surname"].value;
        if (surname == null || surname == "") {
            check_error =  true;
        }
    var phone = document.forms["add_relative_form"]["phone"].value;
        if (phone == null || phone == "") {
            check_error =  true;
        }
    var email = document.forms["add_relative_form"]["email"].value;
        if (email == null || email == "") {
            check_error =  true;
        }
    var address = document.forms["add_relative_form"]["address"].value;
        if (address == null || address == "") {
            check_error =  true;
        }
    if(check_error===false){
        var postData = $(this).serializeArray();
        $.ajax(
        {
            url : '<?php echo WEB_URL . 'controllers/ajax/check_relative_email.php'; ?>',
            type: "POST",
            data : postData,
            success:function(data, textStatus, jqXHR) {
            if(data == 'success') {
                return true;
            }
            else {
                alert('test');
                return false;
                $('.relative_email_error').removeClass('hidden');
                $('.relative_email_error').html('Email is already in use. Please choose another.');

            }
            },
            error: function(jqXHR, textStatus, errorThrown)
            {
                $('.relative_email_error').removeClass('hidden');
                $('.relative_email_error').html('Error. Please try again later.');
                return false;
            }
        });
    }
    else{
        return false;
    }
}

$('.add_relative_form').submit(function(e) {
    e.preventDefault();
    if(validate_add_relative()) {
        var ajaxurl = '<?php echo WEB_URL; ?>controllers/ajax/add_relative.php',
        form_data = $('.add_relative_form').serialize();
        $.post(ajaxurl, form_data, function (response) {
            //location.reload();
        });
    }
});

UPDATES

change following code :

   if(data == 'success') {
            return true;
        }
        else {
            alert('test');
            return false;
            $('.relative_email_error').removeClass('hidden');
            $('.relative_email_error').html('Email is already in use. Please choose another.');

        }

To

   if(data == 'success') {
        return true;
    }
    else {
        alert('test');

        $('.relative_email_error').removeClass('hidden');
        $('.relative_email_error').html('Email is already in use. Please choose another.');
           return false;
    }
AkshayP
  • 2,141
  • 2
  • 18
  • 27
  • Thank, I get an error in my console that says 'unreachable code after return statement' on: $('.relative_email_error').removeClass('hidden'); – Pete Naylor May 18 '17 at 10:38
  • Ok, you can remove error: function(jqXHR, textStatus, errorThrown) { $('.relative_email_error').removeClass('hidden'); $('.relative_email_error').html('Error. Please try again later.'); return false; } because I think this will not get call, as we are handling our conditions on success. Try that once. – AkshayP May 18 '17 at 10:44
  • And you can add that error: function(jqXHR, textStatus, errorThrown) { function, I took wrong line before, updated code should work. – AkshayP May 18 '17 at 11:03
  • Thank you, it does work, bit it doesn't run the var ajaxurl = 'controllers/ajax/add_relative.php' so it doesn't add to the database – Pete Naylor May 18 '17 at 11:18
  • ok, please try following : url : ''+'controllers/ajax/check_relative_email.php', – AkshayP May 18 '17 at 11:20
  • No it doesn't get the return true response – Pete Naylor May 18 '17 at 11:39
  • Check what you are getting in the AJAX response, in Network – AkshayP May 18 '17 at 12:21
0

You can check, if the email already exists by using .blur() as soon after the user enters their email, you send AJAX call to check if the email exists and disable the submit button and show proper message to the user.

Form

<form action="" name="add_relative_form" class="add_relative_form">
<input type="text" name="title">
<input type="text" name="first_name">
<input type="text" name="surname">
<input type="text" name="phone">
<input type="text" id="email" name="email"> <!-- give email an id -->
<input type="text" name="address">
<input type="submit" id="sub" value="Sub"> <!-- give submit an id -->

Javascript

function validate_add_relative() {
    var check_error = false;
    var email_error = false;
    var title = document.forms["add_relative_form"]["title"].value;
    if (title == null || title == "") {
        check_error = true;
    }
    var first_name = document.forms["add_relative_form"]["first_name"].value;
    if (first_name == null || first_name == "") {
        check_error = true;
    }
    var surname = document.forms["add_relative_form"]["surname"].value;
    if (surname == null || surname == "") {
        check_error = true;
    }
    var phone = document.forms["add_relative_form"]["phone"].value;
    if (phone == null || phone == "") {
        check_error = true;
    }
    var email = document.forms["add_relative_form"]["email"].value;
    if (email == null || email == "") {
        check_error = true;
    }
    var address = document.forms["add_relative_form"]["address"].value;
    if (address == null || address == "") {
        check_error = true;
    }

    if (email_error == true) {
        alert("Please choose another email address, that one is already in use.");
        return false;
    }
    if (check_error == true) {
        alert("Please ensure you fill in all mandatory fields.");
        return false;
    }
    if (email_error == false && check_error == false) {
        return true;
    }
}

$('.add_relative_form').submit(function (e) {
    e.preventDefault();
    if (validate_add_relative()) {
        var ajaxurl = '<?php echo WEB_URL; ?>controllers/ajax/add_relative.php',
            form_data = $('.add_relative_form').serialize();
        $.post(ajaxurl, form_data, function (response) {
            //location.reload();
            console.log(response)
        });
    }
});

$('#email').on('blur', function () {
    $.ajax({
        url: '<?php echo WEB_URL . 'controllers/ajax/check_relative_email.php'; ?>',
        type: "POST",
        data: {email: $(this).val()},
        success: function (data, textStatus, jqXHR) {
            if (data == 'success') {
                $('#sub').prop('disabled', false);
            }
            else {
                $('.relative_email_error').show();
                $('.relative_email_error').html('Email is already in use. Please choose another.');
                $('#sub').prop('disabled', true);
            }
        },
        error: function (jqXHR, textStatus, errorThrown) {
            $('.relative_email_error').removeClass('hidden');
            $('.relative_email_error').html('Error. Please try again later.');
        }
    });
})

Then in your PHP get the email from post

<?php

    $email = $_POST['email'];

    // your SQL code here 
Junius L
  • 15,881
  • 6
  • 52
  • 96