I have a PHP page, 'home.php', beginning like this:
require_once "data/secure/sessions.php";
session_start();
require "data/secure/dbconn.php";
require "data/get_data.php";
....
<div id="store_items">
<?php echo getStoreItems(); ?>
</div>
...
The sessions.php file controls sessions and works as expected. Then in the HTML within the same page, there is a function called getStoreItems() that begins like this:
<?php
header("Cache-control: no-store, no-cache, must-revalidate");
header("Expires: Mon, 26 Jun 1997 05:00:00 GMT");
header("Pragma: no-cache");
header("Last-Modified: ".gmdate("D, d M Y H:i:s")." GMT");
require "secure/dbconn.php";
$current_store_brand = "";
$current_store_name = "";
$items_per_page = 15;
$item_type = "Groceries";
...
function getStoreItems()
{
$current_page = 1;
$store_data = "";
$pages_html = "";
if($GLOBALS['current_store_brand'] != "")
{
$conn = mysqli_connect($GLOBALS['host'], $GLOBALS['user'], $GLOBALS['password'], $GLOBALS['database']) or die("Could not connect to database!".mysqli_connect_error());
...
return "No Stores found for ".$_SESSION['location'].", ".$_SESSION['country'].".";
}
?>
On the home.php page, I have a jQuery function that calls the function via a $.get() call to fetch more data from the file whenever the user clicks on a button. On the first run, when the user opens the page, the function runs perfectly, but when the jQuery function tries to get more data from the file 'get_data.php', the 'home.php' page returns the error
"Undefined variable: _SESSION in data/get_data.php".
I have tried including the 'sessions.php' file in the external file but to no avail. I have also tried an if...else... statement to require the sessions.php file if the $_SESSION variable is not available. Why isn't the $_SESSION global array accessible when I call the external file using jQuery from 'home'php' page? Part of the the jQuery function is as shown below:
$('#store_items').on("click", ".item > .basket_data > button", function(event)
{
event.preventDefault();
...
$.get("data/get_data.php", {"basket":"", "username":$username, "item_name":$item_name, "item_qty":$item_qty, "store_brand":$store_brand, "store_name":$store_name}, function($data)
{
$('#shopping_cart').html($data);
}).fail(function(error)
{
$('#shopping_cart').html("An error occurred: " + error.status).append(error.responseText);
});
@Snowburn, thanks, your comment led me to the solution. i had to include the statements
if(!isSet($_SESSION))
{
require "secure/sessions.php";
session_start();
}
within the function itself, not outside at the beginning of the get_data.php file, so it looks like this:
function getStoreItems()
{
if(!isSet($_SESSION))
{
require "secure/sessions.php";
session_start();
}
....
now it works, thanks!!!