Onclick and AJAX event to update database

1

I want to do the following. When clicking on a link, a onclick event is executed and the database is updated with AJAX.

PHP Code

if ($mencion['seccion'] == "noticia") {
   if ($mencion['leido'] == 0) {
      echo sprintf(
        '<a class="mencion" rel="nofollow" data-idmencion="%s" data-id="%s" data-foro="%s" data-subforo="%s" data-asunto="%s" data-pagina="%s" class="leido" href="%s"><strong>%s</strong></a>',
         $id_mencion,
         $id_hilo,
         str_replace(" ", "%",$mencion['foro']),
         $mencion['subforo'],
         limpia_url($informacion_hilo[0]['titulo']),
         $mencion['pagina_hilo'],
         $ruta . "noticia/" . $id_hilo . "/" . limpia_url($informacion_hilo[0]['titulo']) . "/",
         $informacion_hilo[0]['titulo']
      );
      ?>
      <script>
         document.querySelector('.mencion').addEventListener('click', function leido (event) {
         var idmencion = this.dataset.idmencion
         // Prevent the default link behaviour, i.e. the redirect
         event.preventDefault()

         $.ajax ({
            type: 'POST',
            url: 'process_leido.php',
            data: { "idmencion": idmencion },
            success: function(data){
            location.href = "<?php echo $ruta ?>noticia/" + idmencion + "/<?php echo limpia_url($informacion_hilo[0]['titulo']) ?>/";
         }
       })
      })
      </script>
      <?php
   } else {
       echo "<a class='mencion' rel='nofollow' href=''>" . $informacion_hilo[0]['titulo'] . "</a>";
   }
}

This generates the following HTML code:

<a class="mencion" rel="nofollow" data-idmencion="56" data-id="161" data-foro="-" data-subforo="-" data-asunto="Need-For-Speed-Payback-lo-nuevo-de-Ghost-Games-y-Electronic-Arts" data-pagina="0" href="http://localhost/xboxone/noticia/161/Need-For-Speed-Payback-lo-nuevo-de-Ghost-Games-y-Electronic-Arts/" style="color: rgb(124, 6, 32);"><strong>Need For Speed Payback, lo nuevo de Ghost Games y Electronic Arts</strong></a>

The code where AJAX runs:

session_start();

require 'admin/config.php';

try {
   $conexion = new PDO($bd_config['dbname'], $bd_config['usuario'], $bd_config['password'] );
} catch (Exception $e) {
   echo "Error: " . $e->getMessage();
}

$id = isset($_POST['idmencion'])? $_POST['idmencion'] : 0;

$statement = $conexion->prepare("UPDATE menciones SET leido = 1 WHERE id = :id");
$statement->execute(array(":id" => $id));
    
asked by JetLagFox 04.06.2017 в 21:00
source

1 answer

1

A type link < a href > does not send a POST to the controller of the associated url. Therefore, you will not be able to read the parameter with POST on the server side. You can do it in these ways:

SENDING A GET WITH A LINK

The way to do this with a link is to generate it with a parameter in the url, such as:

<a href="http://localhost/MyGame?idmencion=10"><strong>Delete</strong></a>

With this, the php will arrive in the _GET field idmencion with the value 10. You can pick it up with:

$id = isset($_GET['idmencion'])? $_GET['idmencion'] : 0;

SEND PUT IN FORM

If we put ourselves a bit more stringent, the most correct thing would be to send a form with the PUT method to the url. Your code, instead of generating a link should generate something like:

<form method="PUT" action="http://localhost/MyGame">
<input type="hidden" name="idmencion" value="10">
<input type="submit"> name="borrar">
</form>

And in your php, control the PUT method:

if ($_METHOD="PUT") {
    $id = isset($_REQUEST['idmencion'])? $_REQUEST['idmencion'] : 0;

    $statement = $conexion->prepare("UPDATE menciones SET leido = 1 WHERE id = :id");
    $statement->execute(array(":id" => $id));
}
    
answered by 05.06.2017 в 09:36