简体   繁体   English

传递自定义错误消息AJAX

[英]Pass custom error message AJAX

On my index.php page, I have a form. 在我的index.php页面上,我有一个表单。 When you submit the form, it goes to process.php, which runs the code below: 提交表单后,它进入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!');
            }
        }
    });
});
});

This then executes the following code which is the proclogin.php page: 然后执行以下代码,即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);


?>

When the email field is blank, you get the error message that is written in the process.js page. 当电子邮件字段为空白时,您将获得在process.js页面中编写的错误消息。 When the password field is blank, you get the error message that is written in the process.js page. 当密码字段为空白时,您将获得在process.js页面中写入的错误消息。

Neither of the error messages get pushed through from the proclogin.php. 从proclogin.php都不会推送任何错误消息。 I'm not too fussed about that, what's bothering me is that the 'failed' one gets get pushed through to notify them of their credentials being wrong. 我对此不太在意,令我困扰的是,“失败”的人被迫通过通知他们的凭证错误。 I've played around with the code and tried to match what was above but I cannot get it to work. 我玩过这些代码,并尝试匹配上面的内容,但是我无法使其正常工作。

I also created a $errors['deny'] = "Incorrect details"; 我还创建了$ errors ['deny'] =“错误的详细信息”; and tried to push it through on the process.js page as data.errors.deny - is this the correct way? 并尝试将其作为data.errors.deny推送到process.js页面上-这是正确的方法吗? (new to AJAX/jQuery). (是AJAX / jQuery的新功能)。

You must pass event in the function parameter. 您必须在function参数中传递事件。 try this: 尝试这个:

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

}); });

Using the latest toastr and jquery, this works fine 使用最新的toastr和jquery,可以正常工作

in proclogin.php you need to modify this part of the code: 在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';

       }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM