Waiting for get request response from JS does not work - javascript

In my javascript code I have:
function getThing(){
var url = "myhost/thing";
var x = new XMLHttpRequest();
x.open("GET", url, false);
x.onload = function (){
return x.responseText
}
x.send(null);
}
console.log(getThing())
And console log gives me undefined.
What am I doing wrong?

Your HTTP request is executed asynchronously, and getThing is not returning anything other than undefined. Instead, your onload handler is returning the requested value, which is not used.
Instead, you need to wait with logging until the call has returned:
function getThing(){
var url = "myhost/thing";
var x = new XMLHttpRequest();
x.open("GET", url);
x.onload = function (){
console.log(x.responseText);
}
x.send(null);
}
getThing();

Related

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>

Why the "Uncaught ReferenceError:" when making my HTTP request?

"use strict";
(function() {
var url = "http://api.openweathermap.org/data/2.5/weather?q=London,England";
var apiKey = "OMMITTED FOR PRIVACY REASONS"; // Replace "APIKEY" with your own API key; otherwise, your HTTP request will not work
var httpRequest;
makeRequest();
// create and send an XHR request
function makeRequest() {
httpRequest = new XMLHttpRequest();
httpRequest.onreadystatechange = responseMethod;
httpRequest.open('GET', url + '&appid=' + apiKey);
httpRequest.send();
}
// handle XHR response
function responseMethod() {
if (httpRequest.readyState === 4) {
console.log(httpRequest.responseText);
}
}
})();
See link below for a screenshot of the errors, but here's what I'm getting:
An Uncaught ReferenceError on line 12 where my onreadystatechange is.
I also get an error saying 'responseMethod' isn't defined at
makeRequest nor when I call it.
Also getting an error on the very last line for some reason.
Your code looks good. I just replaced your code with my api key and everything worked (see below).
Can you be more specific about the browser where you get an error?
I tried in the latest chrome and firefox and there is no problem.
"use strict";
(function() {
var url = "http://api.openweathermap.org/data/2.5/weather?q=London,England";
var apiKey = "4ff5002c91520701ec111b6082de9387"; // This key might expire soon.
var httpRequest;
makeRequest();
// create and send an XHR request
function makeRequest() {
httpRequest = new XMLHttpRequest();
httpRequest.onreadystatechange = responseMethod;
httpRequest.open('GET', url + '&appid=' + apiKey);
httpRequest.send();
}
// handle XHR response
function responseMethod() {
if (httpRequest.readyState === 4) {
console.log(httpRequest.responseText);
}
}
})();

Multiple http requests by same js file

i have a problem with my file js that call multiple http requests.
I have a button that call the function VisualizzaReport that is in my file visualizzaReport.js
Here is the function VisualizzaReport(select is the ID of the user)
function visualizzaReport(select){
reportUtente(select)
loadPianificazione(select)
}
Here the function reportUtente(select)
function reportUtente(select) {
var url = "../loadReportUtenteServlet?";
url += "type=perso_atti&value=" + select.value;
xmlhttp.onreadystatechange = handlerForReportUtente;
xmlhttp.open("GET", url);
xmlhttp.send("");
}
Here the function loadPianificazione(select)
function loadPianificazione(select) {
var url = "../loadPianificazione2Servlet?";
url += "type=pianificazioni&value=" + select.value;
xmlhttp.onreadystatechange = handlerForPianificazioneUtente;
xmlhttp.open("GET", url);
xmlhttp.send("");
}
my problem is that the function reportUtente is launched but has not effect because it seems that it is substitute by loadPianificazione function.
How can i call loadPianificazione only when reportUtente has finished his execution?
In your case I suggest you use either jQuery or AngularJs for this purposes.
jQuery example:
$.get('url1.com', function(){
$.get('url2.com');
})
You will request url2.com only when first request has finished.
You appear to be using a single, global xmlhttp variable.
Then you call two functions which do things with it. The second one will overwrite xmlhttp.onreadystatechange before the first request has finished so the second function you put there will be called for each request.
Don't do that. Create a new instance of XMLHttpRequest for each request, and keep it in a local scope so that it doesn't interfere with other instances.
function reportUtente(select) {
var url = "../loadReportUtenteServlet?";
url += "type=perso_atti&value=" + select.value;
var xmlhttp = new XMLHttpRequest(); // New instance here
xmlhttp.onreadystatechange = handlerForReportUtente;
xmlhttp.open("GET", url);
xmlhttp.send("");
}
You haven't shared handlerForReportUtente but it should look something like:
function handlerForReportUtente() {
alert(this.responseText); // Use `this` to get the right XHR object
}

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

