How can I use ajax twice on one page to call different php pages

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • whitep8
    New Member
    • Oct 2009
    • 65

    How can I use ajax twice on one page to call different php pages

    Hi All,

    Im hoping somebody could help me with this. Ajax is not my strongest point.

    On a page I have a requirement to call 2 different php pages using ajax. this code works fine, but if i add another is seems to conflift and im insure how.

    the calls are in different areas of the page.

    Code:
    <html>
    <head>
    <script type="text/javascript">
    function showHint(str)
    {
      if (window.XMLHttpRequest)
        xmlhttp = new XMLHttpRequest();
      else
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    
      xmlhttp.onreadystatechange = function()
      {
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
          document.getElementById("txtHint").innerHTML = xmlhttp.responseText;
      };
      xmlhttp.open("GET", "console4.php" + str, true);
      xmlhttp.send(null);
    }
    </script>
    </head>
    <body>
    <script type="text/javascript">showHint(this.value)</script>
    
    <p><span id="txtHint"></span></p> 
    </body>
    </html>
    
          <script type="text/javascript">
          function keepCalling() {
          showHint("");
          window.setTimeout("keepCalling()", 2000) ;// call the showHint every (2)000 second
          }
          keepCalling();
          </script>
  • whitep8
    New Member
    • Oct 2009
    • 65

    #2
    i have just tried renaming xmlhttp to xmlhttp2 but it didnt work.

    i have made a few small changes in that the second call is called show, rather than showhint, just so i can ensure each one is different

    Comment

    • dgreenhouse
      Recognized Expert Contributor
      • May 2008
      • 250

      #3
      Use the same Ajax call (generalize it) for the various page sections. When the function is called it will determine which script/page section is currently being operated on (possibly using a switch statement). You may want to use the setInterval() method versus the setTimeout() method. That way, your code doesn't have to keep calling the same function over and over again.

      Set some type of flag that is used by the call to determine which server script to call and the page section {element(s)} that require(s) updating.

      You could also use a factory method to instantiate multiple xhr objects, but some browsers have limited number of simultaneous xhr requests active.

      These are just some initial thoughts, but my belief is your code will have to be refactored to allow for what you want to accomplish.

      Comment

      Working...