-1

I am pulling out data from a external source and the data seems to appear in a different order after every page refresh. I'm unsure if its related to my jquery or a lack of. Or if it's related to the google finance data I use to collect the data. Ideally I would like it sorted by column one alphabetically.

I'm adamant that there has to be a way to sort the array without it populating the list randomly. JSfiddle:

https://jsfiddle.net/vkf0jhpq/

$(document).ready(function () {
    for (var i = 0; i < gstock.length; i++) {
        $.getJSON("https://finance.google.com/finance/info?client=ig&q=" + gstock[i] + "&callback=?", function (response) {
            var stockInfo1 = response[0];
            var divContainer = $('*[data-symbol="' + stockInfo1.t + '"]');
            var percentStock = !isNaN(stockInfo1.c) && !isNaN(stockInfo1.l) && stockInfo1.l ? ((parseFloat(stockInfo1.c)/parseFloat(stockInfo1.l)) * 100) : undefined;
Sam Wilson
  • 65
  • 5

2 Answers2

1

your problem is that you are doing asynchronous calls to get each stock (meaning they will run at the same time) and then appending each item when the call has been successful.

This means that each item will be appended depending on the time it takes to do the request so if the first request takes slightly longer than the second request, the second one will show before the first (which is why they seem to be in a random order).

One way to stop this and keep your order would be to make the calls synchronous but I think this would make your page load time a lot longer.

Another way is to used the .when so that you can use the ajax to populate a var and then once all the calls are finished you can sort the resulting var into the order you want and then append them to the document

This is a quick example to show one way of keeping the appended items in the same order as the gstock var

Community
  • 1
  • 1
Pete
  • 57,112
  • 28
  • 117
  • 166
1

You cant use sync call with $.ajax() in crossdomain value. You must use this syntax

$.when( $.getJSON( YOUR_RESOURCE ) ).then( function( data, status, jqXHR ) {
    alert( jqXHR.status );
});

in according with http://api.jquery.com/jQuery.when/

UPDATE: see this examples

$.when( $.ajax( "/page1.php" ), $.ajax( "/page2.php" ) ).done(function( a1, a2 ) {
  // a1 and a2 are arguments resolved for the page1 and page2 ajax requests, respectively.
  // Each argument is an array with the following structure: [ data, statusText, jqXHR ]
  var data = a1[ 0 ] + a2[ 0 ]; // a1[ 0 ] = "Whip", a2[ 0 ] = " It"
  if ( /Whip It/.test( data ) ) {
    alert( "We got what we came for!" );
  }
});

UPDATE2:

jsfiddle example (only console.log but work) https://jsfiddle.net/k41y4yqu/1/

carlo denaro
  • 425
  • 6
  • 14