Nexus1234 Nexus1234 - 3 years ago 71
Ajax Question

Utilising the same ajax data for a "refresh all" event (wanting to prevent multiple calls)

So I have a page where multiple containers are dynamically added and filled with html, some of which are populated with data pulled via ajax from a json file. Every 5 minutes the page runs a function that gets every container (marked with class) and for each of them works out its id/index (probably not very efficiently) and does the ajax post.etc.

But the ajax call resulting data is the same essentially for every instance (no limit but on average there would be ~30 ajax calls of the same data for one whole page), it grabs it, decodes it, sorts it, updates html and that is it really.

This feels clunky and im sure will cause issues down the line, is there anything I can do to prevent these 30+ ajax posts without disabling it being 'Asynchronous'/lessen the impact of it?

setInterval(function() {
$('.fill').each(function() {
var selectId = this.id;
var selectIdNum = selectId.replace(/\D/g, '');
selectedId = 'selectedcoin' + selectIdNum;
var index = document.getElementById(selectedId).selectedIndex;
$.ajax({
url: 'array-to-json.php',
type: 'POST',
dataType: 'json',
success: function(data) {
data.sort(function(a, b) {
return (a.id > b.id) ? 1 : ((b.id > a.id) ? -1 : 0);
});
result = data;
var php1 = [result[index].name, result[index].symbol, result[index].price_btc, result[index].percent_change_24h, result[index].price_usd, result[index].id, result[index]['24h_volume_usd']];
var myCoinCost = parseFloat($('#buyprice' + selectIdNum).val());
var myPercCoin = (parseFloat(php1[2]).toPrecision(20) - myCoinCost) / myCoinCost * 100;
var myCoinTotal = parseFloat($('#coins' + selectIdNum).val());
var myUsdCoin = myCoinTotal * parseFloat(php1[4]).toPrecision(20);
$("#price" + selectIdNum).html(php1[2]);
$("#pricePercent" + selectIdNum).html(php1[3]);
$("#priceUsd" + selectIdNum).html(php1[4] + "</span>");
$("#volDay" + selectIdNum).html("$" + php1[6] + "</span>");
$("#myPercent" + selectIdNum).html(myPercCoin.toFixed(2) + "%");
$("#myEarnings" + selectIdNum).html(myUsdCoin.toFixed(2));
},
error: function() {
alert("error");
}
});
});
}, 300 * 1000);

Answer Source

It seems like your call returns all the data for all the containers already. You don't pass any specific ID into it, and you are filtering the results when you get them, so I will make that assumption.

In that case, all you need to do is move your .each loop inside the ajax success function. That way the ajax runs once, and you just loop through the data when it's received to apply it to the HTML.

I think this should do it:

setInterval(function() {
    $.ajax({
        url: 'array-to-json.php',
        type: 'POST',
        dataType: 'json',
        success: function(data) {
            data.sort(function(a, b) {
                return (a.id > b.id) ? 1 : ((b.id > a.id) ? -1 : 0);
            }); //is this really necessary? The server-side could probably sort it more efficiently, esp if it's the result of the SQL query.
            result = data;
            $('.fill').each(function() {
                var selectId = this.id;
                var selectIdNum = selectId.replace(/\D/g, '');
                selectedId = 'selectedcoin' + selectIdNum;
                var index = document.getElementById(selectedId).selectedIndex;
                var php1 = [
                  result[index].name, result[index].symbol, 
                  result[index].price_btc, result[index].percent_change_24h, 
                  result[index].price_usd, result[index].id, 
                  result[index]['24h_volume_usd']
                ];
                var myCoinCost = parseFloat($('#buyprice' + selectIdNum).val());
                var myPercCoin = (parseFloat(php1[2]).toPrecision(20) - myCoinCost) / myCoinCost * 100;
                var myCoinTotal = parseFloat($('#coins' + selectIdNum).val());
                var myUsdCoin = myCoinTotal * parseFloat(php1[4]).toPrecision(20);
                $("#price" + selectIdNum).html(php1[2]);
                $("#pricePercent" + selectIdNum).html(php1[3]);
                $("#priceUsd" + selectIdNum).html(php1[4] + "</span>");
                $("#volDay" + selectIdNum).html("$" + php1[6] + "</span>");
                $("#myPercent" + selectIdNum).html(myPercCoin.toFixed(2) + "%");
                $("#myEarnings" + selectIdNum).html(myUsdCoin.toFixed(2));
            });
        },
        error: function(jqXHR) {
            alert("Error while fetching data");
            console.log("Error while fetching data: " + jqXHR.status + " " + jqXHR.statusText + " " + jqXHR.responseText); //improved error logging
        }
    });
}, 300 * 1000);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download