Page 1 of 1

XML from PHP doesn't refresh

Posted: Sat May 29, 2010 5:48 am
by Wrathrowe
I have an HTML page that calls a function in javascript that calls a function in php. I'm trying to display how many rows I have in a mysql table in php, and I'm passing it back as XML to javascript to parse and place it in HTML. The only thing is, it doesn't refresh unless I actually type in the php page in the address bar, which shows the XML information, then when I reload it, it updates. I've read that it's probably a caching problem, but I can't seem to find a solution. Here are some examples of my code...

<html>
<head>
<script type="text/javascript" src="getRows.js"></script>
<head>
<body onLoad="getRows()">
<div id="rows"></div>
</body>
</html>

JAVASCRIPT
function getRows(){
if(xmlHttp.readyState == 4 || xmlHttp.readyState == 0){
xmlHttp.open('GET', 'getRows.php', true);
xmlHttp.onreadystatechange = getRowsResponse;
xmlHttp.send(null);
}
}
function getRowsResponse(){
if(xmlHttp.readyState == 4){
if(xmlHttp.status == 200){
var xmlResponse = xmlHttp.responseXML;
xmlRoot = xmlResponse.documentElement;
RowArray = xmlRoot.getElementsByTagName('Rows1');
document.getElementById('rows').innerHTML = RowArray.item(0).firstChild.data;
}
}
}

PHP CODE

Code: Select all

<?php	
	ini_set('session.cache_limiter','private');
	session_start();
        $mysqli = new mysqli('localhost', 'root', '', 'myDB');
	header('Content-Type: text/xml');
	
	$dom = new DOMDocument();
	$response = $dom->createElement('response');
	$dom->appendChild($response);
        $RowResult = $mysqli->query("SELECT * FROM table");
        $RowNum = $mysqli->affected_rows;
        
        $RowText = $dom->createTextNode($RowNum);
	$RowRes = $dom->createElement('Row1');
	$RowRes->appendChild($RowText);
	$response->appendChild($RowRes);
        
        $xmlString = $dom->saveXML(); 
	echo $xmlString;
    
        $RowResult->close();
        $mysqli->close();
?>
Thanks for any help!!!

Re: XML from PHP doesn't refresh

Posted: Sun May 30, 2010 6:38 am
by kaszu
To solve caching add something random/unique to url and since date is in milliseconds:

Code: Select all

var r = (new Date()).getTime();
xmlHttp.open('GET', 'getRows.php?' + r, true);