Sunday 4 November 2012

ajax calling multiple function with same xmlhttprequest object

If you are not familiar to ajax then check out ajax introduction click here 

As explained in previous post we need to create XMLHttpRequest object for sending request.

If you have morethan one AJAX call on one page then you should reuse them. You should create one standard ajax XMLHttpRequest object and that should be called times.

And don't worry if you use morethan one XHR (XMLHttpRequest) object on same page. It won't create any problem. But better coding practice it is suggested to reduce code.

<script>
var xmlhttp;
function ajaxFunction(url,myReadyStateFunc)
{
   if (window.XMLHttpRequest)
   {
      // For IE7+, Firefox, Chrome, Opera, Safari
      xmlhttp=new XMLHttpRequest();
   }
   else
   {
      // For IE5, IE6
      xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
   }
   xmlhttp.onreadystatechange= myReadyStateFunc;
   xmlhttp.open("GET",url,true);
   xmlhttp.send();
}

function myFunction()
{
    ajaxFunction("ajaxTest.txt",function()
    {
        if (xmlhttp.readyState==4 && xmlhttp.status==200)
        {
             document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
        }
    });
}
function myFunction1()
{
   ajaxFunction("ajaxTest.txt",function()
   {
       if (xmlhttp.readyState==4 && xmlhttp.status==200)
       {
            document.getElementById("myDiv1").innerHTML=xmlhttp.responseText;
        }
    });
}
</script>

<body>
<div id="myDiv"><h2>Default Text Click Button to change Text</h2></div>
<button type="button" onclick="myFunction()">Change Content</button> 

<div id="myDiv1"><h2>Default text Click Button to change Text</h2></div>
<button type="button" onclick="myFunction1()">Change Content</button>
</body>

Here myFunction() and myFunction1() are two different functions.
While ajaxFunction()is ajax function which is creating request and response.

First we are calling myFunction() function in which we are calling ajaxFunction() with two arguments - url for server communication and in second argument we are passing whole onreadystatechange() function, means on response what we are gonna do.

both function having onreadystatechange function which are to update myDiv and myDiv1. myDiv and myDiv1 are id of div. which will be replaced by respective AJAX call response.

No comments:

Post a Comment