How to do click counter in PHP, MySQL and AJAX?

2

Okay, my question is to make a clicks or likes counter so that when someone clicks a <div> this add the click to a <span> anywhere in the article. This means that, if I have a new click on a photo, I put the total number of people who clicked on that photo, in the span of "I like it" without updating the page. And that I can handle it by id s so that I can have many "likeable" photos. I have seen the odd issue about this from the outside but I have not been able to adapt it to what I need. I do not have much knowledge in PHP. And here is a basic example of my code.

$(document).ready(function(){

  $(this).find(".img-hover").mouseenter(function(){
  
    $(this).css({"background-color": "rgba(255, 255, 255, 0.5)"});
    $(this).find("i").css({"color": "rgb(27, 27, 28)"});
    $(this).find("i").stop().removeClass("fa-2x");
    $(this).find("i").stop().addClass("fa-4x");
    $(this).find("span").stop().fadeIn(200);
  
  });
  
  $(this).find(".img-hover").mouseleave(function(){
  
    $(this).css({"background-color": "rgba(0, 0, 0, 0)"});
    $(this).find("i").css({"color": "rgba(0, 0, 0, 0)"});
    $(this).find("i").stop().removeClass("fa-4x");
    $(this).find("i").stop().addClass("fa-2x");
    $(this).find("span").stop().fadeOut(200);
  
  });
  
  $(this).find(".fa-heart").mouseenter(function(){
  
    $(this).css({"color": "rgb(234, 96, 86)"});
    
  });
  
  $(this).find(".fa-heart").mouseleave(function(){
  
    $(this).css({"color": "rgb(27, 27, 28)"});
    
  });

});
*{
 padding: 0;
 margin: 0;
 font-family: sans-serif;
}

.contenedor {
 position: relative;
 width: 250px;
 height: 450px;
}

img {
 max-width: 100%;
 position: absolute;
}

.img-hover {
 width: 100%;
 height: 99%;
 position: absolute;
 top: 0;
 left: 0;
 z-index: 100;
 transition: .2s;
 background-color: rgba(0, 0, 0, 0);
 text-align: center;
}

.fa-heart {
 color: rgba(0, 0, 0, 0);
 position: absolute;
 top: 40%;
 left: 40%;
 transition: .2s;
}

.fa-heart:hover {
 cursor: pointer;
}

.cuenta {
 padding: 3px 8px;
 background-color: rgb(247, 247, 247);
 border-radius: 3px;
 color: rgb(27, 27, 28);
 font-size: 12px;
 right: 0;
 bottom: 0;
 margin-right: 5px;
 margin-bottom: 6px;
 position: absolute;
 display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://use.fontawesome.com/acad8e21f9.js"></script>
<div class="contenedor">
  <img src="https://s-media-cache-ak0.pinimg.com/736x/0f/61/18/0f6118f167ccca50dff9e06f5b27146b.jpg" alt="img">
  <div class="img-hover">
    <!--Este es el "div" del click-->
    <i class="fa fa-heart fa-2x"></i>
    <!--Este es el "span" del resultado-->
    <span class="cuenta">716</span>
  </div>
</div>
    
asked by Dєηyη Crawford 22.06.2017 в 23:48
source

2 answers

0

What I do is simply mount an IFRAME that runs in background ie invisible with CSS index: -1 then send the requests with target | Use PHP |

<?php


// $id es el ID de la imagen que has sacado de la base de datos o simplemente asignale uno


echo "<a href='count.php?id=".$id."' target='myframe'><img src='img.jpg'></a>";

?>

I imagine that the ids of the image are generated when loading the images of the database.

    
answered by 23.06.2017 в 21:05
0

Possible answer, EYE , I have not tested it, it may contain faults, it is made by eye:

EXAMPLE HTML

<div id="clickLike">LIKE</div><!-- poner por ejemplo un corazon como en instagram, que se ponga en rojo si el usuario le dio like-->
<span id="totalLikes"></span>

JS

$("#clickLike").on("click",(evt)=>{
  evt.preventDeault();
  $.ajax({
    url : "archivoQueManejaLikes.php",
    method: "POST", //o GET, la diferencia es que se vean los datos o no en el enlace
    data : {
      "idPublicacion" : /*Asignarle una id, o introducirla en tu html y después recibirla $("elementoQueGuardaId").attr("idAlgo")*/ "algo",
          ,"idUsuario" : /*LA ID DEL USUARIO QUE DA LIKE para que no le dé infinitos*/"algo"}
  }).done((data)=>{
    //El dato debería ser el número de likes y posiblemente la id del artículo
    var datos = JSON.parse(data); //Es conveniente siempre comunicarse mediante json
    $("totalLikes").text(datos.likes);//por ejemplo
  });
});

PHP

if(isset($_POST['idPublicacion']) && isset($_POST['idUsuario'])){
  manejaLikes($_POST['idPublicacion'], $_POST['idUsuario']);
}

function manejaLikes($pub, $usr){
  $conn = new Mysqli (/*DATOS CONEXION A BASE DE DATOS*/);
  //primero intentemos saber si el usuario ya dio like en la publicación, a lo mejor lo que quiere es retirarlo
  //saber si han funcionado El delete o el insert
  $operacionDI = false;
  $sql ="SELECT * from likes WHERE id_usuario = ".$usr." AND id_publicacion = ".$pub;
  $result = $conn->query($sql);
  if($result){
    if($result->num_rows > 0){
      //el usuario ya habia dado like, eliminar el like
      $delete = "DELETE FROM likes where id_usuario = ".$usr." AND id_publicacion = ".$pub;
       $result2 = $conn->query($delete);
        if($result2){
          $operacionDI = true;
        }
    }else{
      $insert = "INSERT INTO likes (id_usuario, id_publicacion) values (".$usr.", ".$pub.")";
       $result3 = $conn->query($insert);
        if($result3){
          $operacionDI = true;
        }
    }
  }
  if($operacionDI){
    $likes = "select count(*) from likes where id_publicacion = ".$pub;
    $resultFinal = $conn->query($likes);
    if($resultFinal){
      $data = [];
      $data['likes'] = $resultFinal->fetch_array()[0];
      echo json_encode($data,JSON_FORCE_OBJECT);
    }
  }
}

I hope it serves as a reference to do what you ask, is an example similar to what you want, there are shots:)

    
answered by 24.05.2018 в 08:58