简体   繁体   中英

Pass custom error message AJAX

On my index.php page, I have a form. When you submit the form, it goes to process.php, which runs the code below:

$(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:

<?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. When the password field is blank, you get the error message that is written in the process.js page.

Neither of the error messages get pushed through from the 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"; and tried to push it through on the process.js page as data.errors.deny - is this the correct way? (new to AJAX/jQuery).

You must pass event in the function parameter. 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

in proclogin.php you need to modify this part of the code:

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

       }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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