如何返回我的表单错误


How do I return my Form errors

我的php运行,但由于某些原因,我的变量没有被通信。我做错了什么?我正试图通过ajax传递消息,但无论我把它放在php的哪里,我似乎都无法弹出任何类型的错误或成功消息。。这让我相信问题出在我的ajax/javascript函数内部。ajax应该将消息直接放在已定义的中。我也意识到以前有人问过这个问题,但我真的看了很多,仍然不知道出了什么问题。谢谢大家,对不起墙。

AJAX

<!-- Email -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
  // magic.js
  $(document).ready(function() {
    // process the form
    $('form').submit(function(event) {
        $('#sub_result').html("");
        // get the form data
        // there are many ways to get this data using jQuery (you can use the class or id also)
        var formData = {
            'email'             : $('input[name=email]').val(),
        };
        // process the form
        $.ajax({
            type        : 'POST', // define the type of HTTP verb we want to use (POST for our form)
            url         : 'phEmail.php', // the url where we want to POST
            data        : formData, // our data object
            dataType    : 'json', // what type of data do we expect back from the server
            encode      : true
        })
            // using the done promise callback
            .done(function(data) {
                // log data to the console so we can see
                console.log(data); 
                // here we will handle errors and validation messages
                if ( ! data.success) {
                    // handle errors for email ---------------
                    if (data.errors.email) {
                        $('#sub_result').addClass('class="error"'); // add the error class to show red input
                        $('#sub_result').append('<div class="error">' + data.errors.email + '</div>'); // add the actual error message under our input
                    }

                } else {
                    // ALL GOOD! just show the success message!
                    $('#sub_result').append('<div class="success" >' + data.message + '</div>');
                    // usually after form submission, you'll want to redirect
                    // window.location = '/thank-you'; // redirect a user to another page
                }
            })
            // using the fail promise callback
            .fail(function(data) {
                // show any errors
                // best to remove for production
                console.log(data);
            });
        // stop the form from submitting the normal way and refreshing the page
        event.preventDefault();
    });
  });
</script>

PHP

<?php
$errors = array();      // array to hold validation errors
$data = array(); // array to pass back data
// validate the variables ======================================================
// if any of these variables don't exist, add an error to our $errors array
if(filter_var($_POST['email'],FILTER_VALIDATE_EMAIL) === false)
{
   $errors['email'] = 'Email is not valid';
}

if (empty($_POST['email'])){
$errors['email'] = 'Email is required.';
}
// if there are items in our errors array, return those errors============================
if ( ! empty($errors)) {
$data['success'] = false;
$data['errors']  = $errors;

} else {
//variables===============================================================================
$servername = "localhost";
$username = "ghostx19";
$password = "nick1218";
$dbname = "ghostx19_samplepacks";
$user = $_POST['email'];
// Create connection======================================================================
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    echo "Connection failed";
} 
//add user================================================================================
$sql = "INSERT INTO users (email)
VALUES ('$user')";
if ($conn->query($sql) === TRUE) {
    $data['success'] = true;
    $data['message'] = 'Subscribed!';
} else {
    $errors['email'] = 'Error';
}
$conn->close();

// message to me==========================================================================
$to      = 'garvernr@mail.uc.edu';
$subject = 'New subscription';
$message = $_POST['email'];
$headers = 'From: newsubscription@samplepackgenerator.com' . "'r'n" .
    'Reply-To: newsubscription@samplepackgenerator.com';
mail($to, $subject, $message, $headers);
//message to user=========================================================================
$to      = $_POST['email'];
$subject = 'Subscribed!';
$message = 'Hello new member,
    Thank you for becoming a part of samplepackgenerator.com. You are now a community member and will recieve light email updates with the lastest information.  If you have recieved this email by mistake or wish to no longer be apart of this community please contact nickgarver5@gmail.com
    Cheers!,
    -Nick Garver ';
$headers = 'From: newsubscription@samplepackgenerator.com' . "'r'n" .
    'Reply-To: newsubscription@samplepackgenerator.com';
mail($to, $subject, $message, $headers);
// show a message of success and provide a true success variable==========================
$data['success'] = true;
$data['message'] = 'Subscribed!';
}
?>

HTML

  <!--  Subscription  -->
  <div class="container shorter">
    <div class="no-result vertical-align-outer">
      <div class="vertical-align">
        <form action="phEmail.php" method="POST">
          <!-- EMAIL -->
          <div id="email-group" class="form-group">
            <label for="email"></label>
            <input type="text" class="email" name="email" placeholder="Enter your email">
            <button type="submit" class="emailbtn">Subscribe</button>
             <span></span>
            <!-- errors -->
          </div>
          </div>
        </div>
      </div>
          <br>
          <br>
          <div id="sub_result">
          </div>

您只需要在PHP中使用json_encode,因为您的数据类型是json,并且您希望得到类似的json格式的响应

if (!empty($error)){
// your stuff
$data['success'] = false;
$data['errors']  = $errors;
echo json_encode($data);
}
else {
// your stuff
$data['success'] = "SUCCESS MESSAGE";
$data['errors']  = false;
echo json_encode($data);
}

这是因为您忘记了对$data数组进行编码。在结束PHP标记(?>)之前执行echo json_encode($data);,如下所示:

    // your code
    mail($to, $subject, $message, $headers);
    // show a message of success and provide a true success variable==========================
    $data['success'] = true;
    $data['message'] = 'Subscribed!';
    }
    echo json_encode($data);
?>

php不返回任何值,在末尾添加一个简单的"echo"行:

...
$data['success'] = true;
$data['message'] = 'Subscribed!';
}
echo $data['message'];
?>

在js中(如果所有其他代码都是正确的),您会收到消息。

php文件不会向输出发送任何内容。

添加一行exit(json_encode($data));在您想要返回回复的行上,将您的php文件。