Page 1 of 1

AJAX call failing when it encounters session_start()

Posted: Fri Jun 12, 2009 5:02 pm
by noblegas
My app uses an ajax call to get information from the database and return it as a string to be parsed in javascript and placed in the correct controls on the form. When the ajax call is invoked (button click) it returns a status 500(internal server error). My ajax script...

Code: Select all

 
<?php       
    require_once('..\config.php');   
    session_start();  
    if (!isset($_SESSION['initiated'])) 
    { 
        session_regenerate_id(); 
        $_SESSION['initiated'] = true; 
    }
    $bAjaxCall = true;
    require_once('class.DataSource.inc.php');
        ...
?>
 
The script fails on session_start() and goes no further. I do not use session.auto_start in php.ini. The same code snippet works within the script that creates the page the ajax call is made from, see below.

Code: Select all

 
<?php
// Require the configuration file before any php code.
require_once('config.php');
 
// * Execute the script
main();
 
function main()
{
    session_start();  
    if (!isset($_SESSION['initiated'])) 
    { 
        session_regenerate_id(); 
        $_SESSION['initiated'] = true; 
    }
        ...
}
?>
 
My ajax code is fine because it is working when I call other scripts that are not looking for session data. I am only making 1 ajax call from the web page.

Who has an(the) answer?

Re: AJAX call failing when it encounters session_start()

Posted: Fri Jun 12, 2009 5:06 pm
by JAB Creations
An HTTP 500 error sounds more like a .htaccess or Perl error, I've never encountered that sort of error with PHP.

I know you can't start a session once anything has been output to the client so move your session to be the first thing PHP executes.

Re: AJAX call failing when it encounters session_start()

Posted: Fri Jun 12, 2009 5:21 pm
by noblegas
HTTP Error 500 - Internal server error : Explained
It is caused by an ajax call and you are correct it is not a php error. It just means that an error occurred in the script that was requested from the server.

Since the only code executed in my script prior to the session_start() is the require_once('..\config.php'); You might be correct in your understanding, however it works perfectly in the script also mentioned that creates the page that makes the ajax call.

If I remove the session_start() from the script called by ajax it will execute up until it reaches a session variable reference, then it dies because the session was not started.