Ajax, limit time even giving Reload on page

Asked

Viewed 506 times

0

I have the code that does what it has to do, and when it finishes it hides the button and shows the message of success:

function getFollow() {
  $('#btnFollow').click(function(a) {

    a.preventDefault(), $('#btnFollow').html('Ganhando seguidores...');

    $.ajax({
      url: 'api/follow.php',
      dataType: 'JSON',
      success: function(a) {
        1 == a.error ? alert(a.message) : (
          $('.success').css('display', 'block'),
          $('.success').html(a.message),
          setTimeout(function () {
              $('#btnFollow').hide();
          }, 2e3)
        )
      }
    })
  });
}

getFollow();

The problem is that when updating the page the button returns and the message disappears, in the message is written the following: "Followers sent successfully, come back in 30 minutes."

I would like that after 30 minutes the button would return automatically, without updating the page, and if update before 30 minutes the message is still there. How to do it right?

EDIT

Follow.php

<?php

require_once dirname(__DIR__) . DIRECTORY_SEPARATOR . 'autoload.php';
require_once dirname(__DIR__) . DIRECTORY_SEPARATOR . 'helpers' . DIRECTORY_SEPARATOR . 'TwitterOAuthHelper.php';

$helper = new TwitterOAuthHelper;

$twitterusers = new TwitterUsers;



if ($user = $helper->signedIn()) {
    $fetch = $twitterusers->selectUser($user->screen_name);

    foreach ($fetch as $row) {
        $screen_name[] = $row['screen_name'];
    }

    if ($followers = $helper->getFollowers($screen_name)) {
        echo json_encode([
            "error" => "Algo deu errado!",
            "success" => '',
            "message" => "Seguidores enviados com sucesso, volte em 30 minutos."
        ]);
    }
} else {
    echo json_encode([
            "error" => "true",
            "message" => "You have no open session."
        ]
    );
}
  • You can use $_COOKIE to handle OR you can handle it through the user’s IP OR you can handle it through the user id that returns in "$helper->signedIn()"

  • @Everson, I tried to put it into practice, but my logic didn’t match yours, is there a minimum example? , I would post my code here but I deleted....

4 answers

3


You need to call api/follow.php also in the onready of the page; ie while reloading the page it checks the status of time again and hides or not your button.

VerificarSeguidores = function(){
    $.ajax({
            url: 'api/follow.php',
            dataType: 'JSON',
            success: function(a) {
                1 == a.error ? alert(a.message) : (
                $('.success').css('display', 'block'),
                $('.success').html(a.message),
                setTimeout(function(){
                    $('#btnFollow').hide();
                }, 2e3))
            }
    }); 
}


/* Quando a página carregar verifica o status de seguidores 
e omite ou não o botão.*/
$(document).ready(function() {
    /* O código incluído no interior $( document ).ready() só será executado 
    uma vez que a página Document Object Model (DOM) 
    esteja pronta para o código JavaScript para executar.*/
    VerificarSeguidores();      
});

/*Quando houver o evento clique sobre o botão executa verificações de 
seguidores.*/
$('#btnFollow').click(function(a){
    a.preventDefault(), $('#btnFollow').html('Ganhando seguidores...');
    VerificaSeguidores();
});

After that to monitor the elapsed time, if it is greater than 30 minutes. You could save a cookie with the date and time of user input on the page, and using setInterval check from time to time how many minutes have elapsed. If greater than 30 minutes call again the ajax routine and release the button. The cookie would avoid sending unnecessary requests to the server.

  • Pow, thanks for the answer, I’ll be late blz? now I’m leaving, I’ll probably be here tonight. there

  • Quiet, the night vomit tests calmly.

  • Oops, I got to test here real quick, I’m only going out half a day anyway, but it didn’t work and it doesn’t show errors.

  • It would be good to also put an example of the use of setInterval to answer the question @Rafaelsalomão

2

You can use cookies, something like:

