A little bit of everything…
RSS icon Home icon
  • Refreshing DIV content with AJAX (multiple DIVs)

    Posted on February 25th, 2009 Aleix 27 comments

    AJAXAfter reading the post Refreshing DIV content with AJAX, you already know how to refresh the content of a DIV in your website with the help of AJAX. But perhaps you want to refresh more than one DIV, and you’ve realised the code in the other post didn’t work! Don’t panic, as a matter of a fact refreshing multiple DIVs is the same process than refreshing a single DIV. I’ve prepared an example and some code so you can see how easy it is. See the working demo here.

    The example is like the one in the aforementioned post (refreshing single DIV), but it has three DIVs in the same page instead of just one. I assume you read the post so you know what each part of the code is for (if you’ve not read it I recommend you to do so, as now I will go straight to the point). The files we need for this are (in the same folder):

    • ajax.js
    • index.html
    • boo.php
    • boo2.php
    • boo3.php

    So why so many ‘boo’ files? You can rename them to whatever you want, but be sure to also change the name in the customizable variables in ajax.js. In the example they’re named ‘boo’ for the sake of simplicity, and because the three of them have a common feature: each of them contains a different php script, and each of those scripts produces the content of each DIV.

    The three divs (click to enlarge)

    The three divs (click to enlarge)

    In the screenshot of the example to the right, boo.php outputs data into timediv, boo2.php into timeinwashington and boo3.php into otherdiv. Let’s see how this is done, with some code:


    ajax.js

    In comparison with the single DIV refresh example of the other post, ajax.js has many more lines of code. It basically controls each DIV’s behavior separately, with different parameters; note as well that the function to get the UNIX timestamp so to append it to the request URL and avoid IE caching requests, is common to them all and therefore appears only once. Of utmost importance however is to create a separate XMLHttpRequest object for each DIV!

    
    // The AJAX function...
    
    function AJAX(){
    try{
    xmlHttp=new XMLHttpRequest(); // Firefox, Opera 8.0+, Safari
    return xmlHttp;
    }
    catch (e){
    try{
    xmlHttp=new ActiveXObject("Msxml2.XMLHTTP"); // Internet Explorer
    return xmlHttp;
    }
    catch (e){
    try{
    xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
    return xmlHttp;
    }
    catch (e){
    alert("Your browser does not support AJAX.");
    return false;
    }
    }
    }
    }
    
    // Timestamp for preventing IE caching the GET request (common function)
    
    function fetch_unix_timestamp()
    {
     return parseInt(new Date().getTime().toString().substring(0, 10))
    }
    
    ////////////////////////////////
    //
    // Refreshing the DIV TIMEDIV
    //
    ////////////////////////////////
    
    function refreshdiv_timediv(){
    
    // Customise those settings
    
    var seconds = 5;
    var divid = "timediv";
    var url = "boo.php";
    
    // Create xmlHttp
    
    var xmlHttp_one = AJAX();
    
    // No cache
    
    var timestamp = fetch_unix_timestamp();
    var nocacheurl = url+"?t="+timestamp;
    
    // The code...
    
    xmlHttp_one.onreadystatechange=function(){
    if(xmlHttp_one.readyState==4){
    document.getElementById(divid).innerHTML=xmlHttp_one.responseText;
    setTimeout('refreshdiv_timediv()',seconds*1000);
    }
    }
    xmlHttp_one.open("GET",nocacheurl,true);
    xmlHttp_one.send(null);
    }
    
    // Start the refreshing process
    
    window.onload = function startrefresh(){
    setTimeout('refreshdiv_timediv()',seconds*1000);
    }
    
    ////////////////////////////////
    //
    // Refreshing the DIV TIMEINWASHINGTON
    //
    ////////////////////////////////
    
    function refreshdiv_timeinwashington(){
    
    // Customise those settings
    
    var seconds = 8;
    var divid = "timeinwashington";
    var url = "boo2.php";
    
    // Create xmlHttp
    
    var xmlHttp_two = AJAX();
    
    // No cache
    
    var timestamp = fetch_unix_timestamp();
    var nocacheurl = url+"?t="+timestamp;
    
    // The code...
    
    xmlHttp_two.onreadystatechange=function(){
    if(xmlHttp_two.readyState==4){
    document.getElementById(divid).innerHTML=xmlHttp_two.responseText;
    setTimeout('refreshdiv_timeinwashington()',seconds*1000);
    }
    }
    xmlHttp_two.open("GET",nocacheurl,true);
    xmlHttp_two.send(null);
    }
    
    // Start the refreshing process
    
    window.onload = function startrefresh(){
    setTimeout('refreshdiv_timeinwashington()',seconds*1000);
    }
    
    ////////////////////////////////
    //
    // Refreshing the DIV OTHERDIV
    //
    ////////////////////////////////
    
    function refreshdiv_otherdiv(){
    
    // Customise those settings
    
    var seconds = 10;
    var divid = "otherdiv";
    var url = "boo3.php";
    
    // Create xmlHttp
    
    var xmlHttp_three = AJAX();
    
    // No cache
    
    var timestamp = fetch_unix_timestamp();
    var nocacheurl = url+"?t="+timestamp;
    
    // The code...
    
    xmlHttp_three.onreadystatechange=function(){
    if(xmlHttp_three.readyState==4){
    document.getElementById(divid).innerHTML=xmlHttp_three.responseText;
    setTimeout('refreshdiv_otherdiv()',seconds*1000);
    }
    }
    xmlHttp_three.open("GET",nocacheurl,true);
    xmlHttp_three.send(null);
    }
    
    // Start the refreshing process
    
    var seconds;
    window.onload = function startrefresh(){
    setTimeout('refreshdiv_otherdiv()',seconds*1000);
    }
    


    index.html

    Nothing special to say here, the code is really self-explanatory.

    <html>
    
    <title>AJAX Multiple DIV Refresh</title>
    
    <head>
    <script src="ajax.js"></script>
    </head>
    
    <body>
    <b>This is the current GMT date and time
     (updates every 5 seconds):</b>
    
    <script type="text/javascript">
    refreshdiv_timediv();
    </script>
    <div name="timediv" id="timediv"></div>
    <b>... and this is the date and
     time in Washington DC [DST GMT -7] (updates every 8 seconds):</b>
    
    <script type="text/javascript">
    refreshdiv_timeinwashington();
    </script>
    <div name="timeinwashington" id="timeinwashington"></div>
    <b>Oh, and this is the current timestamp!
     (updates every 10 seconds):</b>
    
    <script type="text/javascript">
    refreshdiv_otherdiv();
    </script>
    <div name="otherdiv" id="otherdiv"></div>
    </body>
    
    </html>
    


    boo.php

    This and the other PHP files containing the scripts to be refreshed (namely boo.php, boo2.php and boo3.php) contain sample PHP code; this is the code used in the demo of this script. You may alter it or add new code to suit your needs.

    <?php 
    
    // Format time output
    
    $str = "It is %a on %b %d, %Y, %X - Time zone: %Z";
    
    // Echo results
    
    echo(gmstrftime($str,time())); 
    
    ?>
    


    boo2.php

    
    <?php 
    
    // Format time output
    
    $str = "It is %a on %b %d, %Y, %X - Time zone: PST";
    
    // Echo results
    
    echo(gmstrftime($str,time() - (3600*7))); 
    
    ?>
    


    boo3.php

    
    <?php 
    
    // Echo results
    
    echo time(); 
    
    ?>
    

    As you can see, it is fairly the same process than making a single DIV refresh, isn’t it? The difference: multiple XMLHttpRequest objects are created. Of course there might be other (better or worse) ways to do it;  but this one I’ve tested it and works to me – and should work to you too.

    You can see the demo again here.

    Finally let me repeat again that – especially when refreshing multiple DIVs – you should test the performance of the page with different refresh rates. Performance depends on the number of DIVs being refreshed, the number of users viewing the page (and therefore receiving the data), the scripts being periodically run, etc. Remember as well to be generous with the refresh time rates… :) Enjoy!

    NB: occasionally, the blog replaces some specific characters from posted source code. May the code provided not work, check if it is because of wrong syntax and notify me so I fix it. Thanks!

     

    27 responses to “Refreshing DIV content with AJAX (multiple DIVs)”

    1. Hello there,
      great article and thanks for this but what can we do if the DIV tag is in table rows printed by a loop. Every time loop runs, assigns a unique id to DIV tag.
      how can we pass that unique id to javascript function and get ajax.js to accomodate this.

      The output would be many rows with different values e.g. time in unique DIV tags.

      I would really appreciate your help.
      Ahmed

    2. Hello Ahmed,

      As in your case you cannot rely in element ID’s, I suggest you try the GetElementsByName() method instead.

      See its description here.

      You will have to make some minor changes to the ajax.js code above to get this to work:

      - Replace lines 20, 76, 132 with:
      var divname = “nameofdiv”;

      (and obviously write name of each DIV as appropriate; each DIV a different name)

      - Replace lines 51, 107, 163 with:
      document.getElementsByName(divname).innerHTML=xmlHttp.responseText;

      I think that’s all. Give it a try; let me know if it works.

      Regards

    3. Updated 06-03-2009; improved the code by removing the unnecessary AJAX functions and create multiple XMLHttpRequest objects instead.

    4. Mate, nice script. and great job. appreciate it too for posting it. Just quick one, im having trouble making it work in IE7. even tries it with Msxml2.XMLHTTP.7.0
      Do you know anytoher way of making it work in all browsers?

    5. Hello All,

      This code doesn’t work in IE. Help me, please…

      Nomad

    6. Hello guys,

      Thanks for the feedback and sorry for the inconvenience… the old code seemed not to work in my IE7 either, but now it does.

      Did a minor fix to the code and posted the updated code above.

      Please try with IE7 the demo now to confirm the code update works.
      http://www.aleixcortadellas.com/demos/ajaxdivrefresh2/index.html

      If you already use it in your website, simply replace the AJAX.JS code with the one above. ;) I’d be thankful that you confirm it works in your projects now…

      Regards

    7. hey Aleix, its working perfect with IE7 now.
      ive been trying to pass the url to the function, and thats where im having trouble. passing the url by:

      view_job(”view_job.php?event=’.$jid.’&subid=’.$subid.’”);

      and in ajax:

      var url2 = “”;
      function view_job(temp){

      // Customise those settings
      var seconds = 8;
      var divid = “tab02″;
      url2 = temp;

      // Create xmlHttp
      var xmlHttp_two = AJAX();

      // No cache
      var timestamp = fetch_unix_timestamp();
      var nocacheurl = url2+”&t=”+timestamp;

      // The code…
      xmlHttp_two.onreadystatechange=function(){
      if(xmlHttp_two.readyState==4){
      document.getElementById(divid).innerHTML=xmlHttp_two.responseText;
      setTimeout(’view_job(url2)’,seconds*1000);
      }
      }
      xmlHttp_two.open(”GET”,nocacheurl,true);
      xmlHttp_two.send(null);
      }

      // Start the refreshing process
      window.onload = function startrefresh(){
      setTimeout(’view_job(url2)’,seconds*1000);
      }

      thats not working in IE but works perfectly in firefox.
      any ideas?

    8. okay i got it now.
      var formvar = “”;
      function view_job(temp){

      // Customise those settings
      var seconds = 8;
      var divid = “tab02″;
      var url = “view_job.php”;
      formvar = temp;

      // Create xmlHttp
      var xmlHttp_two = AJAX();

      // No cache
      var timestamp = fetch_unix_timestamp();
      var nocacheurl = url+”?t=”+timestamp+”&”+formvar;

      // The code…
      xmlHttp_two.onreadystatechange=function(){
      if(xmlHttp_two.readyState==4){
      document.getElementById(divid).innerHTML=xmlHttp_two.responseText;
      setTimeout(’view_job(formvar)’,seconds*1000);
      }
      }
      xmlHttp_two.open(”GET”,nocacheurl,true);
      xmlHttp_two.send(null);
      }

      // Start the refreshing process
      window.onload = function startrefresh(){
      setTimeout(’view_job(formvar)’,seconds*1000);
      }

    9. Hi there,

      Glad you found the solution to the problem :)
      if you have any more questions just let me know.

      Aleix

    10. Hi Aleix, now am trying to make the js load everytime the ajax is loaded. My javascript is not working for the loaded contents.

      So, am trying to work that out. Do you have any suggestions?

    11. You mean the view_job.php page has JS in it and it is not being parsed? Of course, the page is run with PHP server-side and therefore only the parsed PHP is returned in the XMLHTTP request. JS is client-side, and therefore it doesn’t run because the PHP page is processed server-side (sorry that my words are so redundant…). Most things you might be wanting to achieve with JS can be achieved with PHP too, so try turning that JS code into PHP.

      Another thing is, if you want to return JS code from view_job.php to the page which has the DIV where AJAX retrieves content. Depending on what this code is, you might consider using the eval() function
      http://www.w3schools.com/jsref/jsref_eval.asp

      This is a small example:

      1. Create a PHP file to retrieve with the following test code:

      < ?php
      echo 'alert(\'hello\')';
      ?>

      2. Change the innerhtml line of ajax.js to

      document.getElementById(divid).innerHTML=eval(xmlHttp.responseText);

      3. Customize the variable to retrieve the page you created in step one, and try if it works. If it does (to me, yes) a JS popup should appear in the main page, even though the JS code for it was in the PHP page.

      Give it a try ;)

    12. hi aleix, ill try that. Actually am using jquery tablesorter function in the index.php file. So now the tablesorter only works for the first time, and once the content is being reloaded by ajax, it doesnt work anymore. am trying using livequery, but its not too helpfull either.

    13. Best luck with your project; I’m afraid I won’t be able to help you with JQuery issues, as I don’t use frameworks for AJAX (only Mootools for FX like accordion menus and so on…) therefore I’m not familiarised with the way they work.

      Regards

    14. thats fine mate. Thanks for your help so far anyway. Ill try to resolve it somehow. Ill always end-up resolving it.

      thankx

    15. hi there, i have tried to modify your code to accomidate my needs of it – i have a shoutcast stream and have made a simple php parse script to pluck out the figures of listeners and so on, id like for ajax to refresh just the figures and leave the rest of the page alone, any ideas around this ?

    16. Hello,

      I am not sure what the problem is; it sounds to me like you don’t want the whole page to refresh, but this can’t be the problem because this code just refreshes the innerhtml of specific DIVs. If you could please detail a bit more, so I understand what the problem is exactly… :)

      Thanks

    17. HI,
      can anyone tell me how to refresh div tag that is updated with ajax.I want to view the new div contents on view page source which i cannot see now.

    18. Hello,

      the content div was upadated with ajax

      this is ajax loaded div content

      but when i view the contents in view page source the div still remains same instead it should replace with above code.also please tell me ajax has any effect on web crawler

    19. Hi, Aleix

      Do you have any idea why IE8 keeps saying ’seconds’ is undefined. I have your code working fine, but would like to get rid of the error if possible.

      http://www.edwardbrett.com/test.html

      Thanks,
      Edward

    20. Hello Edward,

      Try adding the following:

      var seconds;

      in the line just before

      window.onload = function startrefresh(){

      Kind regards

    21. cool stuff! bookmarked! :)

    22. Thanks Aleix that was it!

    23. Hello,

      I want to pass this PHP variable $destFile from index.html to foo.php so that i can then use that variable inside foo.php.

      I am able to do this with php include, but not sure how to do this here.

      great code, and will be the best if i can get this figured out!

    24. oh ..its really great tutorial in DIV with ajax.
      thanks dude …..

    25. Nice code Aleix!
      I want to use your code to load only a specific div from the boo pages.
      My boo pages in my case will be complete php pages with header, menus, sidebars, etc; and I cannot load all that stuff because it would screw the layout of the main page.
      I’m planning to use your code to display news from other pages of my website. Not the entire news, only the first two paragraphs for each one of them with a ‘read more’ link to go to the complete news.
      Any help you can provide will be much aprreciated.

    26. Hello Rainier,

      I’ve thought of your issue – new to me -, and I could just think of one approach. I am not sure it’s the only one neither the easiest one, but I believe it could do the job.

      The approach is to import the whole boo.php file, but just dump into the target DIV of the main page the information contained in the origin DIV of the boo.php file. The filtering could be done with JavaScript, by using string functions as found here:
      http://www.w3schools.com/jsref/jsref_obj_string.asp

      The functions you could use for that are two:

      Search()
      Slice()

      Assuming the string is the whole imported boo.php code; with search() you find the start and ending numbers for slicing the string into pieces. You want here to start slicing where the following is found in the string: < div id = "origin_div" > and end the slice where the corresponding < / div > is found. Use the search() to find where those points are, and then assign those values to the slice() function. The sliced part should be the wished content and therefore the only part of the whole string to be displayed in the target DIV.

      I’m not sure if I explained it clearly enough, I hope yes, as I unfortunately don’t have the time to code this. Let me know if you get it to work, however ;-)

      Greetings

      N.B.: If I’m not wrong, I think you cannot import external pages content using the AJAX method, just those present in your server (security grounds).

    27. Thanks for publishing this resource. Saved me a lot of grief! Works perfectly! :)

    Leave a reply