I have a php session array and ajax request to add captured data to a div via java script. All works fine except when I refresh the page the data disappears until I add the next item all shows up again. How can I fix this issue?
file 1 (test.php):
<?php
session_start();
?>
<!DOCTYPE html>
<html>
<head>
<script>
function loadXMLDoc()
{
var xmlhttp;
var myname = document.getElementById("firstname").value;
if(window.XMLHttpRequest){
xmlhttp = new XMLHttpRequest();
}
else
{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if(xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("POST", "test2.php", true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send("firstname="+myname);
}
</script>
</head>
<body>
<h1>Enter Your Name</h1>
<input id="firstname"> </input>
<button type="button" onclick="loadXMLDoc()"> Add Item </button>
<div id="myDiv"></div>
</body>
</html>
file 2 (test2.php):
<?php
session_start();
$myitems = array();
if (!isset($_SESSION['item'])) $_SESSION['item']=$myitems;
if (isset($_POST['firstname']) && !empty($_POST['firstname'])) {
$data = $_POST['firstname'];
$_SESSION['item'][] = $data;
}
//echo '<pre>';
//print_r($_SESSION);
//echo '</pre>';
foreach ($_SESSION['item'] as $key=>$value){
echo "<h2>".$value."</h2>";
}
?>