0

I've been trying to get the data I have in my database(in my PHP file) over to my javascript program. I'm trying to get the query results over to the Javascript file so I can produce a graph out of these results.

I have tried to use ajax but it isn't responding anything back. I'm not sure where I'm going wrong. My PHP file is called MySQLDau.php. Any help is much appreciated! Thanks!

PHP code:

<?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:

  function callPHP() {
        $.ajax ({
            type: "GET",
            url: "MySQLDao.php",
            data: { action : 'getResults' },
            success: function(output) {
                alert(output);
            }
        });
    }
7
  • You haven't shown any part of your PHP code that actually writes a response, so we can't help you. Make sure your PHP actually sends a response. Commented Aug 16, 2017 at 16:57
  • How do I write a response? I couldn't find a good example. Thanks Commented Aug 16, 2017 at 16:59
  • You need to show the content of your MySQLDao.php file to allow us to help you. Commented Aug 16, 2017 at 17:07
  • Okay I've added my whole php code. Thanks Commented Aug 16, 2017 at 17:09
  • What you are getting in your network tab in browser ? Commented Aug 16, 2017 at 17:15

1 Answer 1

1

You don't have any code that is checking the GET parameters, instantiating the class and calling the function. Your AJAX request just creates that class, but does not actually execute anything.

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. Get the basic functionality working (ie. returning something useful), then improve upon it to execute different functions based on the AJAX request.

Sign up to request clarification or add additional context in comments.

9 Comments

I did this and I got an error with the ajax that is in the js file. How do I check the GET params and everything else I'm missing? Thanks
Ok, In the Network tab of your browsers debugger, you should be able to view the HTTP response, which may include the error message from PHP to debug this further.
Also, adding this "error_reporting(E_ALL); ini_set('display_errors', 1);" to the top of your PHP will help as well.
All I can find is 'send @ jquery-1.7.2.min.js:4 ajax @ jquery-1.7.2.min.js:4 callPHP @ test.html:263 (anonymous) @ test.html:283'
Hmm ok. well looking at your code more closely, the echo "Hello World!" needs to be removed. Can't have a random command in the middle of a class outside of a function. The 'var' in front of the variables at the top of the class should be changed to 'private'. In the constructor, you are referencing a class called Conn, but that is neither defined anywhere in that file, nor are any other files that might define that included. Change those to hard coded values for testing purposes.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.