How to know how many asynchronous calls are pending - javascript

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

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

Returning the XML received on readystatechange - JavaScript

This is my first post here on Stack. I am trying to make a Get request which is succeeding but I am having trouble getting the responseXML into a variable for processing. I think I am supposed to be using a callback function, but I still can't get it quite right. I am hopeful that somebody can point me in the correct direction. Code below.
<script type="text/javascript">
function buildOptions() {
var data = null;
/*xhr.addEventListener("readystatechange", function () {
if (this.readyState === 4) {
console.log(this.responseText);
callback.call(xhr.responseXML);
}
});*/ //This code block worked, but I couldn't figure out how to get the result back
getXML = function(callback) {
var xhr = new XMLHttpRequest();
xhr.withCredentials = true;
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
callback(xhr.responseText);
}
xhr.open("GET", "http://URLRemoved");
xhr.setRequestHeader("authorization", "StringRemoved");
xhr.setRequestHeader("cache-control", "no-cache");
xhr.setRequestHeader("postman-token", "TokenRemoved");
xhr.send();
}
}
function XMLCallBack(data) {
alert(data); // These two functions were the most recent attempt but I'm still missing something
}
xmlDoc = getXML(XMLCallBack); // this is supposed to start the processing of the returned XML
console.log(xmlDoc);
var campaignName = xmlDoc.getElementsByTagName('self')[0]; //XMLDoc contains a null variable when I get to this line
console.log(campaignName);
var campaigns = ["","Freshman Campaign","Sophomore Campaign","Junior Campaign","Senior Campaign"]; //Code from here and below will be changing slightly once I can get XMLDoc to be correct
var sel = document.getElementById('campaignList');
for(var i = 0; i < campaigns.length; i++) {
var opt = document.createElement('option');
opt.innerHTML = campaigns[i];
opt.value = campaigns[i];
sel.appendChild(opt);
}
}
</script>
I believe you should move open ---> send outside the onreadystatechange, like this:
getXML = function(callback) {
var xhr = new XMLHttpRequest();
xhr.withCredentials = true;
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
callback(xhr.responseText);
}
}
xhr.open("GET", "http://URLRemoved");
xhr.setRequestHeader("authorization", "StringRemoved");
xhr.setRequestHeader("cache-control", "no-cache");
xhr.setRequestHeader("postman-token", "TokenRemoved");
xhr.send();
}
EDIT: This code should work:
<script type="text/javascript">
function buildOptions() {
var xhr = new XMLHttpRequest();
xhr.withCredentials = true;
xhr.onreadystatechange = XMLCallBack;
xhr.open("GET", "http://URLRemoved");
xhr.setRequestHeader("authorization", "StringRemoved");
xhr.setRequestHeader("cache-control", "no-cache");
xhr.setRequestHeader("postman-token", "TokenRemoved");
xhr.send();
function XMLCallBack() {
if (xhr.readyState == 4 && xhr.status == 200) {
xmlDoc = xhr.responseText;
var campaignName = xmlDoc.getElementsByTagName('self')[0];
var campaigns = ["","Freshman Campaign","Sophomore Campaign","Junior Campaign","Senior Campaign"];
var sel = document.getElementById('campaignList');
for(var i = 0; i < campaigns.length; i++) {
var opt = document.createElement('option');
opt.innerHTML = campaigns[i];
opt.value = campaigns[i];
sel.appendChild(opt);
}
}
}
}
</script>
I haven't tried it so I might have made some mistakes. If you want to, you can move XMLCallBack() outside of buildOptions() and use this.readyState, this.status and this.responseText instead of xhr.readyState etc..

set time out in ajax call while using core javascript

