How to handle AJAX requests and Sessions and Db connections?

advertisements

Okay, the best way I know to describe the scenario is to first give the example:

Say I have a page called index.php;

At the very top before the <html> tag, one can find;

<?php session_start();
 $_SESSION['user_id'] = 1234;
 require_once "db.con.php";
?>

Inside that of the <body> tag, one can find:

<div id="div_ajax">
<?php require_once "ajax.php"; ?>
</div>

Now inside the ajax.php page, there is a single button that when clicked will make an ajax request. After the request is made, a simple Db query statement to select user information based on the user_id will be made. The thing is, after the AJAX request, it seems as if the user_id session and the already included Db connection is "lost".

I know I can use a conditional statement to check for AJAX request and just add the lines...

session_start();
require_once "db.con.php";

..at the top of the ajax.php page, but I'm wondering if there's a better way to do this? I don't want to always have to add those two lines to every ajax called PHP page. It sort of defeats the purpose of having the lines on the master page (index.php) to begin with. I guess I can use one ajax called page and just include a bunch of case statements, but still wondering if there's a better way.

Thanks a lot.


As far as my experience goes, I think your problem can be solved with something called the FrontController pattern.

The basic idea is that you're whole application always calls the same file, index.php for instance (also called the single point of entry).

index.php then performs all the tasks that you need on every single page (like starting the session or including your library classes) and then calls the page you want to requested.

This could look something like this: (Can't test it now)

index.php:

<?php

    session_start();
    $_SESSION['user_id'] = 1234;
    require_once("db.con.php");

    if($_REQUEST['Request_Type'] == 'website'){
        require_once("header.html");

        switch($_REQUEST['Request_Url']){
            case 'SomePage':
                require('SomePage.php');
                break;
            case 'SomeOtherPage':
                require('SomeOtherPage.php');
                break;
            default:
                require('ajax.php');
        }

        require_once("footer.html");

    }elseif($_REQUEST['Request_Type'] == 'ajax'){
        switch($_REQUEST['Ajax_Function']){
            case 'ProcessButton':
                require('ProcessButton.php');
                break;
        }
    }

?>

ajax.php

echo '<input type="button" onClick="ajaxRequest(\"index.php\",\"ProcessButton\")" Value="ClickMe!" />';

The ajaxRequest() Javascript function would have to send an Ajax Request to index.php setting the parameters
Request_Type = 'ajax'
Ajax_Function = 'ProcessButton'