简体   繁体   English

如何在JavaScript中从PHP调用函数,Ajax不返回任何内容

[英]How to call functions from PHP in javascript, Ajax not returning anything

I've been trying to get the data I have in my database(in my PHP file) over to my javascript program. 我一直在尝试将数据库中的数据(在PHP文件中)转移到我的javascript程序中。 I'm trying to get the query results over to the Javascript file so I can produce a graph out of these results. 我正在尝试将查询结果传递到Javascript文件,以便可以从这些结果中生成图形。

I have tried to use ajax but it isn't responding anything back. 我已经尝试过使用Ajax,但它没有响应。 I'm not sure where I'm going wrong. 我不确定我要去哪里。 My PHP file is called MySQLDau.php. 我的PHP文件称为MySQLDau.php。 Any help is much appreciated! 任何帮助深表感谢! Thanks! 谢谢!

PHP code: PHP代码:

<?php

    header("Access-Control-Allow-Origin: *");

    //Class for holding queries
    class MySQLDao
    {
        var $dbhost = null;
        var $dbuser = null;
        var $dbpass = null;
        var $mysqli = null;
        var $dbname = null;
        var $result = null;




        //constructor
        function __construct()
        {
            $this->dbhost = Conn::$dbhost;
            $this->dbuser = Conn::$dbuser;
            $this->dbpass = Conn::$dbpass;
            $this->dbname = Conn::$dbname;
        }

        //Attempt a connection to the database
        public function openConnection()
        {
            //Try and connect to the database
            $this->mysqli = new mysqli($this->dbhost, $this->dbuser, $this->dbpass, $this->dbname);
            //If the connection threw an error, report it
            if (mysqli_connect_errno())
            {
                return false;
            }
            else
            {
                return true;
            }
        }

        //Get method for retrieving the database conection
        public function getConnection()
        {
            return $this->mysqli;
        }

        //Close the connection to the database
        public function closeConnection()
        {
            //If there is a connection to the database then close it
            if ($this->mysqli != null)
                $this->mysqli->close();
        }

        //-----------------------------------QUERY METHODS-------------------------------------

        public function generateRoomID()
        {
            $sql = "INSERT INTO room (room_id) VALUES (null);";
            $result = $this->mysqli->query($sql);
            if ($result == true)
            {
                $toReturn["status"] = true;
                $toReturn["roomID"] = $this->mysqli->insert_id;
                return $toReturn;
            }
            else
            {
                $toReturn["status"] = false;
                $toReturn["message"] = mysql_error($this->mysqli);
                return $toReturn;
            }
        }

        public function saveRoom($data)
        {
            $roomID = $data[0];
            $roomDescription = $data[1];
            $columns = $data[2];
            $rows = $data[3];

            $this->mysqli->autocommit(FALSE);

            $this->mysqli->query("UPDATE room SET room_description='".$roomDescription."' WHERE room_id='".$roomID."';");

            for ($i = 0; $i<count($columns); $i++)
            {
                for ($j = 1; $j<=$rows[$i]; $j++)
                {
                    $currentLabel = "{$columns[$i]}{$j}";
                    $this->mysqli->query("INSERT INTO shelf (shelf_label) VALUES ('".$currentLabel."');");
                    $shelfID = $this->mysqli->insert_id;
                    $this->mysqli->query("INSERT INTO room_shelf (room_id, shelf_id) VALUES ('".$roomID."','".$shelfID."');");
                }
            }

            if ($this->mysqli->commit())
            {
                $toReturn["status"] = true;
                $toReturn["message"] = "Room Created";
                return $toReturn;
            }
            else
            {
                $this->mysqli->rollback();
                $toReturn["status"] = false;
                $toReturn["message"] = "SQL Error";
                return $toReturn;
            }
        }

        public function updateShelf($data)
        {
            $shelfID = $data[0];
            $itemName = $data[1];
        }

        public function getRoomDetails($data)
        {
            $roomID = $data[0];

            $sql = "SELECT room.room_description, shelf.shelf_label, shelf.shelf_id FROM room INNER JOIN room_shelf ON room.room_id=room_shelf.room_id INNER JOIN shelf ON shelf.shelf_id=room_shelf.shelf_id WHERE room.room_id='".$roomID."';";

            $result = $this->mysqli->query($sql);

            if (mysqli_num_rows($result) > 0)
            {
                $toReturn["status"] = true;
                $toReturn["message"] = "Room Found";
                $toReturn["room_description"] = $row['room_description'];
                $shelves = [];

                foreach ($result as $row)
                {
                    $currentShelf["shelf_label"] = $row['shelf_label'];
                    $currentShelf["shelf_id"] = $row['shelf_id'];
                    array_push($shelves, $currentShelf);
                }
                $toReturn["shelves"] = $shelves;
                return $toReturn;
            }
            else
            {
                $toReturn["status"] = false;
                $toReturn["title"] = "Error";
                $toReturn["message"] = "Room Not Found";
                return $toReturn;
            }

        }

        echo "Hello World!";

        public function getResults($data){

            $sql = "SELECT * FROM room";

            $result = $this->mysqli->query($sql);

            if (mysql_num_rows($result) == 1) {
                $obj = mysql_fetch_object($result, 'obResults');

            }

            echo json_encode($obj);
        }   
    }
?>

Part of my Javascript code: 我的Javascript代码的一部分:

  function callPHP() {
        $.ajax ({
            type: "GET",
            url: "MySQLDao.php",
            data: { action : 'getResults' },
            success: function(output) {
                alert(output);
            }
        });
    }

You don't have any code that is checking the GET parameters, instantiating the class and calling the function. 您没有任何代码可以检查GET参数,实例化该类并调用该函数。 Your AJAX request just creates that class, but does not actually execute anything. 您的AJAX请求仅创建该类,但实际上不执行任何操作。

What you can do, is after the closing } of the class definition is this: 您可以做的是,在类定义的结束}之后是这样的:

$daoObj = new MySQLDao();
$daoObj->getResults(); // this function takes a $data parameter, but doesn't use it

This will execute your getResults function, but is currently ignoring the "data: { action : 'getResults' }" part of your AJAX request. 这将执行您的getResults函数,但当前忽略了AJAX请求的“数据:{action:'getResults'}”部分。 Get the basic functionality working (ie. returning something useful), then improve upon it to execute different functions based on the AJAX request. 使基本功能正常工作(即返回有用的东西),然后对其进行改进以根据AJAX请求执行不同的功能。

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

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