-2

Method to get Data: I am trying to get data with axios. But there is no result is coming and also there is no error!!!!!

getTodoList() {
    axios({
        method: 'GET',
        url: 'api/todos.php'
    }).then(function(res){
         console.log(res);
    })
}

It is giving me this Result:

enter image description here

api.todos.php

<?php
    class Todo {

        private $connection_string ;

        public function __construct() {
            // connection code. Connection is okay. 
        }

        public function fetchTodo() {
            $sql = "SELECT * FROM todo ";
            $result = mysqli_query($this->connection_string, $sql);
        }
    }

    $todo = new Todo;
    $todo->fetchTodo();
?>

What is the problem, I can't understand!!

aspile
  • 543
  • 8
  • 23
  • Well, `fetchTodo()` executes a query and, assuming it works, stores a result object in `$result`. And that's it. You haven't told it to do anything else, like actually output the data. – rickdenhaan Apr 22 '20 at 15:25
  • Yes. You are exactly right. What will I do then? How will pass it to an array? – aspile Apr 22 '20 at 15:37

1 Answers1

1

I'll assume you want your API to return JSON data.

As you can see from your screenshot, your PHP code is currently sending a (empty) HTML response: headers: { [...] content-type: "text/html; charset=UTF-8", [...] }. That is the default for PHP, if you intend to output JSON you will have to explicitly send the correct header.

Since your function is named fetchTodo() I will only make it fetch the data and deal with outputting it as JSON somewhere else.

<?php
    class Todo {

        private $connection_string ;

        public function __construct() {
            // connection code. Connection is okay. 
        }

        public function fetchTodo() {
            $sql = "SELECT * FROM todo ";
            $result = mysqli_query($this->connection_string, $sql);

            // add this line
            return $result ? $result->fetch_all(MYSQLI_ASSOC) : [];
        }
    }

    // tell whoever requested this API that we're going to send JSON data
    header("Content-Type: application/json");

    $todo = new Todo;

    // output whatever fetchTodo() returns as JSON
    echo json_encode($todo->fetchTodo());
?>

Note that this does not handle any query errors. I'll assume your connection code sets error reporting up properly. If you don't already have one, you might consider adding a global error handler to send a JSON response if things break, perhaps something like this.

rickdenhaan
  • 10,857
  • 28
  • 37