PHP Global variables for an externally included, AJAX loaded PHP file

4.2k Views Asked by At

Is it possible to access a Global variable declared in a file, e.g. a header.php file, from another external PHP file named content.php that has been loaded with an AJAX call, without using GET or POST?

e.g.

index.php:

<?php

    include 'header.php'; //The global variable $SESSIONID is defined in this file

    echo '<div id="for-content"></div>';

    include 'footer.php';
?>

header.php

<?php
    $SESSIONID = "asdf";
?>

content.php:

<?php
    echo $SESSIONID;
?>

And the AJAX call:

$("#for-content").load("content.php");
1

There are 1 best solutions below

2
Yannici On BEST ANSWER

No it isn't possible to get access to the global variable. You have to include header.php again. AJAX is loading the document (in your case content.php) asynchronous with a complete new http-request. So it will loading content.php without any data.

The only possible solution is to send $SESSIONID with AJAX-Call via POST:

$.ajax({
  type: "POST",
  url: 'content.php',
  data: {session: '<?php echo $SESSIONID; ?>'},
  success: function(data) {
       $('.target').html(data)
    },
  dataType: 'html'
});

or GET

$.ajax({
  url: 'content.php',
  data: {session: '<?php echo $SESSIONID; ?>'},
  success: function(data) {
       $('.target').html(data)
    },
  dataType: 'html'
});