Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass Parameters To XMLHttpRequest Object

Tags:

javascript

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;

}
like image 769
Nick LaMarca Avatar asked Oct 01 '12 15:10

Nick LaMarca


People also ask

How can request content type be set to XML via XMLHttpRequest?

setRequestHeader('Content-Type', 'application/json') ; is added 1 line above or below the Accept header, the method used changes to OPTIONS, the Accept header changes to "text/html,application/xhtml+xml,application/xml;q=0.9,/;q=0.8" and the Content-Type header disappears as if it wasn't seen.

What is the XMLHttpRequest object?

XMLHttpRequest (XHR) objects are used to interact with servers. You can retrieve data from a URL without having to do a full page refresh. This enables a Web page to update just part of a page without disrupting what the user is doing. XMLHttpRequest is used heavily in AJAX programming.


1 Answers

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);
like image 73
lolol Avatar answered Sep 29 '22 07:09

lolol