function getFollow() {
    $('#btnFollow').click(function(a) {

        a.preventDefault(), $('#btnFollow').html('Ganhando seguidores...');

        $.ajax({
            url: 'api/follow.php',
            dataType: 'JSON',
            success: function(a) {
                if (a.error == 1) {
                    alert(a.message)
                } else {

                    $('.success').css('display', 'block');
                    $('.success').html(a.message);
                    var expires = new Date();
                    expires.setTime(expires.getTime() + (30*60*1000));
                    document.cookie = "esconderBotao='" + a.message + "'; expires=" +  expires.toUTCString() + "; path=/";
                    setTimeout(function () {
                            $('#btnFollow').hide();
                    }, 2e3);
                    setTimeout(verificaCookie, (30*60*1000));

                }
            }
        })
    });
}

getFollow();

// original em https://www.w3schools.com/js/js_cookies.asp
function getCookie(cname) {
    var name = cname + "=";
    var decodedCookie = decodeURIComponent(document.cookie);
    var ca = decodedCookie.split(';');
    for(var i = 0; i <ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') {
            c = c.substring(1);
        }
        if (c.indexOf(name) == 0) {
            return c.substring(name.length, c.length);
        }
    }
    return "";
}

function verificaCookie() {
    var msg = getCookie('esconderBotao');
    if(msg != "") {
        // pagina recarregou mas cookie nao expirou
        $('#btnFollow').hide();
        $('.success').css('display', 'block');
        $('.success').html(msg);
        // verifica novamente em 1 minuto
        setTimeout(verificaCookie, 60 * 1000);
    } else {
        $('#btnFollow').show();
        $('.success').css('display', 'none');

    }
}

$(document).ready(function(){
    // ao carregar verifica cookie
    verificaCookie();
})
  • but if the user clears the cookies he can use again?

  • is working though, 'NaNfunction toUTCString() { [native code] } what this mistake means ?

  • Really if the user cleans the cookies he can reuse the system again. only one fix var cookie = getCookie('hideButton');&#xA; if(cookie != "") {&#xA; var msg = "Seguidores enviados com sucesso, volte em 30 minutos."; To avoid that message I quoted above.

  • This code does not work, I did everything to fix, cookies do not expire, is with errors, IE, It did not serve!

  • Fix errors, question: follow.php within 30 minutes of waiting will return error == 1 and after error == 0?

  • well I’ll put my follow.php file to you see.

  • I edited the question

  • Taking advantage of the topic, if you can help me count followers received in real time... and also in the message, go down for example "wait 30, then wait 29" understood ?

Show 3 more comments

1

As I said, you can define several ways. Some are a little safer and others less, it will depend on your need.

Basic code for changes:

<?php

require_once dirname(__DIR__) . DIRECTORY_SEPARATOR . 'autoload.php';
require_once dirname(__DIR__) . DIRECTORY_SEPARATOR . 'helpers' . DIRECTORY_SEPARATOR . 'TwitterOAuthHelper.php';

$helper = new TwitterOAuthHelper;

$twitterusers = new TwitterUsers;

$verificar = $_GET['verificar'];//Verificar se está apenas consultando
if($verificar == 'S'){
   $ret = verify_user_activity('S'); // Realiza a consulta para verificar se pode ou não mostrar os botões
   die( ($ret ? 'S' : 'N') ); // S = mostrar botões, N = não mostrar
}

if ($user = $helper->signedIn()) {

    verify_user_activity(); //Verifica se está dentro do prazo, caso algum usuário tente burlar o método.

    $fetch = $twitterusers->selectUser($user->screen_name);

    foreach ($fetch as $row) {
        $screen_name[] = $row['screen_name'];
    }

    if ($followers = $helper->getFollowers($screen_name)) {
        echo json_encode([
            "error" => "false",
            "waiting"=>"false",
            "success" => "true",
            "message" => "Seguidores enviados com sucesso, volte em 30 minutos."
        ]);
    }
} else {
    echo json_encode([
            "error" => "true",
            "waiting"=>"false",
            "success" => "false",
            "message" => "You have no open session."
        ]
    );
}
  1. Using $_COOKIE for validation

Example:

