Interval to test if user is online issue

I have the following script below that is inside a 6 second interval.

I am trying to loop through a DIV container that has a number of div’s and each div has an ID set to an instructor code for identification. Now I want to loop through this container…grab each ID one at a time and test to see if it is still present in the database. If present then it means the instructor is still online and then I will set the CSS to show “online”.

For some reason my code loops through each ID and THEN it calls the ajax function to execute the check.

setInterval(function() {
    $('.instructors_container table').each(function(){
        var i_code = $(this).closest('div').attr('id');
        console.log(i_code);            
        
        // Test to see if i_code is online
        $.ajax({
            type:"POST",
            url: "get_number_instructors_online.php",
            dataType: 'text',      
            data: {i_code:i_code},
            success: function(response) { 
                var answer = response;
                console.log(answer);

                if(answer == "online"){
                    var online = "<div class='i_online'></div>";
                    $('#'+i_code).find("td:first").html('').append(online);
                  }else{
                    var offline = "<div class='i_offline'></div>";
                    $('#'+i_code).find("td:first").html('').append(offline);
                }
            },
        });             
        })
    }, 6000); // every 6 seconds

Yes, that is how it works. Ajax isn’t magic and cannot interrupt the normal flow of JavaScript code.

As your code runs it sends a series of http requests to get_number_instructors_online.php
Those requests take time to be sent, time to be processed, and time to receive a response.

After the code has finished running the scripting code, when the web browser receives a response from one of those requests, the success part of the code is then run.

Thank you - I had a feeling this is what is happening. I will take a different approach.

A more reliable way seems to be to request information about all instructors currently online. When you receive that information as JSON data, you can then parse that and loop through that information to do the update.

That is exactly what I did and it works like a charm now thanks

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.