处理对Ajax的不同PHP验证响应,以显示在警报引导程序中

时间:2018-07-31 14:55:52

标签: javascript php html ajax twitter-bootstrap

我有一个通过电子邮件恢复密码的表格。我将输入发送到PHP以执行以下操作:

  1. 验证{三种不同的验证消息)
  2. 如果通过,则处理

一旦收到响应,在AJAX中虽然无效,但由于已在php中进行了处理,因此被认为是成功的。

我需要区分每个响应,以便显示适当的警报消息

  • 如果字段输入为空,我想在alert-info消息框中显示它
  • 如果字段输入不是有效的电子邮件,我想在alert-warning消息框中显示它
  • 如果在服务器中找不到字段输入,我想在alert-danger消息框中显示它
  • 如果成功,我想显示为成功

$(function() {
	// Get FORM ID ///////////////////////////////////////////
	var form = $('#RecoveryForm');
	// Get MESSAGE DIV ID ///////////////////////////////////////////
	var formMessages = $('#formresults');
	$(form).submit(function(e) {
		$( "#submit" ).prop( "disabled", false ); 
		e.preventDefault();
		var formData = $(form).serialize();
			$.ajax({
			type: 'POST',
			url: $(form).attr('action'),
			data: formData
			})
		.done(function(response) {
			$(formMessages).removeClass('error');
			$(formMessages).addClass('success');
			$(formMessages).text(response);
			// Get FORM ID ///////////////////////////////////////////
			document.getElementById("RecoveryForm").reset();
			//$('#reset-button').click();
		})
		.fail(function(data) {
			$(formMessages).removeClass('success');
			$(formMessages).addClass('error');

			if (data.responseText !== '') {
				$(formMessages).text(data.responseText);
			} else {
				$(formMessages).text('Oops! An error occured and your message could not be sent.');
			}
		});
	$("#submit").removeAttr("disabled");		
	});
});
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
</head>
<body>

    	<div id="formresults"></div>	 
	<form id="RecoveryForm" method="post" action="exa.php">
      <table align="center">
      <tr><td><div class="input-append"><input type="text" name="email" id="email" class="input-xlarge" placeholder="Email" maxlength="100" /><span class="add-on"><li class="icon-envelope"></li></span></div></td></tr>
      </table>
      <input type="hidden" name="token" value="<?=Token::generate();?>" />
      <center><input type="submit" id="submit" name="Forget" class="btn btn-primary" value="Submit" /></center>
    </form>
  	<script src="ajax/jquery-2.1.0.min.js"></script>
	<script src="ajax/app.js"></script>
<!---------------------------------------------------------------->
<?php include 'footer.php'; ?>
</body>
</html>

PHP代码>>

<?php   
header('Content-type: application/json');
require 'Access.php'; // Get Access
//response array with status code and message
$response_array = array();    
if ($_SERVER["REQUEST_METHOD"] == "POST") { 
    $email = $_POST["email"];                   

    if ( empty($email) ) {                      
        $response_array['status'] = 'info';
        $response_array['message'] = 'No Input';
        echo json_encode($response_array);
        exit;   
        }
    if ( !filter_var($email, FILTER_VALIDATE_EMAIL) ) {
        $response_array['status'] = 'warning';
        $response_array['message'] = 'Not Valid Email';
        echo json_encode($response_array);
        exit;   
        }
    if (@mysql_num_rows(mysql_query("SELECT `id` FROM `accounts` WHERE `email`='$email'")) < 1) {
        $response_array['status'] = 'danger';
        $response_array['message'] = 'Account Not Found';
        echo json_encode($response_array);
        exit;   
        }
            $row_user = @mysql_fetch_array(mysql_query("SELECT * FROM `accounts` WHERE `email`='$email'"));
            $password = $row_user['pass'];
            $to = $row_user['email'];
            $subject = "Your Recovered Password";
            $message = "Please use this password to login: " . $password;
            $headers = "From : XXX@hotmail.com";
    // Send the email.
    if (mail($to, $subject, $message, $headers)) {
        $response_array['status'] = 'Success';
        $response_array['message'] = 'Email Sent';
        echo json_encode($response_array);
        } else {
        $response_array['status'] = 'info';
        $response_array['message'] = 'Try Again Later';
        echo json_encode($response_array);
                }
} else {
$response_array['status'] = 'info';
        $response_array['message'] = 'Try Again Later';
        echo json_encode($response_array);
}
$response_array['status'] = 'info';
        $response_array['message'] = 'Try Again Later';
        echo json_encode($response_array);
