Include registration and return disabled button without refresh

Asked

Viewed 97 times

0

I made a button adicionar amigo, as in social networks, except that I use form to do this, it sends the user to another page. Wanted some dynamic way without updating the page, when clicking the button is made the Insert in the database and returns the disabled button not letting the user to trigger the button more than once.

This is the page where the user adds a user:

php friends.

<a class="btn btn-primary" amigo_id="<?php echo $id; ?>">Adicionar amigo</a>

When clicking the button would have to run this file in the background without updating the page.

add-friend.php

<?php 


session_start();

$conn = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
$conn->set_charset("utf8");

if ($conn->connect_error) {
    die("<font color='red'>A conexão falhou: </font>" . $conn->connect_error);
} 

$sql = "INSERT INTO amigos (id_usuario,id_amigo,data_adc)
VALUES ('$_SESSION[UsuarioID]', '$_GET[id]', now() )";

if ($conn->query($sql) === TRUE) {
    echo "Amigo adicionado!";
} else {
    echo "Erro: " . $sql . "<br>" . $conn->error;
}

1 answer

2


First put a class on the button to identify you to the javascript:

<a class="btn btn-primary botao-adicionar-amigo" amigo_id="<?php echo $id; ?>">Adicionar amigo</a>

Now use that class as selector in the event click:

    $(".botao-adicionar-amigo").click(function() {

      var amigo_id = $(this).attr('amigo_id'); //Capturando o atributo amigo_id

     //Post ajax para sua página php, sem refresh
     $.ajax({
       type: "GET",
       url: "adicionar-amigo.php",
       data: {id: amigo_id},
       success: function(resposta){
          console.log(resposta);
       }
     });

      //Esconde o botão
      $(this).css('display','none'); 

    });

Here is the documentation of the post via ajax https://api.jquery.com/jquery.post/

On your page php keep doing the same thing. It won’t change anything.

You may need to treat the return in some specific way, in the example above it is being returned to the browser console, but you can do it the way you prefer.

The button, after executing the function click will receive the attribute hidden of css. You can also switch to the one that is best for your scenario.

Browser other questions tagged

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