Tuesday, March 15, 2011

Basic AJAX: Javascript


Below are sample on how to use basic AJAX on your web application/site.


function sendData(url, target, str) { 
var xmlhttp
    xmlhttp = GetXmlHttpObject();
    xmlhttp.onreadystatechange = function () {
        if (xmlhttp.readyState == 0) {
            document.getElementById(target).innerHTML = "Sending Request...";
        }
        if (xmlhttp.readyState == 1) {
            document.getElementById(target).innerHTML = "Loading Response...";
        }
        if (xmlhttp.readyState == 2) {
            document.getElementById(target).innerHTML = "Response Loaded...";
        }
        if (xmlhttp.readyState == 3) {
            document.getElementById(target).innerHTML = "Response Ready...";
        }
        if (xmlhttp.readyState == 4 && xmlhttp.status==200) {
  if (str.length==0) {
document.getElementById(target).innerHTML = xmlhttp.responseText;
  } else {
document.getElementById(target).innerHTML = str;
  }
        }
    }
    xmlhttp.open("GET", url, true);
    xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
    xmlhttp.send();


    function GetXmlHttpObject() {
        var xmlHttpObject = null;
        try {
            // Firefox, Opera 8.0+, Safari
            xmlHttpObject = new XMLHttpRequest();
        }
        catch (e) {
            // Internet Explorer
            try {
                xmlHttpObject = new ActiveXObject("Msxml2.XMLHTTP");
            }
            catch (e) {
                xmlHttpObject = new ActiveXObject("Microsoft.XMLHTTP");
            }
        }
        return xmlHttpObject;
    }
}

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...

Blog List