In this article, I would like to give a quick demo of how to code a basic AJAX function.
Explanation
function ajaxfunction(arguments_if_any){
if (typeof XMLHttpRequest != "undefined"){
xmlHttp = new XMLHttpRequest();
}
else if (window.ActiveXObject){
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
if (xmlHttp == null){
alert ("Browser does not support XMLHTTP Request");
return false;
}
var url;
url = "/application-name/any-serverside-program";
url += "?name="+value;
xmlHttp.onreadystatechange = callback-function-name;
xmlHttp.open("GET", url, true);
xmlHttp.send(null);
return true;
}
function callback-function-name(){
if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete"){
/* Stuff to do */
document.getElementById('id').innerHTML = xmlHttp.responseText;
}
}
Explanation
- First the function 'ajaxfunction' is called during a particular event like clicking a div tag or others.
- It checks whether the browser is able to send and receive a XMLHttpRequest object through which asynchronous request and response is achieved.
- If the support is available, an asynchronous request is made to a server side script (php/JSP) and once the response is received a 'callbackfunction' is executed.
- The third parameter in the open() method, in this case true implies that async is turned ON.
- The send() method is useful if we are using POST method - we can send large information using it. Example:- xmlHttp.send("fname=Athi&lname=Ruban");
- To assign a stream of HTML from a server output to a div tag we use InnerHtml property.
No comments:
Post a Comment