Link to home
Start Free TrialLog in
Avatar of Richard Lloyd
Richard Lloyd

asked on

Prevent form from submitting if ajax error message

I need some help on preventing a form from submitting if an ajax response from some form validation is not correct.

I have a form that uses jqueryvalidation.org to check syntax/formatting/required fields and another script that checks the validity of the email address. If the email does not meet the criteria, then a message is displayed in the "dispemail" div:

<script
    src="https://code.jquery.com/jquery-3.4.1.js"
    integrity="sha256-WpOohJOqMqqyKL9FccASB9O0KwACQJpFTUBLTYOVvVU="
    crossorigin="anonymous">
</script>

<script src="https://cdn.jsdelivr.net/jquery.validation/1.15.0/jquery.validate.min.js"></script>

<p>valid@email.com and true@email.com are the only 2 emails that will pass the checks, everything else will fail</p>

<form action='#' method='post' id='form'>
    <input type='name' name='name' id='name' placeholder='name'/><br/>
    <input type='email' name='email' id='email'  placeholder='email'/><br/>
    <div id='dispemail'></div>
    <input type='submit' id='submit' value='Submit' />
</form>

<script>

    $().ready(function() {


        $("#form").validate({
            rules: {
                email: {email: true, required: true},
                name: {required: true},
            },
        });

    });
</script>

<script type="text/javascript">
$(document).ready(function() {
    $("#email").blur(function() {
        var email = $('#email').val();
        if (email === "") {
            $("#dispemail").html("");
        } else {
            $.ajax({
                type: "POST",
                url: "check-email.php",
                data: "email=" + email,
                success: function(html) {
                    $("#dispemail").html(html);
                }
            });
            return false;
        }
    });
});
</script>

Open in new window


The "check-email.php" code is

<?php

if(isset($_POST['email'])){
$email=(($_POST['email']));

//check email script and return a response, "valid" or "notvalid"...
if($email=='valid@email.com' || $email=='true@email.com'){    // email is valid
    $response='valid'; }
else{    // email is not valid
    $response='notvalid'; }




if($response=='valid'){
$message = $email." is a valid email";
echo "<p>$message</p>";
}
else{
$message = $email." is not a valid email";
echo "<p style='color:red'>$message</p>";
}
}

Open in new window


Is there a way to disable the submit button on the failure of the "check-email.php" to return a valid email?

I need it to work in conjunction with the queryvalidation script, so that if either fails, then the form won't submit until the error has been resolved.

Thank you
Avatar of lenamtl
lenamtl
Flag of Canada image

Hi,

i'm using only server side validation

if (response is not valid) 
			return 
				'<div class="alert alert-danger">'. error message .' </div>';

Open in new window


So this will stop the code prevent to go any further.
If the response is valid then this continue to run the PHP code.
It just to give you an idea my code is using AJAX / OOP.

You can use switch or anything that is best suit to your code
https://www.php.net/manual/en/control-structures.switch.php

Don't rely on Javascript, as it can be bypasses by the user so you can set the button to disabled but it is easy to set it back to enable so you need to make sure the PHP code will prevent the code running if it is not passing the PHP validation.

You can use a script like this to check your form and disable the submit button by default and as soon as user edit the form it enable the button and alert if user quit the page, this is a nice to have but you cannot rely on that.
 https://github.com/simontaite/jquery.dirty
https://github.com/simontaite/jquery.dirty
The usual pattern is to submit via AJAX - validate on the server and send back a status (+ error info if errors).

Doing an AJAX validation and then a normal form submit does not really make a whole lot of sense - it is really just doing things the long and most difficult way.

Make your form an AJAX form.
Disable default submit.
When submitted -  the form details are sent by AJAX to the server.
They are validated
If valid the data is processed and a success status is returned. Display message / redirect page etc
If not send back an array / object of error information and use the AJAX callback to display them.

That is the best way of doing it.
Avatar of Richard Lloyd
Richard Lloyd

ASKER

Thanks, but although I appreciate that my methodology might not be the best, is there a way that I can still achieve what I am trying to do within my existing method?
This question needs an answer!
Become an EE member today
7 DAY FREE TRIAL
Members can start a 7-Day Free trial then enjoy unlimited access to the platform.
View membership options
or
Learn why we charge membership fees
We get it - no one likes a content blocker. Take one extra minute and find out why we block content.