JavaScript - Asynchronous request issue [duplicate] - javascript

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 7 years ago.
A common Asynchronous request is made by the following:
var xhr = new XMLHttpRequest();
xhr.open("GET", "http://localhost:1337/test.php", true);
xhr.onload = function (e) {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
abc = xhr.responseText;
} else {
console.error(xhr.statusText);
}
}
};
a = JSON.parse(abc);
I get the following error:
Uncaught ReferenceError: abc is not defined
What is going wrong here?

You are trying to call abc outside onload that might be the only issue.
var xhr = new XMLHttpRequest();
xhr.open("GET", "http://localhost:1337/test.php", true);
xhr.onload = function (e) {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
var abc = xhr.responseText;
var a = JSON.parse(abc); // moved it here
} else {
console.error(xhr.statusText);
}
}
};
to return value from a function, Use it this way
function getResult(myFunction) {
var xhr = new XMLHttpRequest();
xhr.open("GET", "http://localhost:1337/test.php", true);
xhr.onload = function (e) {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
var abc = xhr.responseText;
myFunction(abc);
} else {
console.error(xhr.statusText);
}
}
};
}
function myFunction(jsonData) {
//do whatever you wish to do here
}
Now how you are going to call it.
getResult(myFunction); //callback;

Related

js xml response return undifined

Please I need help !
To begin I don't speaking very well english sorry for the mistakes
So I'm tryng to receive a JSON Object with this code :
function uhttp(url){
var xhr = new XMLHttpRequest();
xhr.open('get', url, true);
xhr.responseType = 'json';
xhr.onload = function() {
var status = xhr.status;
if (status == 200) {
console.log(xhr.response)
return xhr.response;
}
};
xhr.send();
console.log('exit')
};
but when I use the function https like this :
`
( ()=>{
var perso =uhttp('bd.php?table=charac')
for (var i = 0; i < perso.lenght; i++) {
document.getElementbyID('container').append('<ul>'+perso[i].nom+'</ul>')
}
})()
`
perso he's undifined...
here the console of index.html
I've the impression that we'are exit the function before that whe receive the resonse and that is why the function return a null
Of course before to ask my question I'have make some research but no one working in my case....
Thank you for yours anwsers
It happens because you aren't returning value from uhttp() function but from anonymous function (xhr.onload).
In order to access this value after the AJAX call is over use promises:
function uhttp(url){
return new Promise(function(resolve, reject) {
var xhr = new XMLHttpRequest();
xhr.open('get', url, true);
xhr.responseType = 'json';
xhr.onload = function() {
var status = xhr.status;
if (status == 200) {
resolve(xhr.response);
return;
}
reject();
};
xhr.onerror = function() {
reject()
};
xhr.send();
})
}
And use it like so:
uhttp('bd.php?table=charac').then(function(result) {
var person = result;
for (var i = 0; i < perso.lenght; i++) {
document.getElementbyID('container').append('<ul>'+perso[i].nom+'</ul>');
}
}).catch(function() {
// Logic on error
});

How to call a piece of code only after a callback function has been executed?

Consider this code, just like a toy example:
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML = this.responseText;
}
};
xhttp.open("GET", "demo_get2.asp?fname=Henry&lname=Ford", true);
xhttp.send();
}
Let's consider that there are five kinds of asynchronous calls inside the function loadDoc(). What I want to do is now is to call another function or any piece of code when all five callback functions are executed. Does Javascript provide anything to help with this situation, or we need to set a flag to check if all 5 tasks are executed?
If you use promises you'll be able to use Promise.all([promises]).
"Promisifying" your current ajax request:
function loadDoc() {
req().then(function (responseText) {
document.getElementById("demo").innerHTML = responseText;
})
}
function req () {
return new Promise(function (resolve, reject) {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
resolve(this.responseText);
} else {
reject();
}
};
xhttp.open("GET", "demo_get2.asp?fname=Henry&lname=Ford", true);
xhttp.send();
});
}
You can either use a callback or a promise,
callback example:
function loadDoc(cb) {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML = this.responseText;
cb(xhttp.responseText); // <= run the callback
}
};
xhttp.open("GET", "demo_get2.asp?fname=Henry&lname=Ford", true);
xhttp.send();
}
loadDoc(function(res) {
console.log(res);
// do something
});
promise example:
function loadDoc(cb) {
return return new Promise(function (resolve, reject) {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML = this.responseText;
resolve(xhttp.responseText); // <= run the callback
} else {
reject(xhttp.responseText);
}
};
xhttp.open("GET", "demo_get2.asp?fname=Henry&lname=Ford", true);
xhttp.send();
}
loadDoc()
.then(function(res) {
console.log(res);
// do something
})
.catch(function(err) {
console.error(err);
// do something
});

