weixin_33716154 2017-10-05 15:37 采纳率: 0%
浏览 30

Json返回未定义

Good day guys I have the following login page. Which I access using ajax from my view page. The problem the data that is returned when I try to display on ajax I get an error on the console.

login.js:35 Uncaught TypeError: Cannot read property 'success' of undefined at Object.success (login.js:35) at i (jquery-2.2.0.min.js:2) at Object.fireWith [as resolveWith] (jquery-2.2.0.min.js:2) at z (jquery-2.2.0.min.js:4) at XMLHttpRequest. (jquery-2.2.0.min.js:4)

<?php
ob_start();

function __autoload($classname)
{

    require_once("../../database/$classname.php");
}


class userlogin extends database
{

    private $errors = array();
    private $message = array();
    private $redirect = array();
    private $data = array();
    private $username;
    private $password;

    function login()
    {

        if (empty($_POST['username']) || empty($_POST['password'])) {

            $this->message['error'] = "Please enter username and password";
        } else {

            $this->username = $_POST['username'];
            $this->password = $_POST['password'];


            try {
                $this->stmt = $this->dbh->prepare("SELECT adminID,adminEmail,adminPassword,admintype FROM admin where adminEmail = ? ");

                $this->stmt->execute(array(
                    $this->username
                ));

                $this->results = $this->stmt->fetchall();

                if (count($this->results) > 0) {
                    foreach ($this->results as $key => $row) {
                        if (password_verify($this->password, $row['adminPassword'])) {
                            $_SESSION['user']  = $row['adminID'];
                            $_SESSION['email'] = $this->username;
                            $_SESSION['usertype'] = $row['admintype'];

                            switch ($row['admintype']) {
                                case 's':
                                    $this->redirect['redirect'] = "seo/index.php?route=home";
                                    break;
                                case 'a':
                                    $this->redirect['redirect'] = "admin/index.php?route=home";
                                    break;
                            }

                            $this->message['success'] = "ok";

                        } else {

                            $this->message['error'] = "Username and password does not match";
                        }

                    }

                } else {

                    $this->message['error'] = "Username does not exist";
                }

            }
            catch (PDOException $pdo) {

                $this->error = $pdo->getMessage();

                error_log($this->error);
            }

            $this->data['message']  = $this->message;
            $this->data['redirects'] = $this->redirect;

            ob_end_clean();

            echo json_encode($this->data);

        }  

    }


}

if ($_SERVER['REQUEST_METHOD'] == "POST") {

    $login = new userlogin();
    $login->login();
}
?>

and my js

function proccessLogin(){

        var username = $('input[type="email"][name="email"]').val();
        var password = $('input[type="password"][name="upass"]').val();
        $.ajax({

            type : "POST",
            data : {username:username,password:password},
            url  : "controller/login.php",
            beforeSend : function(){
            $('button').html('Checking...');

            },
            success : function(data){
                console.log(data);

                 if(data.message.success == "ok"){
                    $('#results').removeClass('error');
                    $('#results').addClass('success');
                    $('#results').html('login Success, loading user data..');
                    $('button').html('Loading Profile.. i class="fa fa-spinner fa-pulse fa-1x fa-fw"></i>');
                        var redirectUrl = JSON.stringify(data.redirects);
                        redirectUrl = redirectUrl.replace(/[{"":}]/g, '');
                        var url = redirectUrl.replace('redirect','');
                        setTimeout(' window.location.href = "'+ url + '"; ', 6000);
                }else{

                    $('button').html("Sign in");
                    $('#results').removeClass('success');
                    $('#results').addClass('error');
                    $('#results').html(data.message.error);
                }
            },
            error : function(xhr){

                console.log('Error : ' + xhr);
            }
        });
    return false;   
    }

Console log results :

{"message":{"success":"ok"},"redirects":{"redirect":"seo\/index.php?route=home"}}

I want to be able to display the message from the json array if success is ok I will display custome message else display what is coming from response. the problem is property undefined.

line 35 :

if(data.message.success == "ok"){

  • 写回答

1条回答 默认 最新

  • weixin_33720078 2017-10-05 15:51
    关注

    I think the response data is String and you need to call

    $.parseJSON(data);
    

    before you can access message and then success

    =============

    If you want to use dataType: "json", you need to send your JSON as JSON by using PHP's header() function:

    /* Send as JSON */
    header("Content-Type: application/json", true);
    
    /* Return JSON */
    echo json_encode($json);
    
    /* Stop Execution */
    exit;
    
    评论

报告相同问题?

悬赏问题

  • ¥15 2024-五一综合模拟赛
  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