I'm in need of some assistance when it comes to working with $_GET
, $_SESSION
and the XMLHttpRequest
. I have constructed a minimum working example to illustrate the problem:
index.php
<?php
session_start();
$_SESSION['current'] = 2;
?>
<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="ajax.js"></script>
</head>
<body>
<div id="content"><?php include('table.php'); ?></div>
</body>
</html>
table.php
<?php
if(isset($_GET['current']))
{
$_SESSION['current'] = $_GET['current'];
}
$current = $_SESSION['current'];
echo '<h1>Table Value = '.$current.'<br>';
?>
browse.php
<?php
if(isset($_GET['current']))
{
$_SESSION['current'] = $_GET['current'];
}
$current = $_SESSION['current'];
echo '<h1>Browse value = '.$current.'<br>';
print "<input type=\"button\" value=\"Click here\" onclick=\"myfunc($current)\"/> ";
?>
ajax.js
function myfunc(input) {
xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET","table.php?current=" + (input+1),false);
xmlhttp.send();
document.getElementById("content").innerHTML=xmlhttp.responseText;
xmlhttp.open("GET","browse.php",false);
xmlhttp.send();
document.getElementById("target").innerHTML=xmlhttp.responseText;
}
I use the Firebug console to keep track of what's happening. First let me point out that I set the async parameter to false because my server requests are so small. When I click the button myfunc(2)
is executed and it requests ./table.php?current=3
and ./browser.php
from the server.
My thought was that since I request ./table.php?current=3
first, the session variable $_SESSION['current']
will be set to 3. But when browse.php is requested the session variable is not set! This is what happens after I click the button once:
Any idea what might be wrong? Thanks in advance :)
You need to add session_start();
at the beginning of browser.php. (As Marc B comments to your question).
If you are not sure which script was included in another script which has already started the session, you may use
if(!session_id()) session_start();
at the beginning of every php script.
To your reasoning:
I set the async parameter to false because my server requests are so small.
The problem is the network communication which may freeze your page for significant time (or forever in some cases), regardless the size of the response.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With