Peter
Peter

Reputation: 648

php $_session variable not working with jQuery get()

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!!!

Upvotes: 0

Views: 545

Answers (1)

Abhik Chakraborty
Abhik Chakraborty

Reputation: 44874

You need to add session_start(); in the data/get_data.php

In your home page you have

require_once "data/secure/sessions.php";
session_start();

require "data/secure/dbconn.php";
require "data/get_data.php";

So the file while loading gets the session data since the session_start is on the top

Now when u call the file by ajax it only executes data/get_data.php and this file does not know anything about session if session_start(); is not initiated.

I would suggest to to pass use the line as

$.get("data/get_data.php", 
{"basket":"", "username":$username, "item_name":$item_name, "item_qty":$item_qty, "store_brand":$store_brand, "store_name":$store_name},

to

$.get("data/get_data.php", 
{"basket":"","ajax_reg":"yes" ,"username":$username, "item_name":$item_name, "item_qty":$item_qty, "store_brand":$store_brand, "store_name":$store_name},

Then in the top of the file data/get_data.php add the following

if(isset($_GET["ajax_reg"]) && trim($_GET["ajax_reg"])== "yes"){
  require_once "data/secure/sessions.php";
  session_start();
}

So if you include this file on the home page then it will not re initiate the session_start but when you make a call via ajax get and if it finds the param "ajax_reg":"yes" then it will do the session start.

Finally, your files are in different folders so need to make sure that the session cookie save path is correct.

session_set_cookie_params(0, "/");
session_start();

http://www.php.net/manual/en/function.session-set-cookie-params.php

Upvotes: 1

Related Questions