How I can return XMLHttpRequest response from function? [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 6 years ago.
Value isn't replace and function return 0. How to fix it?
(react-native 0.30, IOS 10.0 Simulator)
export function getCategoryList() {
var xhr = new XMLHttpRequest();
jsonResponse = null;
xhr.onreadystatechange = (e) => {
if (xhr.readyState !== 4) {
return;
}
if (xhr.status === 200) {
console.log('SUCCESS', xhr.responseText);
jsonResponse = JSON.parse(xhr.responseText);
} else {
console.warn('request_error');
}
};
xhr.open('GET', 'https://httpbin.org/user-agent');
xhr.send();
return jsonResponse;
}
You can't return the value like that.
I would suggest going with either callbacks or promises:
Callback:
function getCategoryList(callback) {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = (e) => {
if (xhr.readyState !== 4) {
return;
}
if (xhr.status === 200) {
console.log('SUCCESS', xhr.responseText);
callback(JSON.parse(xhr.responseText));
} else {
console.warn('request_error');
}
};
xhr.open('GET', 'https://httpbin.org/user-agent');
xhr.send();
}
getCategoryList(data => console.log("The data is:", data));
Promises:
function getCategoryList() {
var xhr = new XMLHttpRequest();
return new Promise((resolve, reject) => {
xhr.onreadystatechange = (e) => {
if (xhr.readyState !== 4) {
return;
}
if (xhr.status === 200) {
console.log('SUCCESS', xhr.responseText);
resolve(JSON.parse(xhr.responseText));
} else {
console.warn('request_error');
}
};
xhr.open('GET', 'https://httpbin.org/user-agent');
xhr.send();
});
}
getCategoryList().then(res => console.log("The result is", res));
You can return the request response if XHR is synchronous (xhr.open('GET', 'https://httpbin.org/user-agent', false)), doing a infinite loop that breaks when the request is finished.
Notes:
Synchronous XHR is deprecated;
Infinite loop will stop the page while XHR isn't finished (e.g, a game).
function getCategoryList() {
var xhr = new XMLHttpRequest();
xhr.open("GET", "https://httpbin.org/user-agent", false);
xhr.send();
// stop the engine while xhr isn't done
for(; xhr.readyState !== 4;)
if (xhr.status === 200) {
console.log('SUCCESS', xhr.responseText);
} else console.warn('request_error');
return JSON.parse(xhr.responseText);
}

can't get answer of ajax with Javascript [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 7 years ago.
i have this:
var something = makeRequest(url);
function makeRequest(url) {
var http_request = false;
if (window.XMLHttpRequest) {
http_request = new XMLHttpRequest();
if (http_request.overrideMimeType) {
http_request.overrideMimeType('text/xml');
}
} else if (window.ActiveXObject) {
try {
http_request = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
http_request = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {}
}
}
if (!http_request) {
console.log('Falla :( No es posible crear una instancia XMLHTTP');
return false;
}
http_request.onreadystatechange = alertContents;
http_request.open('GET', url, true);
http_request.send(null);
function alertContents() {
if (http_request.readyState == 4) {
if (http_request.status == 200) {
//console.log(http_request.responseText); //this show a string result
//return http_request.responseText; //this not return nothing
//var something = http_request.responseText; // this return a undefined variable
} else {
console.log('Hubo problemas con la peticiĆ³n.');
}
}
}
}
look just under "if (http_request.status == 200)" the three things i prove and NOTHING.
i don't know how to get out of the function the result of the call. please help me
Your alertContents() function is executed asynchronously. You cannot return a value from the function. You can declare a global variable and assign the reponseText value to it and then process it.
var result ;
function alertContents() {
if (http_request.readyState == 4) {
if (http_request.status == 200) {
result = http_request.responseText ;
process(result) ; // guaranteed that there will be some response
}
}
}
process(result); // Does not guarantee that result will have the
// returned value (response) and may result in failure

How to know how many asynchronous calls are pending

I'm using the following code to make multiple async. calls and I need to know how many of those calls are pending for validating purposes.
function llenarComboMetodos(cell) {
var xhr;
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
}
else if (window.ActiveXObject) {
xhr = new ActiveXObject("Msxml2.XMLHTTP");
}
else {
throw new Error("Las llamandas asincronas no son soportadas por este navegador.");
}
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
if (xhr.status == 200 && xhr.status < 300) {
var combo = '<select name="metodos[]">';
var opciones=xhr.responseText;
combo+= opciones+"</select>";
cell.innerHTML = combo;
}
}
}
xhr.open('POST', 'includes/get_metodos.php');
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.send("completar=1");
}
Is there a way to know that?
Thank you (:
You can intercept the XMLHttpRequest.send and do your counting of active calls:
var activeXhr = (function(){
var count = 0;
XMLHttpRequest.prototype.nativeSend = XMLHttpRequest.prototype.send;
XMLHttpRequest.prototype.send = function(body) {
this.onreadystatechange = function(){
switch(this.readyState){
case 2: count++; break
case 4: count--; break
}
};
this.nativeSend(body);
};
return count;
})();
console.log(activeXhr);

Categories

Resources