Ajax Callback

I wrote a simple javascript ajax object a few moinths ago. The script here I made a little improvement to make it more convenient to use. The response text is handled within the callback function.

ajax Object with callback

Here's the entire codes. As before, if you only use post or get request you can delete the code of the other request to make the code more concise.

var ajax = { 
    
    postRequest: function(url, vars, values, handler) {
        var params = this.paras(vars,values);
        xmlhttp = this.getxmlhttpObj();
        xmlhttp.open("POST", url, true);
        xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        xmlhttp.setRequestHeader("Content-length", params.length);
        xmlhttp.setRequestHeader("Connection", "close");   
        
        xmlhttp.onreadystatechange = function() {
            if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
                    var data = xmlhttp.responseText;
                    if(data != null) 
                    handler(data);
            }
        }
        xmlhttp.send(params);
    },

    getRequest: function(url, vars, values, handler) {
        xmlhttp = this.getxmlhttpObj();
        url = url+"?"+this.paras(vars,values);
        xmlhttp.open("GET", url,true);
        
        xmlhttp.onreadystatechange = function() {
            if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
                    var data = xmlhttp.responseText;
                    if(data != null) 
                    handler(data);
            }
        }
        xmlhttp.send(null);
    },

    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 text data can be used in the callback function.

function foo() {
    var url = "../phpscript/test_get.php";
    ajax.getRequest(url,["p"], ["Mary"], function(data){
        alert(data);
    });
}

PHP Page

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

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