Member Avatar for TechySafi
<html>
  <head>
    <title>An Ajax demo</title>

    <script language = "javascript">
      var XMLHttpRequestObject = false;

      if (window.XMLHttpRequest) {
        XMLHttpRequestObject = new XMLHttpRequest();
      } else if (window.ActiveXObject) {
        XMLHttpRequestObject = new
          ActiveXObject("Microsoft.XMLHTTP");
      }

      function getData(dataSource, divID)
      {
        if(XMLHttpRequestObject) {
          var obj = document.getElementById(divID);
          XMLHttpRequestObject.open("GET", dataSource);

          XMLHttpRequestObject.onreadystatechange = function()
          {
            if (XMLHttpRequestObject.readyState == 4 &&
              XMLHttpRequestObject.status == 200) {
                obj.innerHTML =
                  XMLHttpRequestObject.responseText;
            }
          }
            XMLHttpRequestObject.send(null);
          }
      }
    </script>
  </head>

  <body>

    <H1>An Ajax demo</H1>

    [B]<form>
      <input type = "button" value = "Fetch the message"
        onclick = "getData('data.php', 'targetDiv')">
    </form>
[/B]
    <div id="targetDiv">
      <p>The fetched message will appear here.</p>
    </div>

  </body>
</html>

I wan't to two things here,
1)Cancelling the onclick() event.
Ans: I can use windowonload event right? so user don't have to click again n again to update a particular div. rather it will update itself automatically.
2) setting a timeout event. so that the div updates itselft after a certain period of time.
How can I do that? where to call that event on this code?

actually I'm trying to develop a basic chat room. so periodically I have to refresh msg_show div silently.

Thanks

1. Yes, you can use window.onload:

window.onload=function(){
getData('data.php','targetDiv');
}

and for second:

//in function getData add this (calling the counter):
counter();
//and here's counter function:
function counter(){
setTimeout('getData()',1000); //1000 (miliseconds) = 1 second, calls getData() after every second
}

Hopefully everthing works!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.