Can I call specific methods from file.php using JavaScripts fetch() function? (Answered)

I was rather new to OOP and JavaScript at the time of asking this question and I have gained some more experience with both since I asked this question.

Originally I had asked how to call a specific method in a php file with multiple methods, I did not know that it would be easier and better to make a REST api of sorts.

To implement these changes I would change this function: display.php

# Display's All Series
protected function SeriesDisplay()
{
  try {
    $sql = 'SELECT * FROM series';
    $stmt = $this->connect()->query($sql);
    $rows = $stmt->fetchAll();
    return $rows;
  } catch (TypeError $error) {
    return "Series Display Error: " . $error->getMessage();
  }
}

To an endpoint, the endpoint includes and initializes the class with all the functions in it and then calls the SeriesDisplay() function and echos the results as json for the fetch to grab and resolve.

New display.php:

// Includes the database to create a connection on class initialization.
include_once __DIR__ . '/../../config/database.php';

// Includes the series class containing all of the functions.
include_once __DIR__ . '/../../class/series.php';

// Initialize and connect database
$db = new Database();
$conn = $db->connect();

// Initialize series class with database connection
$items = new Series($conn);

// Call the function to get all the series from that database
$stmt = $items->SeriesDisplay();

// Assigns the database fetch results to an associative array and echos the JSON encoded array. If the fetchAll fails it echoes an array with an "error" saying not_found which can be used for error handling later on.
if ($row = $stmt->fetchAll(PDO::FETCH_ASSOC)) {
    echo json_encode($row);
} else {
    http_response_code(204);
    echo json_encode(["series" => "not_found"]);
}

The SeriesDisplay() function and the class its in would have been modified to look like this now:

class Series
{
    // DB Connection variable
    private $conn;

    // Table To Access
    private $table = "series";

    // Columns in the Database
    public $UID;
    public $Title;
    public $Description;
    public $Chapters;
    public $Folder;
    public $Image;
    public $ExistingImage;
    public $Created;

    // Initiates database connection with connection provided in class initialization and creates a folder to store the series in if it doesn't exist.
    public function __construct($db)
    {
        $this->conn = $db;
        $this->conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        if (!file_exists(__DIR__ . "/../series")) {
            mkdir(__DIR__ . "/../series");
        }
    }

    // Simple function without error handling, just attempts to grab everything from the database table and sends the array to the endpoint.
    public function SeriesDisplay()
    {
        $query = "SELECT * FROM $this->table";
        $stmt = $this->conn->prepare($query);
        $stmt->execute();
        return $stmt;
    }
}

Finally my fetch would look like this:

fetch("/../api/series/display.php")
  .then(res => res.json())
  .then(data => {
    // data would be used like so
    for (let i = 0; i < data.body.length; i++) {
        // data[i].UID | data.body[i].Title etc
    }
   });

Answer

You need to setup an ajax script to send the fetch request to. For example, you can have ajax.php on your server and make a fetch request to that via the url… https://example.com/ajax.php

Then you would send the relevant data to that from the fetch request. In your example, you would use the GET method. If you wanted to use a different function depending on the data you would simply access the data from the fetch request by looking in the $_GET array.

Example

ajax.php

function foo(){
   echo 'foo';
}

function bar(){
   echo 'bar';
}

if($_GET['action'] == 'foo'){
    foo();
} elseif($_GET['action'] == 'bar') {
    bar();
}

exit();

index.js

fetch('https://example.com/ajax.php', {
    method: 'GET',
    body: {
        action:'bar'
    })
    .then(data => {
        console.log(data);
    });

Clearly this is a very simple example and lacks any form of security or sanitization but this is essentially how ajax works.

Leave a Reply

Your email address will not be published. Required fields are marked *