I have a JavaScript function to call ajax. Now I need to add time out in this function like while calling service took more than defile time ajax call should time out and display a default message. I don't want to use Jquery in it.
here is my code:
AJAX = function (url, callback, params) {
var dt = new Date();
url = (url.indexOf('?') == -1) ? url + '?_' + dt.getTime() : url + '&_' + dt.getTime();
if (url.indexOf('callback=') == -1) {
ajaxCallBack(url, function () {
if (this.readyState == 4 && this.status == 200) {
if (callback) {
if (params) {
callback(this.responseText, params);
} else {
callback(this.responseText);
}
}
}
});
} else {
var NewScript = d.createElement("script");
NewScript.type = "text/javascript";
NewScript.src = url + '&_' + Math.random();
d.getElementsByTagName('head')[0].appendChild(NewScript);
}
},
ajaxCallBack = function (url, callback) {
var xmlhttp;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = callback;
xmlhttp.open("GET", url, true);
xmlhttp.send();
}
Here's an example of how you can handle a timeout:
var xmlHttp = new XMLHttpRequest();
xmlHttp.open("GET", "http://www.example.com", true);
xmlHttp.onreadystatechange=function(){
if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
clearTimeout(xmlHttpTimeout);
alert(xmlHttp.responseText);
}
}
// Now that we're ready to handle the response, we can make the request
xmlHttp.send("");
// Timeout to abort in 5 seconds
var xmlHttpTimeout=setTimeout(ajaxTimeout,5000);
function ajaxTimeout(){
xmlHttp.abort();
alert("Request timed out");
}
In IE8, You can add a timeout event handler to the XMLHttpRequest object.
var xmlHttp = new XMLHttpRequest();
xmlHttp.ontimeout = function(){
alert("request timed out");
}
Use a javascript framework to do this though, i don't know why you're not using one, do you like uneccesary work? :)
If you want to simply add timeout, You can add it in the first function in three places:
setTimeout(function() {callback(this.responseText, params)}, 1000)
And your callback will execute around 1s later. The second palce is second call of callback.
Third place that i would suggest is to wrap this function like above:
ajaxCallBack(url, function () {
if (this.readyState == 4 && this.status == 200) {
if (callback) {
if (params) {
callback(this.responseText, params);
} else {
callback(this.responseText);
}
}
}
});
Usually when i get in to testing internet connection i rather add throttling in the chrome developer tools like this:
Here is your code with first approach:
AJAX = function (url, callback, params) {
var dt = new Date();
url = (url.indexOf('?') == -1) ? url + '?_' + dt.getTime() : url + '&_' + dt.getTime();
if (url.indexOf('callback=') == -1) {
ajaxCallBack(url, function () {
if (this.readyState == 4 && this.status == 200) {
if (callback) {
if (params) {
console.log(new Date());
setTimeout(function() {callback(this.responseText, params)}, 2000);
} else {
console.error((new Date()).getSeconds());
setTimeout(function() {callback(this.responseText)}, 2000);
}
}
}
});
} else {
var NewScript = d.createElement("script");
NewScript.type = "text/javascript";
NewScript.src = url + '&_' + Math.random();
d.getElementsByTagName('head')[0].appendChild(NewScript);
}
},
ajaxCallBack = function (url, callback) {
var xmlhttp;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = callback;
xmlhttp.open("GET", url, true);
xmlhttp.send();
}
AJAX('http://ip.jsontest.com/', function() {console.error((new Date()).getSeconds()); });
Maybe the answer to this question will help.
Timeout XMLHttpRequest
since from what i understand you need to set timeout for xmlhttprequest,
you can use xmlhttp.timeout = /*some number*/

Returning an array and storing into another array, creating a multidimensional array

