Access parameters in a XMLHttpRequest Google Apps Script - javascript

I am currently trying to access the parameters of a POST request using Google Apps Script. I can logger the params object using e.parameter though i cannot seem to access the keys of the object by by using e.parameter.name.
XMLHttpRequest
var http = new XMLHttpRequest();
var url = "myappURL";
var params = JSON.stringify({employeeStatus: "Active", name: "Henry"});
http.open("POST", url, true);
//Send the proper header information along with the request
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
//Call a function when the state changes.
http.onreadystatechange = function() {
// call back function
} // end callback
http.send(params);
Google Apps Script
function doPost(e) {
if (typeof e !== 'undefined') {
Logger.log(e.parameter.name); // does not work (undefined)
} // end if
} // end doPost

There are subtle quirks with the different ways data is posed via http. For instance I notice that you are using Content-type "application/x-www-form-urlencoded" when the usual header for json data is Content-Type: application/json.
I added a line that just returns the contents of the e variable so you can see what is returned.
I used curl to debug it with the following command.
curl -H "Content-Type: application/json" ---data "{status:123}" https://script.google.com/macros/s/AKfycbyJ38V-HpG7A-DxIBpik4HJ89fAtnCemCJ7ZXeFEL8KPEuGsR8/exec
The response I received was:
{"parameter":{},"contextPath":"","contentLength":12,"queryString":null,"parameters":{},"postData":{"length":12,"type":"application/json","contents":"{status:123}","name":"postData"}}
You can see that in my case the json was returned in the contents field rather than the parameters.
You could try this with your script to see what you get. You could also try changing the Content-Type.
After Further testing I think you would be better submitting your fields a form data rather than json. I have been able to get the paramer back by amending your javascript to:
var http = new XMLHttpRequest();
var url = "https://script.google.com/macros/s/AKfycbyJ38V-HpG7A-DxIBpik4HJ89fAtnCemCJ7ZXeFEL8KPEuGsR8/exec";
var params = "employeeStatus='Active'&name='Henry'";
http.open("POST", url, true);
//Send the proper header information along with the request
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
//Call a function when the state changes.
http.onreadystatechange = function() {
if (http.readyState==4) {
//alert the user that a response now exists in the responseTest property.
console.log(http.responseText);
// And to view in firebug
// console.log('xhr',xmlhttp)
}
} // end callback
http.send(params);

Related

How to use GET/POST methods to interact with minehutAPI/server

