1

I have code that validates the input inside the form and displays an error message in the div class="error" if condition is met. However, upon using AJAX to prevent page reload, the PHP validation no longer displays the message but still functions in the background. Does anyone why this is happening? How can I make the PHP validation work again? Thank you for help.

As you can see the validation error is supposed to show in $email_error

<form class="form_pro" action="index.php" method="post" role="form">

<input type="text" class="form" name="E-mail" placeholder="E-mail" value="<?= $email ?>">

<div class="error"><?= $email_error ?></div>

<button name="submit" type="submit" class="action_button"></button>

</form>

PHP

The error message here displays inside the "div" prior to adding AJAX code

if ($_SERVER["REQUEST_METHOD"] == "POST") {

 if (empty($_POST["E-mail"])) {
    $email_error = "E-mail is required";
  } else {
    $email = test_input($_POST["E-mail"]);

    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
      $email_error = "Invalid email format"; 
    }
  }
}

jQuery

After adding this to prevent page reload on submit, the PHP error message no longer shows

$( document ).ready(function() {
    $(".form_pro").submit(function(e) {
        e.preventDefault();

        $.ajax({
            type: "POST",
            url: "php/interuni_process.php",
            data: $(this).serialize(), 
            success: function(data) {

            },
            error: function() {

            }
        });

    });
});
2
  • you need to echo the error message in server side and get the response from server and append it to that div Commented Apr 4, 2017 at 8:26
  • Ahh, that just might be it. Commented Apr 4, 2017 at 8:27

5 Answers 5

1

1) you need to echo the error message in server side and get the response from server and append it to that div

HTML : htm_page.php

<form class="form_pro" action="index.php" method="post" role="form">

    <input type="text" class="form" name="E-mail" placeholder="E-mail" value="<?= $email ?>">

    <div class="error"></div>

    <button name="submit" type="submit" class="action_button"></button>

    </form>

PHP :destination.php

   if ($_SERVER["REQUEST_METHOD"] == "POST") {

        $email_error='';

     if (empty($_POST["E-mail"])) {
        $email_error = "E-mail is required";
      } else {
        $email = test_input($_POST["E-mail"]);

        if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
          $email_error = "Invalid email format"; 
        }
      }

          echo $email_error;
    }

AJAX : html_page.php

    $( document ).ready(function() {
        $(".form_pro").submit(function(e) {
            e.preventDefault();

            $.ajax({
                type: "POST",
                url: "destination.php",
                data: $(this).serialize(), 
                success: function(data) {

                 if(data.trim() !='')
                 {
                    $('.error').html('<h1>'+data+'</h1>');
                 }

                },
                error: function() {

                }
            });

        });
    });
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks! Well answered.
Just another question, how would you identify the data if there are multiple validation fields? Thanks.
you just use if condition to identify in ajax success @LordGoderick
1

Simple PHP error :

<div class="error"><?= $email_error ?></div>

When you simply submit the form and according to your condition the validation fails then $email_error is set and when the page is loaded , server interprets the error and print it.

When you submit through AJAX

It checks the error validate and if fail $email_error is set but as the page s not reloaded is not interpreted . SO when you need to submit through ajax instead of setting the error echo it and it will work fine

Comments

1

You need to modify your PHP to return a response with either success response or the error details and then inside your Javascript "success" function you need to parse the response and if it's an error response you need to update your DOM accordingly.

Comments

1

Simply Ajax doesn't work with PHP validation, because the Ajax error part means that the ajax side failed not the PHP validation !!! so it won't go to the error part if the PHP validation failed, how ever you can still make the submit return false and do something like this in JS&Ajax in the success part:

    success: function(data) {
        if(data.error)
        {
            alert(data.error);
            return false;
        }

Comments

0

As you have prevented the page load, you can not see the error which were rendreing on server and display in frontend.

To achieve this you need edit your jquery code

$( document ).ready(function() {
    $(".form_pro").submit(function(e) {
        e.preventDefault();

        $.ajax({
            type: "POST",
            url: "php/interuni_process.php",
            data: $(this).serialize(), 
            success: function(data) {

            },
            error: function(data, errorThrown)
            {
               $('.error').html(errorThrown);
            }
        });

    });
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.