0

My AJAX return isn't styling errors with css.

What I am finding is that all my returns from the PHP are displaying with the success property function. All my returns are displaying with the successCSS (Bootstrap).

I am not sure if there is a better way to receive data from my PHP and then style the output accordingly.

<a class="btn btn-primary" onclick="validateForm()">Send</a>
<div class="alert hide" role="alert hide">
  <div class="status" id="status"></div>
</div>
function validateForm() {

  $.ajax({
      url: "register.php",
      type: "POST",
      data: $('#registration-form').serialize(),
      success: function(data, textStatus, jqXHR) {
        $('#status').text(data.message).addClass('successCSS');
        if (data.code) //If mail was sent successfully, reset the form.
          $('#registration-form').closest('form').find("input[type=text], 
            textarea ").val("
            ");
          },
          error: function(jqXHR, textStatus, errorThrown) {
            $('#status').text(jqXHR).addClass('errorCSS');
          }
      });
  }
<?php
$firstname = $_POST['firstname'];
$surname = $_POST['surname'];
$email = $_POST['email'];

header('Content-Type: application/json');
if ($firstname === '')
{
    print json_encode(array(
        'message' => 'firstname cannot be empty',
        'code' => 0
    ));
    exit();
}
if ($surname === '')
{
    print json_encode(array(
        'message' => 'Surname cannot be empty',
        'code' => 0
    ));
    exit();
}
if ($email === '')
{
    print json_encode(array(
        'message' => 'Email cannot be empty',
        'code' => 0
    ));
    exit();
}
else
{
    if (!filter_var($email, FILTER_VALIDATE_EMAIL))
    {
        print json_encode(array(
            'message' => 'Email format invalid.',
            'code' => 0
        ));
        exit();
    }
}
$content = "Email: $email \nMessage: $message";
$recipient = "@gmail.com";
$mailheader = "From: $email \r\n";
mail($recipient, $subject, $content, $mailheader) or die("Error!");
print json_encode(array(
    'message' => 'Registration successful !',
    'code' => 1
));
exit();
1
  • 2
    check for code===0 before showing success message Commented Jun 2, 2018 at 15:26

1 Answer 1

3

You need to check for code === 0 and code === 1 and reset the class names before making ajax call, so you don't end up adding too many classes. Try this

function validateForm() {


$('#status').text('').removeClass('successCSS').removeClass('errorCSS');
$.ajax({
          url: "register.php",
          type: "POST",
          data: $('#registration-form').serialize(),
          success: function(data, textStatus, jqXHR) {
            if(data.code && data.code === 1) {
                $('#status').text(data.message).addClass('successCSS');
            } else {
                $('#status').text(data.message).addClass('errorCSS');
            }

            if (data.code) //If mail was sent successfully, reset the form.
              $('#registration-form').closest('form').find("input[type=text], 
                textarea ").val("
                ");
              },
              error: function(jqXHR, textStatus, errorThrown) {
                $('#status').text('error when submitting form ' + textStatus + ' : ' + errorThrown).addClass('errorCSS');
              }
          });
      }
Sign up to request clarification or add additional context in comments.

2 Comments

Hi NaturmaN This has essentially solved my issue as the Styling for the error messages are using the errorCSS and the successCSS is showing for the complete registration. One issue this change has now caused is that the error messages are now returning [Object, Object]. I am not sure if you can help with which what might be causing this and why ? Thank you Tommy
@Hutch Try now, it was printing [Object, Object] because we were trying to print the jqXHR object in error msg, now it should be fine

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.