|
|
|
Have converted the the AJAX tutorial [click here] code into a javascript object.
To now make an AJAX call is now simplier.
Just insert the following code into your page [or preferabbly into a seperate .js file]
function AJAXCaller()
{
var m_objXMLHttp;
var m_urlAjax;
var m_fnName;
this.setUrlAjax = setUrlAjax;
this.setCallBackFunctionName = setCallBackFunctionName;
this.sendRequest = sendRequest;
function setCallBackFunctionName(sVal)
{
m_fnName = sVal;
}
function setUrlAjax(sVal)
{
m_urlAjax = sVal;
}
function createXMLHttpObject()
{
try
{
m_objXMLHttp = new XMLHttpRequest();
} catch (trymicrosoft) {
try
{
m_objXMLHttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (othermicrosoft) {
try {
m_objXMLHttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch (failed) {
m_objXMLHttp = false;
}
}
}
if (!m_objXMLHttp)
alert("Error initializing XMLHttpRequest");
}
function sendRequest()
{
createXMLHttpObject();
var stamp = new Date();
m_objXMLHttp.open("GET", m_urlAjax +"&time="+stamp, true);
m_objXMLHttp.onreadystatechange = stateChanged;
m_objXMLHttp.send(null);
}
function stateChanged()
{
if (m_objXMLHttp.readyState == 4 ||
m_objXMLHttp.readyState=="complete")
{
if (m_objXMLHttp.status == 200 ||
m_objXMLHttp.status ==0) {
eval(m_fnName+"(m_objXMLHttp.responseText)");
}else if (m_objXMLHttp.status == 404){
alert("URL does not exist.");
}else{
alert("Unknown error occurred" +
m_objXMLHttp.status + m_objXMLHttp.statusText);
}
}
}
}
Once done, to make an AJAX call simply do the following...
//Create Object
oAJAXCaller = new AJAXCaller();
//Set the url
oAJAXCaller.setUrlAjax("mypage.asp?id=1");
//Set the callback function
oAJAXCaller.setCallBackFunctionName("myFunction");
//Make request
oAJAXCaller.sendRequest();
and then create the call back function that will recieve the response from the AJAX call
function myFunction(responseText)
{
alert(responseText);
}
|
|
|
|
|
|