Search code examples
phpjqueryajaxpdoconcept

PHP modules: how to "connect" files for AJAX requests


Assuming I have a file structure like this:

/
index.php                   // holds db connection, login information, ...
...
/someSubSite
    content_someSite.html   // basic structure, texts, forms, ...
    styles_someSite.css     // styling of content_someSite.html
    backend_someSite.php    // should send answers of AJAX requests
    frontend_someSite.js    // sends AJAX requests
                            // (when a form is submitted)
    ...

The db connection in index.php is realized via a PDO. So, obviously, I can not directly use this db-object in backend_someSite.php because it is declared and initialized in index.php -> two different scopes, no interaction between these files.

So my question now is: What is the best way to solve this problem?

Should I just create a PDO for every php-file for every sub-site? And share login information gathered by index.php via a PHP Session?

Basically the question is: What is the best way to share information or even whole PDO and other objects between index.php and backend_some(sub)Site.php when the subsites are queried via AJAX by the frontend.


Solution

  • It's unclear what else is in index.php. If it is literally just as you described, you can include it in backend_someSite.php.

    If it has other things, for example anything that is output to the browser, then you should make a file that contains ONLY things like connection information (I'd suggest calling it config.php) and then include this file instead (both in index.php and backend_someSite.php)