I have started with the minehut API, and after looking at the docs (see a copy here) it uses get and post.
As a newbie to javascript etc I dont know how it works.
Part 1 - Get Info
for example: I want to get info about a server, it says to use GET https://api.minehut.com/server/{server-id}
How would i get for example playercount from it so that i can give that info to my code and display it on my website.
Required headers: is also mentioned in the docs, what are these and how do i use them?
Part 2 - send info
Now say for example i want to run a command, the docs say to use POST /server/{Server ID}/send_command. It also mentions Required headers saying it needs
Content-Type,
Authorization and
x-session-id
how would i send a string so that it would use POST to run a command
What you need to send or receive data using GET/POST methods is XMLHttpRequest object.
var server_id = "EXAMPLE_ID";
var req = new XMLHttpRequest();
req.onreadystatechange = function(){
if(this.readyState == 4){
// Data sent back available in this.responseText
// For example:
var recData = this.responseText;
// further handling
}
}
req.open('GET', 'https://api.minehut.com/server/' + server_id, true);
req.send();
Or in case of POST request:
req.open('POST', 'https://api.minehut.com/server/' + server_id + '/send_command', true);
req.setRequestHeader("Content-Type", "pplication/x-www-form-urlencoded");
req.setRequestHeader("Authorization", "Basic " + btoa(user + ":" + pass));
req.setRequestHeader("HeaderNameExample", "ItsValueExample");
req.send('optionalVar=sentData&foo=bar&etc");
In some cases preflight request can be done (especially with custom request headers) and the request might fail. To avoid that you might try invoking the opening with user/password instead. For cross domain request Access-Controll request should be made which allows for cookies to be set.
req.open("GET", url, true, username, password);
req.open("POST", url, true, username, password);
req.withCredentials = true;

Post to and visit a URL in Javascript

I'm trying to:
Post a JSON object to a URL and visit it at the same time.
Set the content-type and accept headers
I'm working with an old source base (asp classic / vb). Ideally, if I can do this in javascript it would be wonderful!
Constructing the js call with headers and data is simple with XHR:
var xhr = new XMLHttpRequest();
var url = "url";
xhr.open("POST", url, true);
xhr.setRequestHeader("Content-Type", "application/json");
var data = JSON.stringify({JSON DATA});
xhr.send(data);
However this is an async call and I can't seem to find a way of making it actually visit the URL in the browser.
The alternative is to create an form and append it to a HTML entity before using javascript to submit it. This time is post the data to and visits to the URL.. however, I don't have control over the headers.
So back to my questions. Can I post to and visit a URL in Javascript?
Given that visiting an URL in the browser is a GET request, and you want to POST at the same time, NO you cannot.
Why do you need to post and visit?
You could post your data and in the callback (once the post request is done) load the the page.
No.
The closest you could come would be to:
Use Ajax to make the request
Use DOM to modify the current page with data from the response
Use the History API to update the URL in the address bar
Changing the server side code to expect regular form encoded data and then submitting a regular form would probably be the simplest approach to solving the problem.
You are using XHR, and if you want to manage it from javascript... Add onreadystatechange property to your xhr (this function will be fired when your server response), and in this function redirect using window.location.href
var xhr = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
// Here redirect, with params if you need to
window.location.href = "https://stackoverflow.com?name1=value1&name2=value2";
}
};
var url = "url";
xhr.open("POST", url, true);
xhr.setRequestHeader("Content-Type", "application/json");
var data = JSON.stringify({JSON DATA});
xhr.send(data);

obtain information from API javascript

I wanted to know if there was a way I can receive information from API through JavaScript. I'm currently trying to use the information from API from www.openweathermap.org but I'm not sure how I can do it with JS. I currently tried
var xhr = new XMLHttpRequest();
xhr.open("GET", "http://api.openweathermap.org/data/2.5/weather?
lat=38.892634199999996&lon=-77.0689154", false);
xhr.send();
console.log(xhr);
which responds and sends me information in JS Object format:
{ response: {"coord":{"lon":-77.04,"lat":38.9},"weather":[{"id":800,"main":"Clear",
"description":"sky is clear","icon":"01d"}],"base":"cmc stations","main":{
"temp":301.51,"pressure":1016,"humidity":51,"temp_min":299.15,"temp_max":304.15},
"wind":{"speed":2.6,"deg":360},"clouds":{"all":1},"dt":1436565479,
"sys":{"type":1,"id":1325,"message":0.008,"country":"US","sunrise":1436521925,
"sunset":1436574893},"id":4140963,"name":"Washington, D. C.","cod":200}\n',
responseText: '{"coord":{"lon":-77.04,"lat":38.9},"weather":[{"id":800,
"main":"Clear","description":"sky is clear","icon":"01d"}],"base":"cmc stations",
"main":{"temp":301.51,"pressure":1016,"humidity":51,"temp_min":299.15,
"temp_max":304.15},"wind":{"speed":2.6,"deg":360},"clouds":{"all":1},
"dt":1436565479,"sys":{"type":1,"id":1325,"message":0.008,"country":"US",
"sunrise":1436521925,"sunset":1436574893},"id":4140963,"name":"Washington, D. C.","cod":200} }
I tried console.log(xhr.response.coord) and console.log(xhr.responseText.coord) as an example and both comes out undefined. Do I need to do something else to print out the information?
I know you can use $.get(URL, function()) to receive the information via JQUERY but is there a way I can do it just JS?
You should parse the string as a JSON object. Like this:
var data = JSON.parse(xhr.response);
console.log(data.coord);
You are missing the response handler
var xhr = new XMLHttpRequest();
// when the async call finishes, we need to check what happened
xhr.onreadystatechange=function(){
// if it finished without errors
if (xhr.readyState==4 && xhr.status==200){
// we get the data
var data = JSON.parse(xhr.responseText);
// this should be your json
//console.log(data.response.coord);
document.getElementById('response').innerHTML = xhr.responseText;
}
};
// NOTE! for demo purposes I'm using another api query that does not require an api key, change this to your api url
xhr.open("GET", "http://api.openweathermap.org/data/2.5/weather?q=London,uk", false);
xhr.send();
<div id="response"></div>
Your response is in JSON so you need to parse it first.
Use JSON.parse(xhr.response) to parse the response.
Like this:
JSON.parse(xhr.response)["coord"]["lat"]
JSON.parse(xhr.response)["coord"]["lon"]

