Undefined variable error in jQuery-Collection of common programming errors

The problem with your code is that, because of the asynchronous call you have there the order of execution might look like this (of course it can differ because of the interval and multiple calls to the getJSON):

// 1. the call to setInterval is initiated (the function in it will not be called until the sequential instructions after setInterval are finished)
var yenile = setInterval(function() {...}, 100);
// 2
var anlikwar = $(".wfloodnum").text().split(":")[1];
// 3
var anlikflood = $(".nfloodnum").text().split(":")[1];
// 4
alert(anlikflood);

// 5. NOW COMES THE function given to setInterval
$.getJSON("ayarlar.asp",function(veri) { ... });
// 6. now would come any other instructions in the function given to setInterval after the getJSON
// 7.
$(".wfloodnum").html("Şu anki değer:" + veri.floodwarno);
// 8
$(".nfloodnum").html("Şu anki değer:" + veri.floodnum);

In the above sequence you see that at steps 2 and 3 the variables there are undefined because the element you access does not have any text yet. Or, it has empty string, split is by : and you get the array [""] and therefore the index 1 in this array is undefined.

You must re-think the structure of your code. At least the variables anlikwar and anlikwar should be assigned after the JSON request completes.

At least you coud do something like:

var anlikwar;
var anlikflood;

var yenile = setInterval(function() {
    $.getJSON("ayarlar.asp",function(veri) {
        $(".wfloodnum").html("Şu anki değer:" + veri.floodwarno);
        $(".nfloodnum").html("Şu anki değer:" + veri.floodnum);

        anlikwar = $(".wfloodnum").text().split(":")[1];
        // or simply: anlikwar = veri.floodwarno
        anlikflood = $(".nfloodnum").text().split(":")[1];
        // or simply: anlikflood = veri.floodnum
    });
},100);

It looks like you want to monitor something on the server. This looks like a WebSockets use case. Depending on the server framework you are using, there are different web socket packages you can use.

Originally posted 2013-11-09 23:32:47.