15

How can I pass parameters to the XMLHttpRequest Object?

function setGUID(aGUID) {

    var xhReq = new XMLHttpRequest();

    xhReq.open("POST", "ClientService.svc/REST/SetAGUID" , false);
    xhReq.send(null);
    var serverResponse = JSON.parse(xhReq.responseText);
    alert(serverResponse);
    return serverResponse;
}

I need to use javascript instead of jquery, in jquery I got it to work with this code, but cant seem to figure it out the straight javascript way..

function setGUID(aGUID) {

    var applicationData = null;

    $.ajax({
        type: "POST",
        url: "ClientService.svc/REST/SetAGUID",
        contentType: "application/json; charset=utf-8",
        data: JSON.stringify({ aGUID: aGUID }),
        dataType: "json",
        async: false,
        success: function (msg) {

            applicationData = msg;

        },
        error: function (xhr, status, error) { ); }
    });

    return applicationData;

}
Nick LaMarca
  • 7,512
  • 28
  • 86
  • 145
  • Possible duplicate of [Send POST data using XMLHttpRequest](https://stackoverflow.com/questions/9713058/send-post-data-using-xmlhttprequest) – Matthieu Aug 10 '18 at 04:44

3 Answers3

23

There's a lot of tutorials about "xmlhttprequest post" on the internet. I just copy one of then:

Take a look:

http://www.openjs.com/articles/ajax_xmlhttp_using_post.php

https://www.google.com/search?q=xmlhttprequest+post

var http = new XMLHttpRequest();
var url = "url";
var params = JSON.stringify({ appoverGUID: approverGUID });
http.open("POST", url, true);

http.setRequestHeader("Content-type", "application/json; charset=utf-8");
http.setRequestHeader("Content-length", params.length);
http.setRequestHeader("Connection", "close");

http.onreadystatechange = function() {
    if(http.readyState == 4 && http.status == 200) {
        alert(http.responseText);
    }
}
http.send(params);
lolol
  • 3,969
  • 3
  • 32
  • 48
  • whats http? a new XMLHttpRequest()? – Nick LaMarca Oct 01 '12 at 15:57
  • 3
    The following lines now throw an "unsafe header error": http.setRequestHeader("Content-length", params.length); http.setRequestHeader("Connection", "close"); I am trying to get this to work without those lines, but the parameters don't seem to be setting.. – galactikuh Dec 04 '16 at 20:10
0

Just remove these two lines (which are not allowed to set these headers):

http.setRequestHeader("Content-type", "application/json; charset=utf-8");
xmlHttp.setRequestHeader("Connection", "close");
0

This way works for me.

var data = new FormData();
data.append('parameter_1', 'value parameter 1');
data.append('parameter_2', 'value parameter 2');
...

var xhr = new XMLHttpRequest();
xhr.open('POST', 'URL', true);
xhr.onload = function () {
    console.log(this.responseText);
};
xhr.send(data);