EDIT: I've tried to implemented the solution, but it still doesn't work. Sorry i'm a programming idiot. Thanks for the link to the page.
In my first function databaseBOscreens i am attempting to obtain symbols of stocks according to the filter selected for a broker and/or an asset class. The function sends a request to another file which performs SELECT statement to lookup for the relevant symbols using mysqli. The result would be an array of symbols, which i then encode and subsequently parsed in this js function.
Each symbol will then go through a second process, which is my second function generatePrice() to obtain the historical prices for that particular symbol. What i'm trying to do is to loop through all symbols to generate and store the priceArr as an array in the resultArr. Sorry for being unclear.
function databaseBOscreens(broker,assetClass) {
var xhr;
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
}
else if (window.ActiveXObject) {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
var data = "broker=" + broker + "&category=" + assetClass;
xhr.open("POST", "generateSymbol.php", true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.send(data);
xhr.onreadystatechange = receive_data;
function receive_data() {
if (xhr.readyState == 4 && xhr.status == 200)
{
var resultArr = JSON.parse(xhr.responseText);
var priceArr = new Array();
for(var ctr=0;ctr<resultArr.length;ctr++)
{
generatePrice(function(result,resultArr[ctr].symbol)){
priceArr[ctr] = result;
}
}
}
}
}
function generatePrice(callback,symbol) {
var xhr2;
if (window.XMLHttpRequest) {
xhr2 = new XMLHttpRequest();
}
else if (window.ActiveXObject) {
xhr2 = new ActiveXObject("Microsoft.XMLHTTP");
}
var data2 = "symbol=" + symbol;
xhr2.open("POST", "generatePrice.php", true);
xhr2.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr2.send(data2);
xhr2.onreadystatechange = receive_data2;
function receive_data2() {
if (xhr2.readyState === 4)
{
if (xhr2.status === 200)
{
var priceArr = JSON.parse(xhr2.responseText);
callback(priceArr);
}
}
}
}
function receive_data() {
if (xhr.readyState == 4 && xhr.status == 200)
{
var resultArr = JSON.parse(xhr.responseText);
var priceArray = new Array();
for(var ctr=0;ctr<resultArr.length;ctr++)
{
priceArray = generatePrice(resultArr[ctr].symbol);
}
alert(priceArray.length);
}
}
My function generatePrice() returns an array, but i can't seem to store it in another array to create a multidimensional array. I've search everywhere i can't seem to get it work. Thanks in advance for any help rendered
generatePrice function:
function generatePrice(symbol) {
var xhr2;
if (window.XMLHttpRequest) {
xhr2 = new XMLHttpRequest();
} else if (window.ActiveXObject) {
xhr2 = new ActiveXObject("Microsoft.XMLHTTP");
}
var data2 = "symbol=" + symbol;
xhr2.open("POST", "generatePrice.php", true);
xhr2.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr2.send(data2);
xhr2.onreadystatechange = receive_data2;
function receive_data2() {
if (xhr2.readyState == 4 && xhr2.status == 200)
{
var priceArr = JSON.parse(xhr2.responseText);
return priceArr;
}
}
}
My function generatePrice() returns an array,
No it doesn't, it returns undefined. XHR is asynchronous, see How do I return the response from an asynchronous call?.
priceArray = generatePrice(resultArr[ctr].symbol);
I can't seem to store it in another array
You didn't attempt to do so, you just stored the result of every call in the priceArray variable - instead of in a property of the array. Use
priceArray[ctr] = generatePrice(resultArr[ctr].symbol);
// or
priceArray.push( generatePrice(resultArr[ctr].symbol) );

call generic handler in aspx without jquery

Can i call Generic handler in aspx without using jQuery?
yes, jQuery itself is a javascript, so you can call by writing your own script. The benefit of using jQuery is you don't need to worry about browser compatability, have to write less code, can get advantage of using jquery plugins etc, only the cost of adding jQuery.js.
Example:
<script type="text/javascript">
// Intialize XMLHTTP object
function GetXmlHttpObject() {
var A;
if (window.XMLHttpRequest) {
A = new XMLHttpRequest();
} else {
var msxmlhttp = new Array(
'Msxml2.XMLHTTP.6.0',
'Msxml2.XMLHTTP.3.0',
'Msxml2.XMLHTTP',
'Microsoft.XMLHTTP');
for (var i = 0; i < msxmlhttp.length; i++) {
try {
A = new ActiveXObject(msxmlhttp[i]);
break;
} catch (e) {
A = null;
}
}
}
return A;
}
function sendAjaxRequest(url, postVars, callbackFunc) {
var isPost = (postVars && postVars.length > 0);
var xmlHttp = GetXmlHttpObject();
if (xmlHttp == null) {
alert("Your browser does not support AJAX!");
return;
}
if (!isPost) {
if (url.indexOf('?') == -1) {
url += '?' + uncache();
} else {
url += '&' + uncache();
}
}
xmlHttp.onreadystatechange = function () {
if (xmlHttp.readyState == 4) { //This function will execute on receive
var callback;
var extra_data = false;
var data = xmlHttp.responseText;
callback = callbackFunc;
callbackFunc(data, extra_data);
}
};
//Send data to the url through ajax
if (isPost) {
xmlHttp.open("POST", url, true);
xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xmlHttp.setRequestHeader("Content-Length", postVars.length);
xmlHttp.setRequestHeader("Connection", "close");
xmlHttp.send(postVars);
} else {
xmlHttp.open("GET", url, true);
xmlHttp.send(null);
}
}
function uncache() {
var d = new Date();
var time = d.getTime();
return 'time=' + time;
}
function comp(result) {
alert(result);
}
sendAjaxRequest('test.html', '', comp);
</script>

Categories

Resources