I have been learning how to setup and use ajax in PHP the past few days, and have hit a roadblock that I can’t quite seem to Google my way out of.
My webpage successfully calls api/api.php
and can run through whatever php code I need.
However, it seems to have no access to create class objects, and I have no idea how to let it access the rest of my application.
Example code snippet below of what I was trying to do.
$dashboard = new Dashboard;
$output = $dashboard->tableWidget("newdevs");
echo json_encode(array("value" => $output , "status" => "success"));
Error Log Example:
PHP Fatal error: Uncaught Error: Class 'Dashboard' not found in /var/www/html/mainApp/api/api.php
So here’s my basic web app file structure:
Main App:
api/api.php
classes/exampleClass.php
css/cssExample.css
includes/config.php
->database.php
->common_functions.php
->jtlogin.js
->table.js
module/home.php
->otherPage.php
scripts/myApp.js
index.php
Upon calling that api.php file via ajax, it seems to run it again, but can’t access anything.
I found this out by having this line at the top: if(!defined("APPLICATION")) die("nope");
Note on startup this runs and works fine, but fails upon an ajax call.
I also have api.php required in my config file, with the path defined:
define("API_PATH", ROOT_PATH ."/api/");
require API_PATH ."/api.php";
I feel like I’m missing some sort of key configuration step that have been absent from all of the tutorials I have seen.
My bare bones question is, how can I access all of my classes when I call my api.php file via an ajax call?
If anyone needs any additional details, I’ll be happy to oblige. I’ll be continuing to research the solution, and will come back if I find something first.
2
Answers
My solution to this wasn't to define the api.php file in my config, but rather put this at the top of my api.php file to be able to access the rest of my application's files:
require "includes/config.php";
On top of that, I moved the api.php file into the main folder of my application, rather than a sub folder. However, I would still rather have it organized in a sub folder, and I am still researching how to give it access.
If I understood your question correctly, what you are looking for is PHP autoloader. If the request is performed via AJAX or not is irrelevant in this case. You always need, in your entrypoint (the PHP file that is initially executed), to define an autoloader.
Usually that’s done using Composer (PHP’s dependency manager), but you can write your own autoloader: https://www.php.net/manual/en/language.oop5.autoload.php
PS.: If you write your own autoloader, follow the PSR-4: https://www.php-fig.org/psr/psr-4/