function verify_user_activity( $verify = 'N' ){
    if($verify == 'S'){
       if(!empty($_COOKIE['user_last_activity'])){
            $last_time = $_COOKIE['user_last_activity']; //Pega o timestamp

            //Verifica se passou os 30 min
            if($last_time >= time() ) { 
               return true;
            }else {
               //Gera mensagem
               return false;
            } 
      }else{
         return true; 
      }
    }else{
         //Verifica se existe o COOKIE que guarda o timestamp de quando ele pode realizar novamente o comando
        if(!empty($_COOKIE['user_last_activity'])){
           $last_time = $_COOKIE['user_last_activity']; //Pega o timestamp

           //Verifica se passou os 30 min
           if($last_time >= time() ) { 
              $_COOKIE['user_last_activity'] = strtotime("+30 minutes"); //Atualiza a data
           }else {
               //Gera mensagem
               die json_encode([
                "waiting" => "true",
                "message" => "Você não atingiu o tempo mínimo."
               ]);
           }
        }else{
           $_COOKIE['user_last_activity'] = strtotime("+30 minutes"); //Atualiza a data
        }
    }

}
  1. Using IP + Database

Example:

 function verify_user_activity( $verify = 'N' ){    
    /**
        Esta solução se baseia em ter uma tabela no banco de dados
        Com as colunas de:
            IP - ip do usuário
            TIMESTAMP - timestamp de quando ele poderá realizar a operação novamente
    */      
    $user_ip = getUserIP(); // Busca o IP do usuário da requisição
    $con = get_conexao_do_banco_da_sua_escolha(); //Gera conexão com o banco de dados
    $last_time = get_timestamp_do_ip_no_db($user_ip,$con); //Busca da tabela através do IP do usuário

    if($verify == 'S'){
       if(empty($last_time)){
          return true; 
       }else{
           if($last_time >= time() ) { 
              return true;
           }else {
              return false;
           }
        }       
    }else{      
        //Se estiver vazio ou não há registro no banco
        if(empty($last_time)){
           $last_time = strtotime("+30 minutes"); //Atualiza a data
           insere_atualiza_data_do_usuario($user_ip,$last_time,$con); //Guarda a informação no banco de dados
        }else{
           if($last_time >= time() ) { 
              $last_time = strtotime("+30 minutes"); //Atualiza a data
              insere_atualiza_data_do_usuario($user_ip,$last_time,$con);//Guarda a informação no banco de dados
           }else {
              //Gera mensagem 
              die json_encode([
               "waiting" => "true",
               "message" => "Você não atingiu o tempo mínimo."
              ]);
           }
        }
    }   
}

Now, let’s go to Javascript:

If the user reloads the page, all screen data goes back to its original state, so you need to make an initial request to check if you need the button to appear or not.

$(document).ready(function() {
    //Adicionado um parâmetro de verificação
    VerificarSeguidores('V');      
});

You will need to change your function to:

VerificarSeguidores = function(verificar){

    if(typeof verificar == 'undefined') verificar = '';

    var returnType = 'json'; 
    if(verificar == 'S') returnType = 'text';

    $.ajax({
            url: 'api/follow.php?verificar='+verificar,
            dataType: returnType,
            success: function(a) {
                if(verificar == 'S'){
                   if(a != 'S'){
                      //Defina a ação para esconder os botões AQUI
                   }else{  /* APARECER OS BOTÕES AQUI */ }
                }else{
                   1 == a.error ? alert(a.message) : ( 
                     1 == a.waiting ? alert('ESTOU AGUARDANDO 30 minutos') : 
                   (
                   $('.success').css('display', 'block'),
                   $('.success').html(a.message),
                   setTimeout(function(){
                       $('#btnFollow').hide();
                   }, 2e3))
                   )
                }
            }
    }); 
}

In the comment "//Set the action to hide the buttons HERE", do the hiding of the content you want and set a time for the system to check again whether or not to show the button.

1

There are some ways to do this, with pros and cons:

1. Session

Creating a Session, the client has no way to "cheat" because it is created on the server. The problem is that you will have to request the server from time to time to see if the Session has expired.

Pro: the client cannot circumvent. Against: many requests to the server can slow you down.

2. Localstorage (Javascript)

Create a localStorage I think better than working with cookie.

Pro: ease of use. Against: customer can clear via console.

3. Cookie

If done via client or server, the user can delete.

Pro: ease of handling (server side. I have particularly never worked with cookie client side). Against: customer can clear from browser.

My opinion:

Create a Session on the server and a localStorage with the same values. And go checking the localStorage from time to time (e.g. from 1 to 1 minute) and when it is more than 30 minutes, make a request to the server to validate the Session. If the values are equal, release the button. This prevents a joker from changing the localStorage :).

Browser other questions tagged

You are not signed in. Login or sign up in order to post.