Ajax, limit time even by reloading the page

0

I have the code that does what it has to do, and at the end 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, the message says: "Successfully sent followers, come back in 30 minutes."

I would like the button to go back automatically after 30 minutes without updating the page, and if you update before 30 minutes the message is still there. How to do it correctly?

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."
        ]
    );
}
    
asked by anonymous 29.07.2017 / 14:21

4 answers

3

You need to call api/follow.php also onready on the page; ie when reloading the page it re-checks the status of time 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 this to monitor the elapsed time, if it is longer 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 is called again the ajax routine and releases the button. The cookie would avoid sending unnecessary requests to the server.

    
31.07.2017 / 16:18
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();
})
    
31.07.2017 / 21:13
1

As I said, you can define it in several ways. Some are a little more secure and some less, it will depend on your need.

Base 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."
        ]
    );
}
  • 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
            }
        }
    
    }
    
  • 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 the data on the screen will return to the original state, so you will have 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');      
    });
    

    With this 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," perform the hiding of the content you want and set a time for the system to check again whether or not to show the button.

        
    02.08.2017 / 22:15
    1

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

    1. Session

    Creating a session, the client can not "cheat" because it is created on the server. The problem is that you will have to keep making requests to the server from time to time to see if the session has expired.

    Pro: the client can not 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. Contra: the client can clean via console.

    3. Cookie

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

    Pro: ease of handling (server side. I've particularly never worked with client side cookie). Contra: client can clear from browser.

    My opinion:

    Create a session on the server and a localStorage with the same values. And check the localStorage from time to time (eg every 1 minute) and when it is longer than 30 minutes, make a request to the server to validate the session. If the values are the same, release the button. This prevents a joker from changing the localStorage:).

        
    02.08.2017 / 23:34