-2

i have an application that runs continuously and updates itself if needed. It uses ajax to call a php file that will check some data on the database, if it has changed then we update the screen. The php seems to work just fine its the js that i'm having a problem with.

$(document).ready(function () {
    $('.trade_window').load('signals.php?action=init', setInterval(function () {
        for(var i = 1; i < 6; i++) {
            console.log('market_name_' + i + " is " + $('.market_name_' + i).text().trim());
            $.ajax({
                url: 'signals.php?action=check&param=' + JSON.stringify({
                    'market_number': i,
                    'market_name': ('.trade_window .market_name_' + i).text().trim(),
                    'trade_type': $('.trade_window .status_' + i).text().trim(),
                    'trade_start_price': '1.1234',
                    'trade_open_time': '18:21:02'
                }),
                type: 'GET',
                success: function (result) {
                    if(result.trim() === "false") {
                        console.log("RESULT IS " + result.trim());
                    } else {
                        $('.trade_window #market_1').html(result);
                        setTimeout(function () {
                            // This is to make it a little more visible 
                            console.log(" ");
                            console.log(" ");
                            console.log("PAUSE!!!!");
                            console.log(" ");
                            console.log(" ");
                        }, 5000);
                    }
                }
            });

        };
    }, 2000));
});

So, what happens in the application is there are 6 elements (divs) within these we have a few pieces of information, these are compared with the data on the DB if they're different then the DB information needs to be shown.

Now the script above checks each element and then updates if it is needed, the problem is that the ajax call is done in the background and all the other stuff is executed while we're waiting for the ajax calls to complete so by the time tthey have completed the for loop is at the end so only element 6 will be updated even if element 1, 2, 3, 4 or 5 are changed.

What can i do to change this? is there a js/jquery method that can be used to check if the php file has finished loading?

Thanks for your time.

gen_Eric
  • 223,194
  • 41
  • 299
  • 337
ragebunny
  • 1,582
  • 10
  • 33
  • 53
  • complete : function(){} – pmandell May 07 '13 at 13:42
  • A callback function is needed :: http://stackoverflow.com/questions/11576176/wait-for-a-jquery-ajax-callback-from-calling-function – tymeJV May 07 '13 at 13:43
  • 2
    Why in the world do you have a setTimeout for the callback of the load method? That makes no sense at all! – epascarello May 07 '13 at 13:46
  • 1
    `setInterval` doesn't return a function, so `$('.trade_window').load('signals.php?action=init', setInterval(function(){` makes no sense whatsoever. – gen_Eric May 07 '13 at 13:48
  • Okay so i'm a little lost here. Does anyone have something i could ready to get my head around this? – ragebunny May 07 '13 at 13:50
  • 1
    I think promises would be a good solution here: [promises on stackoverflow][1] [1]: http://stackoverflow.com/questions/6080050/how-does-jquerys-promise-method-really-work – Jonas Grumann May 07 '13 at 13:52
  • @RocketHazmat Hi, do you have some more information on what im doing wrong or even a different approach do what i'm trying to do? (I'm a bit of a rookie with js/jquery, so this is all a learning curve for me). Thanks. – ragebunny May 07 '13 at 13:56
  • 1
    @ragebunny: What exactly are you trying to do? I don't know if it would work, but try to put your `setInterval` *inside* the function. `$('.trade_window').load('...', function(){ setInterval(function(){ //...; }, 2000); });` – gen_Eric May 07 '13 at 13:58
  • 1
    @RocketHazmat Ahh i see what i've done now and you're right it doesn't make any sense... sometimes you need someone to give you a slap in order to see what you're doing wrong i guess. Thanks a lot for the help there. – ragebunny May 07 '13 at 14:10
  • 1
    @ragebunny: No problem. I've had the same thing happen to me too :-) Sometimes it really does take someone else looking at your code to point out stuff. – gen_Eric May 07 '13 at 14:11
  • @pmandell I just replaced the success part with complete, seems good, but the return i get from ajax is strange to me, before it was just the echoed response from php eg echo "test"; but now it's an object and i'm not 100% sure how i'm accessing that any ideas? – ragebunny May 07 '13 at 14:28

1 Answers1

0

Collect the deferred (promise) return value of your $.ajax calls:

var def = [];

for (var i = 1; i < 6; ++i) {
    def[i - 1] = $.ajax({ ... });
}

and then outside the loop use $.when() to wait for them all to complete:

$.when.apply($, def).done(function(r1, r2, r3, ...) {
    ...
});
Alnitak
  • 334,560
  • 70
  • 407
  • 495
  • I'm not really understanding how this works....? I think i understand the first part, its the $.when bit i haven't a clue about. what are the parameters in the function? – ragebunny May 07 '13 at 15:30
  • `$.when.apply` is just the way of calling `$.when()` with an array of parameters instead of listing them individually. It means "when all these are done, call this". – Alnitak May 07 '13 at 15:35
  • I'm still not getting it, i've put the $.when.apply($, def).done(function(){}); after the for loop and i get 'connot call method 'apply' of undefined.' – ragebunny May 08 '13 at 08:53
  • are you using jQuery older than v1.5 ? See http://api.jquery.com/jQuery.when/ for more info – Alnitak May 08 '13 at 08:57
  • Yeah I'm using 1.8.3. I'll have a little play with it now, i can see the concept, we're making an array of ajax calls and then executing a function when they're done. Is that right? – ragebunny May 08 '13 at 09:21
  • @ragebunny yes, that's the intention. – Alnitak May 08 '13 at 09:21
  • So does the when.apply($, def).cone method check every element in the array or should i be referencing each element? – ragebunny May 08 '13 at 09:27
  • See http://stackoverflow.com/questions/13932344/why-use-apply-method/13932420#13932420 – Alnitak May 08 '13 at 09:31
  • let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/29586/discussion-between-ragebunny-and-alnitak) – ragebunny May 08 '13 at 09:48