跨两页的PHP变量

Sorry if the title is inaccurate, but I need help syncing a variable across two pages, when the second is loading with ajax (Instant Messanging)

I need it to fetch a page with ajax, just if I define a variable earlier on in the same document it doesn't apply to the ajax page (I can't use include)

page1.php

<?php $variable = 'apples'; ?>
<script src="script.js"></script> <!--Contains ajax for page2.php-->

<div id="gets_parsed_here"></div>

And it uses ajax to get page2.php

page2.php

<?php echo $variable; ?>

This isn't my actual code, but it's similar to what it should do.

Any help would be appreciated a lot.

I think what you are asking is how to pass a variable from page1.php to page2.php, when page1.php calls page2.php via AJAX.

As your script is in an external JS file, there are 2 steps involved:

  • Get the variable in Javascript, so script.js can access it. How you do this depends on what you're actually doing, but here's a simple example. Add the following somewhere on page1.php before you include script.js:

    <script>
        var fruit = <?php echo json_encode($variable); ?>;
    </script>
    

    Alternatively it might make more sense to read the variable from wherever it already appears on the page, eg (with jQuery):

    var fruit = $('#someID).val();
    
  • Pass the Javascript variable on to page2.php in the AJAX request. You can do that by passing it as a GET or POST parameter. You haven't shown how you're doing the AJAX call in script.js, but here's how you can do it in jQuery (this is GET):

    $.ajax({
        url: 'http://your-site/page2.php',
        data: { 'fruit': fruit },
        success: function(resp) {
            // AJAX is done, use the response
        }
    });
    

    This issues a request to http://your-site/page2.php?fruit=apples. And as you know from PHP 101 you can access the value of fruit in page2.php like:

    echo $_GET['fruit'];
    

    If you are using a framework use it's preferred method of accessing the input request parameters instead of accessing $_GET directly.

You can try using COOKIES/SESSION.

for example:

page1.php

<?php
@session_start();
    //if you get your variable from a remote page you should place it this var defination bellow:
<?php $_SESSION['keyName'] = 'apples'; ?>
<script src="script.js"></script> <!--Contains ajax for page2.php-->

<div id="gets_parsed_here"></div>

page2.php

<?php 
@session_start();
echo $_SESSION['keyName']; 
?>

SESSION can be accssed from every page in the same server with no code related. you just have to enable it by using session_start();

  • really reccomend to add @ before session_start() due to security reason.

you can read more about SESSION on PHP.NET