Tuesday, May 18, 2010

Generic Ajax Request

Here's a generic way to create an AJAX request (AJAX code below being JavaScript):

function createRequest(){

request=null;

try{
request = new XMLHttpRequest();
}catch(tryMS){
try{
request = new ActiveXObject("Mxsml2.XMLHTTP");
}catch(otherMS){
try{
request = new ActiveXObject("Microsoft.XMLHTTP");
}catch(failed){
request=null;
}
}
}

return request;
}


And a sample function that uses it:

function getPage(){

try{

request = createRequest();

var url ="/some/page.html";

request.open("GET", url, true);

request.onreadystatechange=displayPage;

request.send(null);

}catch(e){
alert(e)
}

}


function displayPage(){
try{
if (request.readyState== 4){
obj = document.getElementById('someDiv');
if (request.status== 200){
obj.innerHTML = request.responseText;
}
}
}catch(e){
alert(e + request.responseText);
}
}

Next on the reading list:

Ajax Security