AJAX / JS没有显示警报

时间:2018-06-12 15:40:33

标签: javascript php jquery html ajax

我正在学习AJAX / JS,一旦提交了表单,我希望AJAX能够启动POST并返回数据。这已经完成,数据恢复正常并且成功,我无法得到警告'功能显示。我被重定向到我的process.php,其中包含以下内容:

{"success":false,"errors":{"email":"Email is required.","password":"Password is required."}}

我现在需要将上述内容显示在“警告”中,例如提醒('密码是必需的');

这是我的' process.js'形式:

$(document).ready(function()
{
event.preventDefault();
$('form').submit(function(event) 
{
    var formData = {
        'email'         : $('input[email=email').val(),
        'password'      : $('input[password=password').val()
    };

    $.ajax({
        type        : 'POST',
        url         : 'ajax/proclogin.php',
        data        : JSON.stringify(formData),
        dataType    : 'json',
            encode  : true 
    })

        // using the done promise callback
        .done(function(data)
        {
            console.log(data);

            if (!data.success)
            {
                if(data.errors.email)
                {
                    //toastr.error(''+data.errors.email+'', 'Oops!');
                    alert('Email error');
                }
                if(data.errors.password)
                {
                    //toastr.error(''+data.errors.password+'', 'Oops!');
                    alert('Password Error');
                }
            }
            else
            {
                //toastr.success('Works!', 'WooHoo!');
                alert('Works.');
            }
        });
});
});

这是'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 is required.';

if (empty($_POST['password']))
    $errors['password'] = 'Password is required.';

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

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

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

    // 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'] = 'fail';

       }


    // show a message of success and provide a true success variable
}

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


?>

2 个答案:

答案 0 :(得分:0)

你的提交处理程序之外有event.preventDefault();,它应该在里面。
您用来获取密码和电子邮件的选择器似乎是错误的 您尝试发送JSON但尝试读取表单数据。

$(document).ready(function(){

  $('form').submit(function(event) {
    event.preventDefault();// prevent the form from submitting normally
    var formData = {
        'email'         : $('input[type=email').val(),  // get the value of the email input
        'password'      : $('input[type=password').val() // get the value of the password input
    };

    $.ajax({
        type        : 'POST',
        url         : 'ajax/proclogin.php',
        data        : formData,  // send as form data 
        dataType    : 'json',
    })
...

答案 1 :(得分:0)

您需要检查是否设置了电子邮件或密码,然后显示如下警告消息:

.done(function(data) {
        if(data.errors.email) {
            alert('email required');
        }
        else if(data.errors.password) {
            alert('password required');
        }
        else {
            alert('done');
        }
    })
.fail(function() {
        console.log("error");
    })
    .always(function() {
        console.log("complete");
    });

并删除条件if (!data.success)