How to get HTTP headers form data - javascript

I am using an external payment site to redirect to my own website. I need some of the form data in the headers and I cannot figure out how to grab the data. Here is a screenshot:
Inside the headers tab, I want to get the information from the Form Data tab.
The code below is what I was able to find regarding getting headers, but the problem is it only grabs the code from the ResponseHeaders tab. And req does not have any function to get the form data.
var req = new XMLHttpRequest();
req.open('GET', document.location, false);
req.send(null);
var headers = req.getAllResponseHeaders().toLowerCase();
I want to see if there is a function where I can do something like
var formData = req.getFormData().toLowerCase();

There is no way, in browser-side JavaScript, to get information about the request that was used to get the current page from the server.
If you want access to it, you'll need to use server side code to dynamically generate the page and include it in the DOM (perhaps as a JavaScript object in a <script> element, or as a data-* attribute, or in <meta> elements) and then use JS to extract it from the DOM.

The mozilla site provides an example (https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/getResponseHeader)
var client = new XMLHttpRequest();
client.open("GET", "unicorns-are-teh-awesome.txt", true);
client.send();
client.onreadystatechange = function() {
if(this.readyState == this.HEADERS_RECEIVED) {
console.log(client.getResponseHeader("Content-Type"));
}
}
But fetch is nicer (see https://developer.mozilla.org/en-US/docs/Web/API/Response/headers):
fetch(myRequest).then(function(response) {
console.log(response.headers); // returns a Headers{} object
response.blob().then(function(myBlob) {
var objectURL = URL.createObjectURL(myBlob);
myImage.src = objectURL;
});
});

Related

getting a hidden element and sending it to a different URL

I'm doing a challenge which requires me to get an ID of element (from the source code - its hidden there - in my example called token), and then re-send it to another page with POST request included. however the code will not keep going to the 2nd request(the POST one) some why and it won't throw an error on the console.
var req = new XMLHttpRequest();
req.onload = handleResponse;
req.open('get','/example/ex1',true); // will open the page /example/ex1
req.send(); // sends the request
function handleResponse() {
var token = this.responseText.match(/name="token" value="(\w+)"/)[1];
var changeReq = new XMLHttpRequest();
changeReq.open('post', '/example/ex2', true);
changeReq.send('token='+token+'&user=admin')
};
I appreciate your help.
check the network tab. make sure the target URL is called.

How to attach form data in url which is used by Ajax?

So, I came across this problem whereby I want to access the data of a website, but it works only after the user interacts with the website. So, after selecting the date, it sends the ajax request to its site with a url, but also the form data. Here is the screenshot taken in Google Chrome.
And the problem is, the url doesn't work without specifying the cdate parameter as highlighted in the picture. Is there any way, I can send the form data (cdate in our case) to the specified url, so that it doesn't lead me to the error? Any way to do that?
In order to send form data progmatically, you can use the FormData object like so:
var formData = new FormData();
formData.append("cdate", "09/14/2019");
var request = new XMLHttpRequest();
request.open("POST", "http://example.com");
request.send(formData);
request.onLoad => (e) {
// Do something with request.response
};
Adapted from https://developer.mozilla.org/en-US/docs/Web/API/FormData/Using_FormData_Objects

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);

Access parameters in a XMLHttpRequest Google Apps Script

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);

XMLHttpRequest HTTP Headers

I'm trying to make a little script to rehost pictures on the web on imgur.
This is called Image Sideloading and you only need to point the browser to http://api.imgur.com/2/upload?url= + Picture's Url
It doesn't return any XML or JSON response so I can't parse it to get the img URL.
But I think I found a way to do this but can't get it to work properly. Here's the code I'm using.
$(document).ready(function() {
$("#button").click(function() {
str = $("input").val().toString();
link = "http://api.imgur.com/2/upload?url=" + str;
var xhr = new XMLHttpRequest();
xhr.open("GET", link);
xhr.send();
var headers = xhr.getAllResponseHeaders().toLowerCase;
alert(headers);
});
});
And looking at Google Chrome's console these are the results generated after the script runs.
I am not allowed to post images yet so here's a link to the results: http://i.imgur.com/xCyIP.png
I need to somehow access that 4th response header because even though this method doesn't return any parsable XML or JSON response that link is the uploaded img's URL which is all I need.
So is there a way to access that info? Why is it cancelled?
Thanks everyone!
Well, the API must return something, else it is useless.
Actually, http://api.imgur.com/examples advises you to do something like:
var xhr = new XMLHttpRequest();
xhr.open("GET", link);
xhr.onload = function() {
var url = JSON.parse(xhr.responseText).upload.links.imgur_page;
alert(url);
}
xhr.send();
Edit. OK, I got it. Normally, the above code should work, but I think imgur is facing a problem. I will report the bug.
While the bug is still there, here is a dirty solution to serve your needs:
var xhr = new XMLHttpRequest();
xhr.open("GET", link);
xhr.onload = function() {
html = xhr.responseText;
alert(html.substr(html.indexOf('http://i.imgur.com/') + 19, 5));
}
xhr.send();
You code wasn't working because you weren't waiting for the answer. You have to catch it through a callback function.
Edit. The above code only works locally. As you're using jQuery, let me introduce the shortcut $.post:
$(document).ready(function() {
$("#button").click(function() {
$.post('http://api.imgur.com/2/upload.json', {
key: 'ec575de603b936e54c2b4a9f232d537e',
image: $("input").val().toString()
}, function(data) {
alert(data.upload.image.hash);
});
});
});​
http://jsfiddle.net/Le_Sphinx/rEfdS/

Categories