Thursday, August 29, 2013

JavaScript AJAX Function


This is the function which is need to add in the javascirpt file or page.
function standardAjax(inputvar, url, divid1, AjaxThread) {
var str, arr1, arr2, final_string;
var http = new Array;
document.getElementById(divid1).style.display = 'block';
try
{ http[AjaxThread] = new XMLHttpRequest(); }
catch (e) {
try
{ http[AjaxThread] = new ActiveXObject("Msxml2.XMLHTTP"); }
catch (e) {
try
{ http[AjaxThread] = new ActiveXObject("Microsoft.XMLHTTP"); }
catch (e) {
alert("Your browser does not support AJAX!");
return false;
}
}
}
var params = inputvar;
http[AjaxThread].open("POST", url, true);
http[AjaxThread].setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http[AjaxThread].setRequestHeader("Content-length", params.length);
http[AjaxThread].setRequestHeader("Connection", "close");
http[AjaxThread].onreadystatechange = function() {//Call a function when the state changes.
if (http[AjaxThread].readyState == 4 && http[AjaxThread].status == 200) {
str = http[AjaxThread].responseText;

if (str == null)
document.getElementById(divid2).style.display = 'none';

var strScript = str.split('');
eval(strScript[0]); // to run any script called up from ajax page
}

}
}
http[AjaxThread].send(params);
}

Points to remember:
1) inputvar ---> here we have to pass the parameters that we want to post on the page.
2) url -----> url of the page which we need to call.
3) divid1 -----> id of the div where we want to show the data that return from the page.
4) AjaxThread -----> integer value 1 or 2.

Example:-

standardAjax('var1=10&var2=sachin', 'location of page it is in our solution', 'id of div', 2);