Javascript & Ajax

Performing GET and POST requests using Ajax

Let’s see a simple javascript method that uses XMLHttpRequest API and ActiveXObject(IE) to make HTTP GET and POST requests.

function LoadDataInDiv(page, params, divid, method) {
  var http_request = false;
  if (window.XMLHttpRequest) {
	  http_request = new XMLHttpRequest();
    if (http_request.overrideMimeType) {
      http_request.overrideMimeType('text/html');
    }
  }
  else if (window.ActiveXObject) {
    try {
    	http_request = new ActiveXObject("Msxml2.XMLHTTP");
    } catch (e) {
      try {
        http_request = new ActiveXObject("Microsoft.XMLHTTP");
      } catch (e) {}
    }
  }
 
  if (!http_request) {
    return false;
  }
 
  http_request.onreadystatechange=function(){
	  if (http_request.readyState==4){
	   if (http_request.status==200 || window.location.href.indexOf("http")==-1){
	    document.getElementById(divid).innerHTML=http_request.responseText;
	   }
	  }
	 }
  //make GET request
  if(method=="GET"){
	 http_request.open(method, page+"?"+params, true);
	 http_request.send(null);
  }
  //make POST request
  else if(method=="POST"){
	 http_request.open("POST", page, true);
	 http_request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	 http_request.send(params);
  }
}

An example on how to use this method:

<button onclick="LoadDataInDiv('mypage.php', 'id=2&type=preview', 'test', 'GET');">click me</button>
 
<div id="test"></div>