DCJones
DCJones

Reputation: 3451

Return JSON data into a table

I have a script that returns data into a table, this works to a degree. The issue I am having is the script keep going round in some sort of loop and adding the same data to more rows in the table.

function refreshDataLiveEvents() {
    $.ajax({
        type: 'POST',
        url: 'check_current_events.php',
        data: $('#departcount').serialize(),
        dataType: "json", //to parse string into JSON object,
        success: function (data) {
            if (data) {
                var len = data.length;
                var txt = "";
                if (len > 0) {
                    for (var i = 0; i < len; i++) {

                        if (data[i].Department && data[i].Depart) {

                            txt += "<tr><td>" + data[i].Department + "</td><td>" + data[i].Depart + " </td></tr>";
                        }
                    }
                    if (txt != "") {
                        $("#table").append(txt);
                    }
                }
            }
        },
        error: function (jqXHR, textStatus, errorThrown) {
            alert('error: ' + textStatus + ': ' + errorThrown);
        }
    });
    return false;

}
setInterval(refreshDataLiveEvents, 3000);

Can anyone see where or what I am doing wrong. Any help would be great. Many thanks in advance.

Upvotes: 0

Views: 634

Answers (2)

user3468621
user3468621

Reputation: 357

In your code, you have used settimeinterval method. It will call for every 3000 ms. So you clear the interval once called or use SetTimeOut method

SetTimeOut(methodName, ms); 

Upvotes: -1

michelem
michelem

Reputation: 14590

The loop is because you use setInterval that executes refreshDataLiveEvents every 3 seconds. If you need to execute it once after 3 seconds, use setTimeout instead.

So just change this:

setInterval(refreshDataLiveEvents, 3000);

to this:

setTimeout(refreshDataLiveEvents, 3000);

Upvotes: 3

Related Questions