asdfkjasdfjk
asdfkjasdfjk

Reputation: 3894

PHP show error message on ajax submission

I am php beginner. I am submitting a form using ajax call. So after submission of the form user stay on the same page and do not go to reserve_seat.php since ajax call.

<form action="reserve_seat.php" method="POST">
First name:<br>
<input type="text" name="name" value="Mickey">
<br>
Email:<br>
<input type="text" name="email" value="Mouse">
<br><br>
<input type="submit" value="Submit">
</form> 

<script>
      $(function () {
        $('form').on('submit', function (e) {
          e.preventDefault();
          $.ajax({
            type: 'post',
            url: 'reserve_seat.php',
            data: $('form').serialize(),
            success: function () {
              alert('form was submitted');
            }
          });
        });
      });
    </script>

Now after submission of the form I do some validation for email and if the email validation fail I want to show an error message above the form. May be insert a div showing that email not valid. How can I do that? My validation code below

    if( !empty($_POST['name']) && !empty($_POST['email'])){
        $name = $_POST['name'];
        $email = $_POST['email'];

        if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $insert = 'INSERT into reservation(name,email) VALUES ("'.$name.'", "'.$email.'")';
        mysql_query($insert);
         } else {
        //need help here to show error message 
}
    }

Upvotes: 0

Views: 1749

Answers (2)

paulgv
paulgv

Reputation: 1828

$.ajax will get a response in its success method :

<script>
  $(function () {
    $('form').on('submit', function (e) {
      e.preventDefault();
      $.ajax({
        type: 'post',
        url: 'reserve_seat.php',
        data: $('form').serialize(),
        success: function (data) {
          alert(data); // Alerts server response
        }
      });
    });
  });
</script>

You just need to actually send a response server side, you could simply echo a message with PHP :

if( !empty($_POST['name']) && !empty($_POST['email'])){
  $name = $_POST['name'];
  $email = $_POST['email'];

  if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
    $insert = 'INSERT into reservation(name,email) VALUES ("'.$name.'", "'.$email.'")';
    mysql_query($insert);
  } else {
    echo "This message will be available in success method";
  }
}

Upvotes: 1

RNK
RNK

Reputation: 5792

HTML

<span id='error_message'></span>

In your ajax success:

success: function (res) {
    $('#error_message').text('');
    $('#error_message').text(res);
}

PHP (reserve_seat.php)

echo the error message, based on your requirement/condition. In your case,

if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
    $insert = 'INSERT into reservation(name,email) VALUES ("'.$name.'", "'.$email.'")';
    mysql_query($insert);
} else {
    echo "Invalid Email";
}

Upvotes: 0

Related Questions