Ajax XMLHttpRequest
The function below creates a XMLHttpRequest object; sends the request to the server and finaly receives the data.
Variables:
target: the ID of the HTML element where the rensponse message is displayed.
method: POST or GET.
url: server side script that receives the request.
param: the data.
slideIt: (milliseconds) determines the duration of the rensponse message occurence.
loadImage: If is not zero (0) load an image during the request proccess; its value is the ID of the HTML element where the image appears.
shoWait: displays a message during the request proccess; if its value is zero (0) nothing happens else the value is the message.
Code:
function Ajaxify(target, method, url, param, slideIt, loadImage, shoWait)
{
if(shoWait != 0)
{
document.getElementById(target).innerHTML = shoWait;
}
if(loadImage != 0)
{
document.getElementById(loadImage).innerHTML = '<img src="my_image.gif"/>';
}
//Find Correct XMLHTTP Connection
if(!window.XMLHttpRequest)
{
window.XMLHttpRequest = function()
{
var types = [
'Microsoft.XMLHTTP',
'MSXML2.XMLHTTP.5.0',
'MSXML2.XMLHTTP.4.0',
'MSXML2.XMLHTTP.3.0',
'MSXML2.XMLHTTP'
];
for(var i = 0; i < types.length; i++)
{
try
{
return new ActiveXObject(types[i]);
}
catch(e)
{}
}
return false;
};
}
//Create Socket
NewRequest = new XMLHttpRequest();
NewRequest.open(method, url, true);
NewRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
NewRequest.send(param);
NewRequest.onreadystatechange = function()
{
if (NewRequest.readyState == 4)
{
if (NewRequest.status == 200)
{
if(loadImage != 0)
{
document.getElementById(loadImage).innerHTML = '';
}
if(slideIt != 0)
{
var comment = new Fx.Slide(target, {duration: slideIt}).hide();
}
document.getElementById(target).innerHTML = unescape(NewRequest.responseText);
if(slideIt != 0)
{
comment.toggle();
}
}
else
{
document.getElementById(target).innerHTML = 'Ajax Error';
}
}
}; }
Leave a Reply
You must be logged in to post a comment.