Javascript function returns undefined

I have four functions that handle a certain part of my app for getting a photo url.
In the function handleGetPhotoResponse the alert has my url in it, everything looks like it should.
The problem is in the function handleGetUsersFurKidsResponse. the variable "fkimg" is undefined. Can anyone tell me where I went wrong?
To use this part of the app I make a call to "getUsersFurKids".
function handleGetPhotoResponse(responseText, size) {
var photoDetails = JSON.parse(responseText);
var thePhoto = photoDetails[size];
alert(thePhoto);
return thePhoto;
}
function getPhoto(id, size) {
var url = "url-removed"+id;
var request = new XMLHttpRequest();
//Send the proper header information along with the request
request.open("GET", url);
request.onload = function() {
if (request.status == 200) {
return handleGetPhotoResponse(request.responseText, size);
}
};
request.send(null);
}
// function to handle the response of getting a users fur kids
function handleGetUsersFurKidsResponse(responseText) {
var ul = document.getElementById("furKidList");
var furKids = JSON.parse(responseText);
for(var i = 0; i<furKids.length; i++){
var li = document.createElement("li");
var fkimg = getPhoto(furKids[i].ui_id, 'small');
li.innerHTML = "<a href=\"\"><img src=\""+fkimg+"\"> "+furKids[i].p_name;
ul.appendChild(li);
}
}
// function to get a users fur kids
function getUsersFurKids(id) {
// api url for getting fur kids
var url = "url-removed"+id;
var request = new XMLHttpRequest();
//Send the proper header information along with the request
request.open("GET", url);
request.onload = function() {
if (request.status == 200) {
handleGetUsersFurKidsResponse(request.responseText);
}
};
request.send(null);
}
// receive a callback---v
function getPhoto(furKid, size, callback) {
// ^---and the current furKid
// use the ui_id------------v
var url = "url-removed" + furKid.ui_id;
var request = new XMLHttpRequest();
request.open("GET", url);
request.onload = function() {
if (request.status == 200) {
// Invoke the callback, and pass it the result of handleGetPhotoResponse
callback(handleGetPhotoResponse(request.responseText, size), furKid.p_name);
// use the p_name-----------------------------------------^
}
};
request.send(null);
}
function handleGetUsersFurKidsResponse(responseText) {
var ul = document.getElementById("furKidList");
var furKids = JSON.parse(responseText);
for(var i = 0; i<furKids.length; i++){
// pass a callback-----------------v
getPhoto(furKids[i], 'small', function(fkimg, p_name) {
var li = document.createElement("li");
li.innerHTML = "<a href=\"\"><img src=\""+fkimg+"\"> "+ p_name;
ul.appendChild(li);
});
}
}
You don't seem to understand that getPhotos is an asynchronous function. The onload handler inside it is called sometime LATER long after the getPhoto function itself returns and is finished. As such, you CANNOT return a value from getPhoto that was retrieved in onload.
Instead, you have to put all code that needs to use the onload response from getPhoto inside of the onload handler itself (or called from inside the onload handler) because ONLY when the onload handler is called is that data known.
This is how asynchronous programming works in javsacript.
Add a callback to getPhoto and call that callback from inside the onload handler, passing it the img that you got from the async call. Then, and only then, can you use that img data.

Categories

Resources