Ask your JavaScript questions! Pay money and get answers fast! (more info)

How can I make this script refresh with ajax? JavaScript

  • SOLVED

I have this script that pulls post data from a database and displays it on my site. I need this to check for updates to the topics table using Ajax every 10 seconds and refresh the output, but not refresh the entire page obviously. I know literally nothing about Ajax. Can someone assist with this please?


This is the PHP script, it's very simple as you can see:


<?php

//connect to the server
$connect = mysql_connect("localhost","","");

//connect to the database
mysql_select_db("");

//query the database
$query = mysql_query("SELECT * FROM topics ORDER BY last_post");

//fetch the results / convert results into an array

WHILE($rows = mysql_fetch_array($query)):

$topic_id = $rows['last_post'];
$topic_title = $rows['title'];
$reply_author = $rows['last_poster_name'];
$reply_time = date('h:i A', $rows['last_post']);
$reply_date = date('l, F d, Y', $rows['last_post']);
endwhile;

echo "The last post was made in <font color='blue'>$topic_title</font> by <font color='red'>$reply_author</font> at <font color='green'>$reply_time</font> on <font color='brown'>$reply_date</font>.";

?>

Answers (2)

2015-02-20

Rainner Lins answers:

First, your PHP code is doing unnecessary work by looping through all the rows in your table to return a single entry. You may want to change it to something like this, which fetches just the last post:


//connect to the server
$connect = mysql_connect("localhost","","");

//connect to the database
mysql_select_db("");

//query the database
$row = mysql_fetch_array( mysql_query( "SELECT * FROM topics ORDER BY last_post DESC LIMIT 1" ) );

if( empty( $row ) )
{
echo "No posts found.";
}
else
{
echo "
The last post was made in <font color='blue'>".$row['title']."</font>
by <font color='red'>".$row['last_poster_name']."</font>
at <font color='green'>".date('h:i A', $row['last_post'])."</font>
on <font color='brown'>".date('l, F d, Y', $row['last_post'])."</font>.";
}


As for fetching that over AJAX, that needs to happen on the browser. For that you will need to include a little bit of extra Javascript on the page that you want to display the latest post. This Javascript code would send a request to your PHP script and place the response in the "latest post" HTML container.


<div class="{$class}">

<!-- the JS code below will fetch the response from your script and place it in here -->
<div class="latest-post"></div>

<if test="boxTitle:|:$this->settings['gfm_title']"><h3>{$this->settings['gfm_title']}</h3></if>

{$this->settings['gfm_message']}

</div>

<script type="text/javascript">
// assuming you have jQuery already loaded..
// you could just leave this here, or move to another JS file
// that is loaded after your page HTML loads.
function fetchLatestPost( abort )
{
$( '.latest-post' ).load( 'myscript.php' );
if( abort ) return;
setTimeout( "fetchLatestPost()", 10000 );
}
fetchLatestPost();
</script>

<br />


Padgoi comments:

I think that's the problem. I'm using an Invision Power Board script and it doesn't seem to recognize additional HTML containers. Your PHP code worked perfectly, but the Ajax is not working. I'm using your exact code but it's not recognizing the <div class="latest-post"></div> and so the div is showing up but there's nothing inside of it. That's why I had to parse the original php file.


Padgoi comments:

Actually, I just put your code in a separate HTML file and the last post isn't showing up at all.


Rainner Lins comments:

The last post gets loaded by the JS code. All the work happens on this line:


$( '.latest-post' ).load( 'myscript.php' );


But for that to work, the jQuery library needs to be loaded prior to calling that line, and the path to your PHP script needs to be accessible via the browser.

You can try modifying the container without the ajax code to see if it works:



<script type="text/javascript">
function fetchLatestPost( abort )
{
document.getElementsByClassName( 'latest-post' )[0].innerHTML += 'test...';

if( abort ) return;
setTimeout( "fetchLatestPost()", 10000 );
}
fetchLatestPost();
</script>


Padgoi comments:

All that code is doing is showing the word test.
It's not pulling the last post. And i know the PHP script works because I'm calling it directly from the browser and it's fine.


Padgoi comments:

You can see for yourself here:

http://wootability.com/lastpost.html

http://wootability.com/lastpost.php

The HTML file is the script you provided.
The PHP works from the browser. The HTML does not. And I changed the myscript.php line in your code to lastpost.php as the file is called.


Rainner Lins comments:

Ok, looks like your forum uses Prototype, instead of jQuery. I've tested with this and it seems to work.



<!-- put this in the page where you want posts to load into -->

<div id="latest-post"></div>

<!-- put this on the same page, after the container above -->

<script type="text/javascript">
function fetchLatestPost()
{
new Ajax.Request( 'lastpost.php', {
onComplete: function( data )
{
document.getElementById( 'latest-post' ).innerHTML = data.responseText;
setTimeout( "fetchLatestPost()", 10000 );
}
});
}
fetchLatestPost();
</script>


Padgoi comments:

Empty again.
No posts showing.

http://wootability.com/lastpost.html

http://wootability.com/lastpost.php


Padgoi comments:

By the way, because you're putting so much work into this, if you figure it out and get it working, I'll double the amount.


Rainner Lins comments:

It has to be included with the rest of the site. Trying to load it like you are in that html file by itself is not going to work. That JS code relies on other JS code to be loaded first so it can work.

In your forum's template file, replace this:


<div class="{$class}">

<!-- this is how you are including the latest post right now -->

<center>{parse include="lastpost.php"}</center>

<if test="boxTitle:|:$this->settings['gfm_title']"><h3>{$this->settings['gfm_title']}</h3></if>

{$this->settings['gfm_message']}

</div>


With this:


<div class="{$class}">

<!-- this is how you want to load it using ajax -->

<div id="latest-post" style="text-align:center">
loading latest posts...
</div>

<if test="boxTitle:|:$this->settings['gfm_title']"><h3>{$this->settings['gfm_title']}</h3></if>

{$this->settings['gfm_message']}

</div>

<script type="text/javascript">
function fetchLatestPost()
{
new Ajax.Request( 'lastpost.php', {
onComplete: function( data )
{
document.getElementById( 'latest-post' ).innerHTML = data.responseText;
setTimeout( "fetchLatestPost()", 10000 );
}
});
}
fetchLatestPost();
</script>



Padgoi comments:

It worked!
Thank you for all of your help, my friend.
I've voted to assign the money to you and doubled it to $20. Thanks again!!

2015-02-20

Romel Apuya answers:

save that script as myscript.php
then create another html maybe named index.html

<html>
<head>
<script src="http://code.jquery.com/jquery-2.1.3.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function(){
function updateBox(){
$('#resultbox').load('myscript.php');
}
setInterval( "updateBox()", 10000 );
});
</script>
</head>
<body>
<div id="resultbox"><div>
</body>
</html>


Padgoi comments:

This isn't a possibility. I have parsed the original php file into a forum I run. Creating a new html file won't work, the ajax needs to be included in the php file.

This is the HTML that parses the php file into the forum script. lastpost.php is the name of the php file.


<div class="{$class}">
<center>{parse include="lastpost.php"}</center>
<if test="boxTitle:|:$this->settings['gfm_title']"><h3>{$this->settings['gfm_title']}</h3></if>
{$this->settings['gfm_message']}

</div>
<br />