Page 1 of 1

problem combining php with ajax

Posted: Tue Mar 28, 2006 8:33 pm
by joerosenthal
I am using ajax to automatically reload the content from my mysql database on a given interval without refreshing the page. The code to display the rows from mysql is totally functional but once put into the function below (test.php being the mysql query file)

Code: Select all

function refresh() {
include("test.php");
}
the page no longer reloads nor shows the mysql query. after troubleshooting, i noticed that echo and print seem to disrupt the javascript from working. upon removing the echo command the database is reloaded. even a simple echo of "text" brings the script to a failure. any insight on this issue would be much appreciated.

Posted: Tue Mar 28, 2006 8:40 pm
by feyd
If "test.php" relies on variables that are set prior to the function being called, it will have problems finding them as they will be in a different scope than the code.

Re: problem combining php with ajax

Posted: Tue Mar 28, 2006 8:40 pm
by Christopher
Not sure if that is Javascript or PHP, maybe:

Code: Select all

function refresh() {
<?php include("test.php"); ?>
}

Posted: Tue Mar 28, 2006 8:45 pm
by joerosenthal

Code: Select all

function refresh() {
         mysql_connect(localhost,username,password) or die(mysql_error());
        mysql_select_db(main) or die(mysql_error());
$query = "SELECT postby,date,time,ip,msg FROM chat ORDER BY date,time ASC LIMIT 0,4;";
$result = mysql_query($query) or die('Error, query failed');
while($row = mysql_fetch_array($result))
{
list($postby, $date, $time, $ip, $msg) = $row;
$postby    = htmlspecialchars($postby);
$msg = htmlspecialchars($msg);
$msg = nl2br($msg);
echo $ip;
}
}
thats the full code, the echo does not work even to echo a non variable string.

Posted: Tue Mar 28, 2006 8:56 pm
by feyd
and this code works if called outside of Ajax? Is the refresh function in Javascript or PHP?

Posted: Tue Mar 28, 2006 8:57 pm
by joerosenthal
code works flawlessly if called outside ajax, refresh function shown here is php. it stops refreshing once the echo command is there, but if i put the entire code sans the echo, it refreshes

Posted: Tue Mar 28, 2006 8:58 pm
by feyd
sounds like your Javascript isn't handling the return information correctly.

Posted: Tue Mar 28, 2006 9:06 pm
by joerosenthal
i think the javascript is ok because i just got it to return a string using

Code: Select all

return join("\n", array_slice(mysql_fetch_array($row), -2));
but that code was just a test and doesn't do the function that I had with the echo command

Posted: Tue Mar 28, 2006 10:27 pm
by feyd
without seeing more code, it's hard to recommend anything more than keep plunking away at it.