Click counter with ajax and PHP

3

I would like to know if you have an example of how to count a click in a label <a></a> and that% click is stored in a database so that after the total number of times clicked is counted. < br> In the network you can find but with forms and what I want to do is without form, only one that on a label goes to java or ajax and send it to PHP without recharging the page. p>     

asked by DanielDaniel 09.08.2018 в 18:58
source

1 answer

1

You could do it with the $.ajax() method of jQuery. For example:

index.html

<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title></title>
    <script type="text/javascript" src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
    <script type="text/javascript" src="main.js"></script>
  </head>
  <body>
    <h1>Ejemplo</h1>
    <a href="https://es.stackoverflow.com/">stackoverflow</a>
  </body>
</html>

main.js

// una vez que termine de cargar el dom
$(document).ready(function() {
  // selector del link
  var a = $('#stackoverflow');

  // evento click del link
  // también se puede usar a.click(function(e) {})
  a.on('click', function(e) {
    // esto es sólo un ejemplo de cómo pasar parámetros
    var id_row = 1;

    // método ajax para contar el click
    $.ajax({
      url: 'contador.php',
      type: 'post',
      data: {id: id_row},
      // en caso de éxito de la petición
      success: function(data) {
        console.log(data);
      }
    })
  })
});

contador.php

<?php

// obtengo el id del $_POST
$id = $_POST["id"];

// acá debería estar la conexión a la DB
$mysqli = new mysqli("127.0.0.1", "mi_usuario", "mi_contraseña", "mi_bd");

// incremento en la db el contador
$query = $mysqli->query("UPDATE contadores SET click=click + 1 WHERE id = $id");

$msg = array('msg' => 'error');
if ($query === TRUE) {
  $msg['msg'] = 'success');
}

// esto es importante, la información que devuelve tiene que ser siempre un json
echo json_encode($msg);

// cierro la conexión
$mysqli->close();

?>
    
answered by 09.08.2018 / 19:36
source