Post request with JS without jQuery

  • “Vanilla” JavaScript (without jQuery)

    sendPost = function(url, data) {
        var xmlhttp = new XMLHttpRequest();
        var params = serialize(data);
    
        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.send(params);
    
        xmlhttp.onreadystatechange = function() {
            if (xmlhttp.readyState === 4 && xmlhttp.status === 200){
                console.log(xmlhttp.responseText);
            }
        };
    }
    
    serialize = function(obj, prefix) {
        var str = [];
        for(var p in obj) {
            var k = prefix ? prefix + "[" + p + "]" : p, v = obj[p];
            str.push(typeof v == "object" ?
                    serialize(v, k) :
                    encodeURIComponent(k) + "=" + encodeURIComponent(v));
        }
        return str.join("&");
    }
    
    sendPost("http://some/host", {login: 'me@abc.def', password: 'mypassword'});
    
  • Or just use curl:

    curl 'http://some/host' --data 'login=me%40abc.def&password=mypassword'
    
Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *