XHR get request URL in onreadystatechange - javascript

Is there any way to get the URL of request in the "onreadystatechange" method?
I want to run multiple XHR requests and know which of them comes back:
xhr.open("GET", "https://" + url[i], true);
xhr.onreadystatechange = function(url) {
console.log("Recieved data from " + url);
};
xhr.send();

There are 3 simple ways of doing this.
1: use closures as already described
2: set an attribute on the xhr object that you can reference later like so:
xhr._url = url[i];
xhr.onreadystatechange = function(readystateEvent) {
//'this' is the xhr object
console.log("Recieved data from " + this._url);
};
xhr.open("GET", "https://" + url[i], true);
3: Curry the data you need into your callbacks (my preferred solution)
Function.prototype.curry = function curry() {
var fn = this, args = Array.prototype.slice.call(arguments);
return function curryed() {
return fn.apply(this, args.concat(Array.prototype.slice.call(arguments)));
};
};
function onReadystateChange(url, readystateEvent) {
console.log("Recieved data from " + url);
};
xhr.onreadystatechange = onReadystateChange.curry(url[i]);
xhr.open("GET", "https://" + url[i], true);

Use closures.
function doRequest(url) {
// create the request here
var requestUrl = "https://" + url;
xhr.open("GET", requestUrl, true);
xhr.onreadystatechange = function() {
// the callback still has access to requestUrl
console.log("Recieved data from " + requestUrl);
};
xhr.send();
}

Related

Convert arrow function, old question closed without aid, 'duplicates' were not useful

I've got a bit of a code that works fine as an arrow function, but using wkhtmltopdf converting a webpage to an image, it's unable to read arrow functions. That said, I've tried numerous times to make this function without the arrow, but no success yet.
The 'related' answers do not answer my question. I simply can't get this function to return the same data when I remove the arrow for this async function.
Babel transpiler seems unable to do this, as well.
function getJSON(url, token) {
return new Promise((resolve, reject) => {
var xhr = new XMLHttpRequest();
xhr.open("GET", url, true);
if (token != null){
xhr.setRequestHeader("Authorization", "Bearer " + token);
}
xhr.responseType = "json";
xhr.onload = function() {
var status = xhr.status;
if (status === 200) {
resolve(xhr.response);
}
else {
reject(xhr.status);
}
};
xhr.send();
});
}
Would you please try this:
function getJSON(url, token) {
return new Promise(function (resolve, reject) {
var xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
if (token != null) {
xhr.setRequestHeader('Authorization', 'Bearer ' + token);
}
xhr.responseType = 'json';
xhr.onload = function () {
var status = xhr.status;
if (status === 200) {
resolve(xhr.response);
} else {
reject(xhr.status);
}
};
xhr.send();
});
}

set new GET XMLHttpRequest() after an XML HttpRequest POST Request after onload Function with passing data

I'm currently trying to pass data ( Variable "x" from a POST XMLHttpRequest after an onload function to make another new GET XMLHttpRequest. Does anyone know how to solve this issue?
<script>
var xhr = new XMLHttpRequest();
xhr.open('POST', 'https://reporting.xxxxxxx.com/xxxx/reports', true);
xhr.onload = function () {
var x = JSON.parse(this.responseText);
x=x.taskId;
console.log("Response Text URL = " + x);
var xhr2 = new XMLHttpRequest();
xhr2.open('GET', x, true); // here i would like to use the data from variable "x" ....
xhr2.onload = function() {
}
xhr.send();
xhr2.send();
}
</script>

Passing URL variable with & from JS to PHP result in "&" omission

It is a bit difficult to find the proper title for this question for me, so maybe this example will clarify my issue.
I am making an ajax request to pass some variables from a JS to a PHP.
One of these variables is a URL with some options, namely
https://www.wondermap.it/cgi-bin/qgis_mapserv.fcgi?map=/home/ubuntu/qgis/projects/Demo_sci_WMS/demo_sci.qgs&SERVICE=WFS&VERSION=1.1.0&REQUEST=GetFeature&TYPENAME=impianti_risalita&
The PHP code is ignoring any options after the first & symbol, considering only this part
https://www.wondermap.it/cgi-bin/qgis_mapserv.fcgi?map=/home/ubuntu/qgis/projects/Demo_sci_WMS/demo_sci.qgs
The AJAX request to the PHP I am making at the moment looks like
https://localhost/shire/php/export_wfs.php?wfs_url=https://www.wondermap.it/cgi-bin/qgis_mapserv.fcgi?map=/home/ubuntu/qgis/projects/Demo_sci_WMS/demo_sci.qgs&SERVICE=WFS&VERSION=1.1.0&REQUEST=GetFeature&TYPENAME=impianti_risalita&format=ESRI%20Shapefile
being wfs_url and format the two parameters the PHP is supposed to process.
I think i am supposed to avoid placing the & symbols in the wfs_url parameter, but I have no idea what should i do instead. Any help would be appreciated.
EDIT
Here is the AJAX call:
var xhr;
if (window.XMLHttpRequest) xhr = new XMLHttpRequest(); // all browsers
else xhr = new ActiveXObject("Microsoft.XMLHTTP"); // for IE
// url is https://www.wondermap.it/cgi-bin/qgis_mapserv.fcgi?map=/home/ubuntu/qgis/projects/Demo_sci_WMS/demo_sci.qgs&SERVICE=WFS&VERSION=1.1.0&REQUEST=GetFeature&TYPENAME=impianti_risalita&
var php_url = window.location.protocol + "//" + window.location.hostname + '/shire/php/export_wfs.php?wfs_url=' + url + 'format=' + format_list[0];
xhr.open('GET', php_url, false);
xhr.onreadystatechange = function () {
if (xhr.readyState===4 && xhr.status===200) {
alert('Downloading...');
}
}
xhr.send();
return false;
});
Here's how to send it as POST request:
var php_url = '/shire/php/export_wfs.php';
var formData = new FormData();
formData.append('wfs_url', url);
formData.append('format', format_list[0]);
xhr.open('POST', php_url);
xhr.onreadystatechange = function () {
if (xhr.readyState===4 && xhr.status===200) {
alert('Server reply: ' + xhr.responseText);
}
}
xhr.send(formData);
try including this function (base64_encode):
var php_url = window.location.protocol + "//" + window.location.hostname + '/shire/php/export_wfs.php?wfs_url=' + base64_encode(url) + 'format=' + base64_encode(format_list[0]);
and on the server side:
$wfs_url = base64_decode($_GET['wfs_url']);
$format = base64_decode($_GET['format']);

Get XMLHttpRequest respond for every data received

I'm trying to make a script that will return a respond when data is received on the current page. (New Data Received > Log its content to the console)
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState == XMLHttpRequest.DONE) {
console.log(xhr.responseText);
}
}
xhr.prototype.open = (function(fopen){
return function(){
console.log("Data received.");
return fopen.apply(this,arguments);
}
})(XMLHttpRequest.prototype.open);
The above script is this script. (source)
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState == XMLHttpRequest.DONE) {
console.log(xhr.responseText);
}
}
xhr.open('GET', 'http://example.com', true);
xhr.send(null);
Combine with this script. (source)
XMLHttpRequest.prototype.open = (function(fopen){
return function(){
console.log("Data received.");
return fopen.apply(this,arguments);
}
})(XMLHttpRequest.prototype.open)
I wanted to know what I did wrong and how to make it work. Thanks!
You're assigning to the prototype property of your instantiated object, not to the prototype of XMLHttpRequest. You might want to change XMLHttpRequest.prototype.onreadystatechange instead:
Object.defineProperty(XMLHttpRequest.prototype, 'onreadystatechange', {
set: function(listenerFn) {
this.addEventListener('readystatechange', function(...handlerArgs) {
if (this.readyState == XMLHttpRequest.DONE) {
// Custom action:
// console.log(xhr.responseText);
console.log('Detected a new response');
// Run the previous callback that was passed in:
listenerFn.apply(this, handlerArgs);
}
});
}
});
const xhr = new XMLHttpRequest();
xhr.open('GET', 'https://stacksnippets.net');
xhr.onreadystatechange = () => console.log('handler running');
xhr.send();
This isn't completely in line with the spec of course, this is just an example monkeypatch one might start with. (Mutating the built-in objects like XMLHttpRequest.prototype is bad practice, though - consider avoiding it if possible)
This will log all xhr request
XMLHttpRequest.prototype.send = (function(fsend){
return function(){
this.addEventListener('load', function(){
console.log("Data received.", this.response)
}, {once: true})
return fsend.apply(this, arguments);
}
})(XMLHttpRequest.prototype.send);
xhr = new XMLHttpRequest
xhr.open('GET', 'https://httpbin.org/get')
xhr.send()

function to return string in javascript

I am trying to call an ajax request to my server for json data using a function. If I console out the resp variable inside the ajax function it will show the data successfully. If i try to set the ajax function to a variable, and then console that variable it returns undefined. Any ideas who to make the function request the data and then set ti to a variable to be consoled?
function jsonData(URL) {
var xhr = new XMLHttpRequest();
xhr.open("GET", URL, true);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
var resp = JSON.parse(xhr.responseText);
return resp;
}
}
xhr.send();
}
jsonString = jsonData(http://mywebsite.com/test.php?data=test);
console.log(jsonString);
This is actually pretty simple.. Change your call to by synchronous..
xhr.open("GET", URL, false);
That being said this will block the browser until the operation has been completed and if you can use a callback instead it would likely be preferred.
function jsonData(URL, cb) {
var xhr = new XMLHttpRequest();
xhr.open("GET", URL, true);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
var resp = JSON.parse(xhr.responseText);
cb(resp);
}
}
xhr.send();
}
jsonData("http://mywebsite.com/test.php?data=test"
, function(data) { console.log(data); });

Categories

Resources