A Simple Ajax Object

For my common use, I just send variables to server and get response data from the server. Here's a simple object which separates the process function from the core ajax object.

ajax Object

The tiny js object is just about 40 lines of code. It could handle both post and get requests.

var ajax = { 

    postRequest: function(url, vars, values, handler) {
        var params = this.paras(vars,values);
        this.xmlhttp = this.getxmlhttpObj();
        this.xmlhttp.open("POST", url, true);
        this.xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        this.xmlhttp.setRequestHeader("Content-length", params.length);
        this.xmlhttp.setRequestHeader("Connection", "close");   
        this.xmlhttp.onreadystatechange = handler;
        this.xmlhttp.send(params);

    },

    getRequest: function(url, vars, values, handler) {
        this.xmlhttp = this.getxmlhttpObj();
        url = url+"?"+this.paras(vars,values);
        this.xmlhttp.open("GET", url,true);
        this.xmlhttp.onreadystatechange= handler;
        this.xmlhttp.send(null);
    },

    getResponse: function() {
	    if(this.xmlhttp.readyState == 4 && this.xmlhttp.status == 200) {
            return this.xmlhttp.responseText;
	    }	  
    },

    paras: function(vars, values) {
    var par = vars[0]+"="+values[0];
    for(i=1;i<vars.length;i++)  {
          par += "&"+vars[i]+"="+values[i];
    }
    return par;
    },

    getxmlhttpObj: function (){

    return (window.XMLHttpRequest) ? new XMLHttpRequest() : ((window.ActiveXObject) ? new ActiveXObject("Microsoft.XMLHTTP") : null);

    }

}

Call A Request

Before sending the request, parameters and their values are pushed into vars and values arguments. The response data is retrieved in the callback function.

function foo() {
var url = "../phpscript/test_get.php";
ajax.getRequest(url,["p"], ["Mary"], display);
// get by post request in the same way
// ajax.postRequest(url, ["p"], ["Mary"], display);

function display() {

var a1 = ajax.getResponse();
if(a1 == null) return;
alert(a1);

}

}   

PHP Page

A simpe PHP page to test get request - test_get.php.

<?php
$p=$_GET["p"];
echo "Hi, glad to meet you, ".$p;
?>