传递自定义错误消息AJAX

时间:2018-06-13 15:04:46

标签: javascript php jquery ajax

在我的index.php页面上,我有一个表单。提交表单时,会转到process.php,它运行以下代码:

$(document).ready(function() {
$('#login_button').click(function()
{
    event.preventDefault();
    var formData = {
        'email'         : $('input[name=email]').val(),
        'password'      : $('input[name=password]').val()
    };

    $.ajax({
        type        : 'POST',
        url         : 'ajax/proclogin.php',
        data        : formData,
        dataType    : 'json',
        success     : function(data)
        {
            if (data.success == false)
            {
                if(data.errors.email)
                {
                    toastr.error('Email is blank. Type in an email.');
                }
                else if(data.errors.password)
                {
                    toastr.error('Password input is blank. Type in a password.');
                }
            }
            else
            {
                toastr.success('Works!', 'WooHoo!');
            }
        }
    });
});
});

然后执行以下代码,即proclogin.php页面:

<?php
// proc(ess)login.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 (empty($_POST['email']))
{
    $errors['email'] = 'Email field is blank.';
}

if (empty($_POST['password']))
{
    $errors['password'] = 'Password field is blank.';
}

// return a response ===========================================================

// if there are any errors in our errors array, return a success boolean of false
if(empty($errors))
{

    // if there are no errors process our form, then return a message
        $connection = mysqli_connect("****","*****","*****","*****");
        $email = mysqli_real_escape_string($connection, $_POST['email']); # Define email field
        $input = mysqli_real_escape_string($connection, $_POST['password']); # Define password field

        $query = mysqli_query($connection, "SELECT `Email`, `Password` FROM users WHERE Email='$email' LIMIT 1"); # Query what we need
        $row = mysqli_fetch_array($query); # Fetch what we need

        $p = $row['Password']; # Define fetched details
        $email = $row['Email']; # Define fetched details
        if(password_verify($input, $p)) # Verify input password matches hashed password in the DB.
        {
            #It matches, let's set a session and redirect them to the dashboard.php page.
            //$_SESSION['SID'] = $email;
            $data['success'] = true;
            $data['message'] = 'Success';
        }
        else
        {
            $data['success'] = false;
            $data['message']  = 'failed';

       }
}
else 
{
    // if there are items in our errors array, return those errors
    $data['success'] = false;
    $data['errors']  = $errors;
}

// return all our data to an AJAX call
echo json_encode($data);


?>

当电子邮件字段为空时,您将收到在process.js页面中写入的错误消息。 当密码字段为空时,您将收到在process.js页面中写入的错误消息。

这两个错误消息都没有从proclogin.php中推送出来。我对此并不太感兴趣,困扰我的是“失败的”#39;一个人得到推动通知他们他们的凭据是错误的。我已经玩过代码并试图匹配上面的内容,但我无法让它工作。

我还创建了一个$ errors [&#39; deny&#39;] =&#34;错误的细节&#34 ;;并尝试在process.js页面上将其推送为data.errors.deny - 这是正确的方法吗? (AJAX / jQuery新手)。

1 个答案:

答案 0 :(得分:0)

您必须在函数参数中传递事件。试试这个:

$(document).ready(function() {
$('#login_button').click(function(event){
    event.preventDefault();
    var formData = {
        'email'         : $('input[name=email]').val(),
        'password'      : $('input[name=password]').val()
    };
    $.ajax({
        type        : 'POST',
        url         : 'proclogin.php',
        data        : formData,
        dataType    : 'json',
        success     : function(data)
        {
            if (data.success == false)
            {
                if(data.errors.email)
                {
                    toastr.error(data.errors.email);
                }
                else if(data.errors.password)
                {
                    toastr.error(data.errors.password);
                }
            }
            else
            {
                toastr.success('Works!', 'WooHoo!');
            }
        }
    });
});

});

使用最新的toastr和jquery,这很好用

在proclogin.php中

你需要修改这部分代码:

if(password_verify($input, $p)) # Verify input password matches hashed password in the DB.
        {
            #It matches, let's set a session and redirect them to the dashboard.php page.
            //$_SESSION['SID'] = $email;
            $data['success'] = true;
            $data['message'] = 'Success';
        }
        else
        {
            $data['success'] = false;
            $data['success'] = false;
            $data['errors']['password']  = 'Pass not match';

       }
相关问题