Saturday 22 March 2008

Writing ajax code and display the result of ajax in a div

Here a code for ajax request to server.

This code defines a function sendRequest(url,divId).
This function takes two arguments, first - the url to which ajax request is to be made. second - the divId in which the response is to be included.

<script>
var http = getHTTPObject();
function sendRequest(url,divId) {
SubmitRBData(url,divId);
}

function SubmitRBData(strUrl,divId) {
http.open("GET", strUrl, true);
http.onreadystatechange = function handleHttpResponse() {

if (http.readyState == 4) {
if (http.status == 200){
results = http.responseText;
document.getElementById(divId).innerHTML=results; // string response
}}};
http.send(null);
}

function getHTTPObject() {
var objXMLHttp=null;
if (window.XMLHttpRequest){
objXMLHttp=new XMLHttpRequest();
}
else if (window.ActiveXObject){
objXMLHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
return objXMLHttp;
}
</script>


To make a ajax call, simply include this javascript in your code and call the sendRequest method.

No comments: