首页 > 解决方案 > Setting style based on php return through ajax

问题描述

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();

标签: javascriptphpajaxhtml

解决方案


您需要检查代码 === 0 和代码 === 1 并在进行 ajax 调用之前重置类名,因此您最终不会添加太多类。尝试这个

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');
              }
          });
      }

推荐阅读