How to return PHP code with Javascript?

2

Fully edited topic

My file Follow_Button.php :

<?php

require_once '.././app/autoload.php';

$TwitterUsers = new TwitterUsers;

require_once '.././app/TwitterOAuthHelper.php';

$helper = new TwitterOAuthHelper;

$row = $TwitterUsers->selectUserAll();
foreach ($row as $fetch) {
    $helper->friend($fetch['id_user']);
}

My method:

public function friend($user_id) {
    $access_token = $_SESSION['twitter_access_token'];
    $connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, $access_token['oauth_token'], $access_token['oauth_token_secret']);

    $friend = $connection->post("friendships/create", [
        "user_id" => $user_id,
        'follow' => true

    ]);

    if ($user_id === $this->signedIn()->id) {
        return false;
    }

    return $friend;

}

I wanted to limit the PHP code, receive 1 follower every 10 seconds, and count with javascript and when I finished executing the code the reactivate button again:

<a href="" onclick="return getPhpAjax();" class="text-none">
  <button type="button" data-loading-text="Ganhando seguidores..." id="getFollow" class="btn btn-success btn-block">
    <i class="fa fa-refresh"></i> Ganhar seguidores agora
  </button>
</a>

<script type="text/javascript">
  function getPhpAjax() {
   $.ajax({
      url:'./app/Follow_Button.php',
      complete: function (response) {
         $("#getFollow").click(function() {
            var $btn = $(this);
            $btn.button('loading');
         });
      },
      error: function () {
          alert('Erro');
      }
  });  

  return false;
}
</script>
    
asked by anonymous 08.06.2017 / 16:01

1 answer

4

You should zero the button and only after PHP returns that it should be available again.

Try this:

<a href="" onclick="getPhpAjax();" class="text-none">
  <button type="button" data-loading-text="Ganhando seguidores..." id="getFollow" class="btn btn-success btn-block">
    <i class="fa fa-refresh"></i> Ganhar seguidores agora
  </button>
</a>

<script type="text/javascript">

  function enableBtn(state) {

   if(state) { $('#getFollow').text('Loading...').attr('disabled', true) }
   else { $('#getFollow').text('texto original'). attr('disabled', false) }
  }

  function getPhpAjax() {
   enableBtn(false)
   $.ajax({
      url:'./app/Follow_Button.php',
      complete: function (response) {
         var t = setTimeout(function() { enableBtn(true); clearTimeout(t); }, 10000)
      },
      error: function () {
          alert('Erro');
      }
  });  

  return false;
}
</script>

Obviously it's a pretty simple definition because you could just remove the code and it would stop blocking, I advise you to treat the server to not receive requests before 10s.

    
12.06.2017 / 14:46