XHR in Chrome Extension with CI

I'm sending a POST from a chrome extension content script to a server I control. I setup the permissions in the manifest ok. Here is my XHR code. (I want to avoid jQuery for this). Its sending an empty responseText
var xhr = new XMLHttpRequest();
xhr.open("POST",'http://mysite.com/make',true);
xhr.onreadystatechange=function() {
if (xhr.readyState == 4) {
var res = JSON.parse(xhr.responseText);
console.log(res);
}
}
xhr.send({'textbox':data[0].user,'from':'extension'});
data[0].user is an object I got directly from the Twitter API
in my CI controller I have
$user = $this->input->get_post('textbox', TRUE);
$from = $this->input->get_post('from', TRUE);
$fullURL = 'http://www.google.com'; //example of a URL from code.
$json = $this->output->set_content_type('application/json');
$json->set_output(json_encode(array('URL' => $fullURL)));
The response text is empty
a jquery call on the other hand works fine
$.post("http://mysite.com/make", { 'textbox': data[0].user, 'from':'jquery' },
function(data) {
console.log(data);
});
Reason is simple, JQuery post method can accept JSON and then convert it to string and send to the server.
What you are trying to do is to directly send JSON here :
xhr.send({'textbox':data[0].user,'from':'extension'}) // Incorrect way
send method should either accept NULL or a string which is generally made up of QueryString Parameters like.
xhr.send("textbox="+ data[0].user + "&from=extension"); // Correct way
This will ensure that your data goes to the appropriate URL with textbox and from as post request parameters.
and queryString will be generated like textbox=username1234&from=extension in the packet's body unlike one goes in Get with the headers along side the URL.
jQuery's post method makes it simpler for you to format data you send using JSON and then internally it converts that to a queryString to send parameters.
You can't directly send Javascript object like that with an XHR object!
Also checkout this example:
http://beradrian.wordpress.com/2007/07/19/passing-post-parameters-with-ajax/

Need to post large amount of data using xmlHttprequest

I need to pass huge amount of data to server without page loading. I have this code:
var GlType = "<%=GlType %>";
var pageUrl = "SelectAccount.aspx?callback=true&AccountList=" +accountList +"&AnalysisDate="+analysisDate+"&GlType="+GlType;
if (window.XMLHttpRequest)
{
var xmlRequest = new XMLHttpRequest();
}
else
{
var xmlRequest = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlRequest.open("POST", pageUrl, true);
xmlRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xmlRequest.send(null);
I am have passed using query string its exceeded the maximum Length of query string. Help me on this..
Since you're already using the POST method, you can pass data in the body.
xmlRequest.send("Field1=abc&Field2=def");
You can retrieve the data on the server, e.g. in ASP.NET:
if (Page.Request.Form["Field1"] == "abc") ...
For GET method you can only use the query string for transferring data.
You're sending the request via post, but putting everything in the query string!
Instead, you should send the data as the body of the request (passed to the send method).

Categories