ClearInterval does not work

1

I have a script that does a Post Ajax from time to time.

update ();

$.ajax({
        type: "POST",
        url: "processar.php",
        success: function(resposta){

            $("#resposta").html(resposta);
            $("#resposta").find("script").each(function(i) {
                eval($(this).text());
            });

        },complete: function(){
            setTimeout(function(){atualizar();},5000);
        }

    });

process.php

if( ($result->status=='OK'){

    echo "<script>window.clearInterval(pisca['".$id_div."']);</script>";

}else{

    echo "<script>pisca['".$id_div."'] = setInterval(function(){ 
    $('#".$id_div."').animate({backgroundColor: 'white', color: 'black'}).delay(100);
    $('#".$id_div."').animate({backgroundColor: '".$fundo."', color: '".$letra."'}).delay(100);
    },100);</script>";

}

Step the div id by Post. But clearInterval does not work.

Any help?

    
asked by anonymous 27.01.2015 / 19:02

1 answer

3

I suggest separating the waters.

What belongs to the client side do on the client side, which belongs to the server side do on the server side. This implies that you do not pass the server's JavaScript to a eval on the client side.

Suggestion:

var pisca = {};

function atualizar(id) {
    $.ajax({
        type: "POST",
        url: "processar.php",
        dataType: 'json',
        data: id, // este campo está em falta no teu código. Não vejo de que maneira passas a ID...
        success: function (res) {
            animar(res.id, res.status, res.data);
        },
        complete: function () {
            setTimeout(atualizar, 5000);
        }
    });
}

function animar(id, status, data) {
    if (status == 'OK') return clearInterval(pisca[id]);
    pisca.id = setInterval(function () {
        $('#' + id).animate({
            backgroundColor: 'white',
            color: 'black'
        }).delay(100);
        $('#' + id).animate({
            backgroundColor: data.fundo,
            color: data.letra
        }).delay(100);
    }, 100);
}

and in PHP do only:

echo json_encode(
    'id'=>$id_div, 
    'status' => ($result->status), 
    'data' => array('fundo' => $fundo, 'letra' =>$letra)
);
    
27.01.2015 / 19:54