This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
How do I promisify native XHR?
(6 answers)
Closed 3 years ago.
i have some problem with ordering my functions.
i have 2 function. Two of them to http requests.
what a scenario?
on first request i get some response and in this response i'm getting some string and set it to some variable.
on second request i'm adding this string to my request url.
but my second request working before then in first request response when i set my variable.
because of that i'm getting undefined value of my variable.
I understand this is sync, async problem but how i can resolve this issue ?
it's my variable which i will add end of the second request url.
var urlString = '';
this is my first request:
var requestone = new XMLHttpRequest();
requestone.onload = function () {
if (requestone.status >= 200 && requestone.status < 300) {
var data = requestone.response;
data = JSON.parse(data);
urlString = data.Key
} else {
console.log('fail')
}
};
requestone.open('GET', 'apiurl');
requestone.send();
this is my second request:
var requesttwo = new XMLHttpRequest();
requesttwo.onload = function () {
if (requesttwo.status >= 200 && requesttwo.status < 300) {
var data = requesttwo.response;
} else {
console.log('fail')
}
};
requesttwo.open('GET', 'apiurl' + urlString);
requesttwo.send();
You can do this in 2 ways, using promise, or integrate the second request inside the request1:
var requestone = new XMLHttpRequest();
requestone.onload = function () {
if (requestone.status >= 200 && requestone.status < 300) {
var data = requestone.response;
data = JSON.parse(data);
requesttwo.open('GET', 'apiurl' + data.Key);
requesttwo.send();
} else {
console.log('fail')
}
};
requestone.open('GET', 'apiurl');
requestone.send();
Related
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 6 months ago.
** Placing My actual JS snippet"
I have a small JS function in one JS file as below
function interest(customerRef) {
try {
var customerInterest = "";
var baseUrl="https://test/"
var url = baseUrl+customerRef
var username = "username";
var password = "password";
var request = new XMLHttpRequest();
request.open("GET", url);
request.setRequestHeader("Authorization", "Basic " + btoa(username+":"+password))
request.send()
request.onload=()=>
{
if(request.status==200)
{
var guestJson = JSON.parse(request.response);
var sessions = guestJson.sessions || [];
var interest = sessions.filter(session => session.events)
.flatMap(session => session.events)
.filter(event => event.type === "SEARCH")
.map(event => event.arbitraryData.interest)[0];
customerInterest = interest;
alert("---"+customerInterest);
}
else
{
console.log(`error ${request.status} ${request.statusText}`)
}
}
alert(customerInterest);
return customerInterest;
}
catch (error) {
console.error(error);
}
}
I am calling the above function in my HTML file as below
customerRef = "6a789727"
var interest1 = "";
interest1 = interest(customerRef);
console.log(interest1);
I am not getting any value in "console.log(interest1)" or "alert(customerInterest);" before the return. But i am getting the expected value in "alert("---"+customerInterest);"
No, you'll get an error, not just undefined.
Running
var test = "";
test = test()
console.log(test)
will yield an
Uncaught TypeError: test is not a function
at line 2, since you just defined test to be a string ("") instead of a function you could call.
Instead, try something like:
function greet() {
return "Hi";
}
var test = "";
test = greet();
console.log(test);
If you evaluate this in the console, this will print out
Hi
undefined
; the latter undefined comes from the return value of console.log();
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 9 months ago.
I am not used to asynchronous method so I would like to have your help. I have this ajax method that gets the data of my mysql tables. I need to retrieve this data to use it in my code.
Here is my code :
function ajaxRequest(type,url,callback,data=""){
let request = new XMLHttpRequest();
request.open(type, url);
request.onload = function () {
switch (request.status){
case 200:
case 201: //console.log(request.responseText);
callback(request.responseText);
break;
default: console.log(request.status);
}
};
request.send(data);
}
function setAvailableQuestions(){
ajaxRequest("GET","../controller.php?func=get_availableQuestion", (questions) => {
var allQuestions = JSON.parse(questions);
return allQuestions;
});
}
function getNewQuestion(){
var availableQuestions = setAvailableQuestions();
console.log(availableQuestions); //undefined
}
I read that you could solve it in two different ways, first one is to put ajax request asynchronous to false :
function setAvailableQuestions(){
var ajax = new XMLHttpRequest();
var asynchronous = false;
ajax.open("GET","../controller.php?func=get_availableQuestion", asynchronous);
ajax.send();
ajax.onreadystatechange = function(){
var allQuestions = JSON.parse(this.response);
return allQuestions;
}
}
function getNewQuestion(){
var availableQuestions = setAvailableQuestions();
console.log(availableQuestions); //undefined
}
But it still displays undefined
And the other method is to use .then or await for asynchronous methods but I don't know how to apply it to my first code.
Does anyone has an idea to help me ?
Try setting the "return" on setAvailableQuestions().
function setAvailableQuestions(){
var ajax = new XMLHttpRequest();
var asynchronous = false;
ajax.open("GET","../controller.php?func=get_availableQuestion", asynchronous);
ajax.send();
ajax.onreadystatechange = function(){
var allQuestions = JSON.parse(this.response);
return allQuestions;
}
return ajax.onreadystatechange;
}
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 10 months ago.
I'm trying to access the NHL API for a personal project. I was getting CORS request errors and found the below solution to access all the different sites (some worked prior, and some didn't).
I'm passing through a link and based one the outputs it seems to be accessing the data on the page and displaying it in both JSON and string format. The only problem is I can't return any of that data out of the function as an object or otherwise.
Last 2 logs show undefined, and the 2 within the function output the data I want. Am I missing something obvious or is there a deeper issue with the website access?
Thanks.
function getJSON(url){
let request = new XMLHttpRequest();
request.open('GET', url);
request.onload = function () {
// Begin accessing JSON data here
let data = JSON.parse(this.response);
if (request.status >= 200 && request.status < 400) {
//Start writing function here
console.log(data);
console.log(JSON.stringify(data));
let data2 = JSON.stringify(data)
return data2
} else {
console.log('error');
}
}
request.send();
}
let data1 = getJSON("https://statsapi.web.nhl.com/api/v1/people/8476459/stats?stats=statsSingleSeason&season=20212022")
console.log(data1);
console.log(JSON.stringify(data1));
You are doing asynchronous call, which means you return the value before the response even come back, that's why data1 is undefined
You can see this post for more information.
For your case, you can wrap the request with Promise
async function getJSON(url) {
return new Promise(function (resolve, reject) {
let request = new XMLHttpRequest();
request.open('GET', url);
request.onload = function () {
// Begin accessing JSON data here
let data = JSON.parse(this.response);
if (request.status >= 200 && request.status < 400) {
//Start writing function here
let data2 = JSON.stringify(data)
return resolve(data);
} else {
return reject('error')
}
}
request.send();
}
)
}
async function main() {
let data1 = await getJSON("https://statsapi.web.nhl.com/api/v1/people/8476459/stats?stats=statsSingleSeason&season=20212022")
console.log(data1);
console.log(JSON.stringify(data1));
}
main();
A better way is to use Fetch API
async function getJSON(url) {
const data1 = await fetch(url).
then(response => response.json());
return data1;
}
async function main() {
const result = await getJSON('https://statsapi.web.nhl.com/api/v1/people/8476459/stats?stats=statsSingleSeason&season=20212022');
console.log(result);
}
main();
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 2 years ago.
I'm having a problem with javascript code. I am trying to have dynamical chart, which will update on changing a select field with plotly.reshape function. I call an Ajax request based function inside of chart() function and i want it to wait for variable assignment and then draw a chart. I think i'm using async/await in a wrong place. Can u guys help me ? It is my very first js script, but i need it in project.
function chart(){
var x = Chart();
var X =x[0];
var Close=x[1];
var High=x[2];
var Low=x[3];
var Open=x[4];
console.log(X);
var trace1 = {
x: X,
close: Close,
decreasing: {line: {color: '#7F7F7F'}},
high: High,
increasing: {line: {color: '#17BECF'}},
line: {color: 'rgba(31,119,180,1)'},
low: Low,
open: Open,
type: 'ohlc',
xaxis: 'x',
yaxis: 'y'
};
var data = [trace1];
var layout = {
...
};
Plotly.newPlot('chart', data, layout);
}
function Chart(){
var data, date = [], price = [], open=[], Timestamp=[], High=[], Low = [];
let selectedItem = document.getElementById('currency-selector').value;
var url = `http://127.0.0.1:8000/${selectedItem}/`;
var x = new Array()
var requestURL = url; //URL of the JSON data
var request = new XMLHttpRequest({mozSystem: true}); // create http request
request.onreadystatechange = async function() {
if(request.readyState == 4 && request.status == 200) {
data = JSON.parse(request.responseText);
for (var i=0; i<data.length;i++) {
date.push(data[i].date)
price.push(data[i].close);
High.push(data[i].high);
open.push(data[i].Open);
Low.push(data[i].low);
}
//chart(date,price,High,Low,open);
}
await request.open('GET', requestURL, true);
request.send(); // send the request
}
return [date,price,High,Low,open];
}
I can't test this because of the set up, but this should work... and return things in the order you expect them to be.
this is using the fetch api, which is generally much cleaner than the xmlhttp request api.
but so you know, async is the label for the function that contains await. and .then() is how to order things in a callback like that... the value that is awaited will execute each then first before returning the awaited value.
async function Chart(){
let date = [], price = [], open=[], Timestamp=[], High=[], Low = [];
let selectedItem = document.getElementById('currency-selector').value;
let url = `http://127.0.0.1:8000/${selectedItem}/`;
let requestURL = url; //URL of the JSON data
return await fetch(requestURL)
.then(res=>res.json())
.then(data=>{
data.forEach(x=>{
date.push(x.date)
price.push(x.close);
High.push(x.high);
open.push(x.Open);
Low.push(x.low);
})
})
.then(()=>{
return [date,price,High,Low,open];
})
}
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 7 years ago.
I don't know how to implement getState. What I am trying to do is update a field on click with a state value returned in my AJAX call. I have seen a reference to promises in another response but I do not understand how to use them.
function processRequest(e) {
if (xhr.readyState == 4 && xhr.status == 200) {
var response = JSON.parse(xhr.responseText);
var state = response.state;
}
}
$('#myState').on('click', function() {
var localState = getState();
$('#location').val(localState);
});
You need to change variable scope so it would be accessible from out of processRequest() function.
var response = '';
var state = '';
function processRequest(e) {
if (xhr.readyState == 4 && xhr.status == 200) {
response = JSON.parse(xhr.responseText);
state = response.state;
}
}
$('#myState').on('click', function() {
$('#location').val(state);
});