Solved

AJAX update multiple divs from external .php's without reload

Posted on 2006-06-16
5
1,068 Views
Last Modified: 2011-01-13
Hi there,

I'm in the process of writing a small forum/message board and like to use AJAX for content updating instead of a complete refresh of the page.

I got the AJAX part running, but when updating multiple divs, the script 'collides' and the divs stop updating... Yelp?

The javascript/ajax part (ajax_test.php)

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>AJAX test page</title>
<style type="text/css">
body { font-family: verdana; font-size: 8pt; }
</style>
<script type="text/javascript">
function createRequestObject() {
    var req;
    if(window.XMLHttpRequest){
    // Firefox, Safari, Opera...
        req = new XMLHttpRequest();
    } else if(window.ActiveXObject) {
    // Internet Explorer 5+
    req = new ActiveXObject("Microsoft.XMLHTTP");
    } else {
    // There is an error creating the object,
    // just as an old browser is being used.
        alert('There was a problem creating the XMLHttpRequest object');
    }
    return req;
}

function handleDivTag(divtag) {
    var divtag;
    return divtag;
}

function handleTimeOut(timeout) {
    var timeout;
    return timeout;
}

function handleRefresh(refresh) {
    var refresh;
    return refresh;
}

// Create the Divtag Handler -- Mainly an IE 6 Fix
var divhandler = new handleDivTag(null);
var timehandler = new handleTimeOut(null);
var refreshhandler = new handleRefresh(null);

function sendRequest(act,divtag,timeout,refresh) {
    // Make the XMLHttpRequest object
    http = createRequestObject();
    // Open PHP script for requests
    http.open('get', act);
    http.onreadystatechange = function() { handleResponse(http); };    
    // Open PHP script for requests
    divhandler.divtag = divtag;
    timehandler.timeout = timeout;
    refreshhandler.refresh = refresh;
    http.send(null);
}

function handleResponse(http) {
    if(http.readyState == 4 && http.status == 200) {
        // Text returned FROM PHP script
        var response = http.responseText;
        // document.write(http.responseText);
        if(response) {
            // UPDATE ajaxTest content
            document.getElementById(divhandler.divtag).innerHTML = response;
            setTimeout(timehandler.timeout,refreshhandler.refresh);
        }
    }
}
 
function div1() {sendRequest('page.php','div1',div1,1000); }
function div2() {sendRequest('page.php','div2',div2,1000); }
</script>
</head>
<body onload=''>
<b>div1</b><br>
<div id="div1"><?php include ("page.php") ?></div>
<br>
<b>div2</b><br>
<div id="div2"><?php include ("page.php") ?></div>
<br>
<a href="javascript:div1();">Start refreshing div1</a>
<a href="javascript:div2();">Start refreshing div2</a>
</body>
</html>

...and the content page (page.php)

<?php
echo "System time: ".date("G:i:s",time());
//sleep (1);
?>

This works fine until the refresh collides. Uncommenting the sleep statement demonstrates this perfectly...

-tnx-

Harold.
0
Comment
Question by:aling
  • 3
  • 2
5 Comments
 
LVL 18

Accepted Solution

by:
Morcalavin earned 500 total points
ID: 16919396
I'll make one suggestion.  The ajax protype library makes setting up an ajax session much much easier, and it comes with nifty little shorthand tools.

http://prototype.conio.net/
0
 

Author Comment

by:aling
ID: 16919501
I'll have a look at it... I don't want to include the whole .js since it's ~48 kb but if I can extract the functions to get the above working, I'll give it a go...
0
 

Author Comment

by:aling
ID: 16919777
Well... It works... I'll leave the test page open to check if it keeps running, but I have a good feeling about it...

The prototype.js results in such a page:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>AJAX test page</title>
<style type="text/css">
body { font-family: verdana; font-size: 8pt; }
</style>
<script type="text/javascript" src="prototype.js"></script>
<script type="text/javascript">
new Ajax.PeriodicalUpdater('div1', 'page.php', {asynchronous:true, frequency:1});
new Ajax.PeriodicalUpdater('div2', 'page.php', {asynchronous:true, frequency:1});
// make a HTTP request every 2 seconds to /foo/bar and update the 'mydiv' element.
</script>
</head>
<body onload=''>
<b>div1</b><br>
<div id="div1"><?php include ("page.php") ?></div>
<br>
<b>div2</b><br>
<div id="div2"><?php include ("page.php") ?></div>
<br>
</body>
</html>

I'll keep this post open for a few days, if nobody comes up with a smaller (<48k) suggestion, I will award you your points.

-tnx!-
0
 
LVL 18

Expert Comment

by:Morcalavin
ID: 16919836
48k isn't all that much, and it should cache, making it irrelevant in due time.  Using the 48k library will eliminate a lot of error checking on your part and provides access to some nifty shortcuts, which will make the code you have to type smaller.  So it's a tradeoff, 48k of prewritten code to save you Xk of code you don't have to type.
0
 

Author Comment

by:aling
ID: 16920008
you're right...

this works, and is well supported... And I may even use some other functions of it!

Thank you!
0

Featured Post

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

In my daily work (mainly using ASP.net), I need to write a lot of JavaScript code. One of the most repetitive tasks I do are the jQuery Ajax calls. You know: (CODE) I don't know if for you it's the same, but for me is soooo tedious to write the …
Nothing in an HTTP request can be trusted, including HTTP headers and form data.  A form token is a tool that can be used to guard against request forgeries (CSRF).  This article shows an improved approach to form tokens, making it more difficult to…
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…

760 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

17 Experts available now in Live!

Get 1:1 Help Now