?>

2 个答案:

答案 0 :(得分:1)

通过php验证报告不同的响应

.done(function(response) {
			var messageAlert = response.type;
			var messageText = response.message;
			var alertBox = '<div class="alert ' + messageAlert + '"style="margin-top:10px;"><button type="button" class="close" data-dismiss="alert">&times;</button><d style="font-size:11px; ">' + messageText + '</d></div>';
			(formMessages).html(alertBox);

为每个PHP语句添加:

$responseArray = array('type' => 'alert-warning', 'message' => '<b>Alert!</b>There is not enough credit');

然后发送响应json编码

if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
$encoded = json_encode($responseArray);     header('Content-Type: application/json');   echo $encoded; } else {    echo $responseArray['message'];      }

答案 1 :(得分:0)

首先,我们从html原因开始验证,因为这可能会受到用户的阻碍和操纵,但仍然是一种很好的开始方式。

首先,我们将required属性添加到html中的输入字段中,并更改input types以匹配您期望的数据类型,例如:input type="email"隐藏输入并不妨碍它的形式进行篡改,最好也添加Readonly属性。

   <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    </head>
    <body>
        <div id="formresults"></div>     
        <form id="RecoveryForm" method="post" action="exa.php">
            <table align="center">
                <tr>
                    <td>
                        <div class="input-append">
                            <input type="email" Required name="email" id="email" class="input-xlarge" placeholder="Email" maxlength="100" />
                            <span class="add-on"><li class="icon-envelope"></li></span>
                            <p id="mailerror"></p> <!-- This Segment Displays The Validation Rule For Email -->
                        </div>
                    </td>
                </tr>
            </table>
            <input type="hidden" Readonly name="token" value="<?=Token::generate();?>" />
            <center>
                <input type="submit" id="submit" name="Forget" class="btn btn-primary" value="Submit" />
            </center>
            <script src="ajax/jquery-2.1.0.min.js"></script>
            <script src="ajax/app.js"></script>
        </form>
     </body>
   </html>

第二个您正在使用jquery,尽管这要容易得多,但我建议您从Java脚本验证开始,使用onsubmit属性捕获表单并开始验证。您将更好地了解初学者而不是jquery到底发生了什么。

<script>
 $(function() {
    /*Get FORM ID*/
    var form = $('#RecoveryForm');

    /*Get MESSAGE DIV ID */
    var formMessages = $('#formresults');

    /*Email Validation*/
    var email_regex = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;
    var email = $('#email').val();

    if (!email.match(email_regex) || email.length == 0) {
    $('#mailerror').text("* Please enter a valid email address *");
    $("#email").focus();
    return false;
    }
    else if (email.match(email_regex) && email.length >= 5){
    $(form).submit(function(e) {
        $( "#submit" ).prop( "disabled", false ); 
        e.preventDefault();
        var formData = $(form).serialize();
            $.ajax({
            type: 'POST',
            url: $(form).attr('action'),
            data: formData
            })
        .done(function(response) {
            if (response.status=='Success'){
                $(formMessages).removeClass('error');
                $(formMessages).addClass('success');
                $(formMessages).text(response.message);
            }
            else if (response.status=='warning'){
                $(formMessages).removeClass('success');
                $(formMessages).addClass('error');
                $(formMessages).text(response.message);
            }
            else if (response.status=='danger'){
                $(formMessages).removeClass('success');
                $(formMessages).addClass('error');
                $(formMessages).text(response.message);
            }
            else if (response.status=='info'){
                $(formMessages).removeClass('success');
                $(formMessages).addClass('error');
                $(formMessages).text(response.message);
            }

            /*Get FORM ID */
            document.getElementById("RecoveryForm").reset();
        })
        .fail(function(data) {
            $(formMessages).removeClass('success');
            $(formMessages).addClass('error');

            if (data.responseText !== '') {
                $(formMessages).text(data.responseText);
            } else {
                $(formMessages).text('Oops! An error occured and your message could not be sent.');
            }
        });
    $("#submit").removeAttr("disabled");        
    });
    }
 });
</script>

您本来可以用PHP编写的所有PHP中的第三本可以做得更好,但是大概可以正常工作:(所以我们暂时保留它。