Javascript Ajax error [duplicate]

-1

Well I have the following Javascript code

function fun() {
    $.ajax({
        url: 'aposta.php',
        success: function(a){
            if(a) {
                a = JSON.parse(a);
                $("#tempo").html(a.time);

                if (a.time === 0) {
                    $('#oi').attr('disabled', 'disabled');
                    setTimeout(function() {
                        $('#oi').removeAttr('disabled');
                    }, 6000);
                }

                $("#box").animate({
                    'background-position-x': numero(a.numero)
                }, 500);
            }
            else {
                $("#tempo").html("0");
            }
        }
    });
};
  setInterval(function(){
	 fun();

  }, 1000);
 </script>

What I wanted was in that setinterval that updates every 1 second to put an html code so that this html code is updated without needing refresh if I change the site.

Basically, I want to update this $ balance variable in php every 1 second without having to give f5 on the site.

How can I do this?

Thank you.

    
asked by anonymous 06.03.2016 / 13:23

1 answer

0

The setInterval is not ideal for this situation, it can bring the results in the wrong order if for some delay in the network the response to a request that was made after arriving first or stacking a lot of requests together.

You can request the result of the url by passing a callback function to get more organized:

function requestMyServerData(){
    //a função abaixo chama $.ajax por dentro, 
    //simplifica para esses casos mais simples
    $.get('aposta.php', onResultReturned);
}

jquery.get

Then you implement this callback function:

function onResultReturned(data){
    //aqui 'data' será a mesma coisa que 'a' no seu exemplo
    //pode tratar o resultado e então chamar novamente a primeira função
    //isso garante não fazer uma requisição antes da outra retornar
    requestMyServerData();
}

The ideal even for this kind of situation is to use push, that is, to have the server be able to alert the client's browser when there is an interesting change to it. Polling is outdated.

If you are using an IIS and .NET server, you can use SignalR to communicate with clients that are currently open. SignalR documentation

Using Apache I do not know, but it should have something similar.

Good luck!

    
06.03.2016 / 15:39