AJAX does not run with element a with href indicated

2

Good morning,

I am using a small script to update my database when I click on a link. That link has an onclick event. At the beginning to see the values that I was giving in the console, I did not have any links. Once seen that it worked, when putting the link, something happens, since the database is not modified.

The HTML code referring to the link:

echo "<a rel='nofollow' onclick='leido(" . $id_mencion . ")' href='foro.php?foro=" . $mencion['foro'] . "&subforo=" . $mencion['subforo'] . "&hilo=" . str_replace(" ", "%",$informacion_hilo[0]['asunto']) . "&ID=" . $id_hilo . "&pagina=" . $mencion['pagina_hilo'] . "'><strong>" . $informacion_hilo[0]['asunto'] . "</strong></a>";

The Script:

<script>
function leido(respuesta_id) {
 var id_respuesta = respuesta_id;
 console.log(id_respuesta);

    $.ajax ({
      type: 'POST',
      url: 'process_leido.php',
      data: { "id_respuesta":id_respuesta }
    });

};
</script>

I also put the code of process_leido.php:

<?php

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['id_respuesta'])? $_POST['id_respuesta'] : 0;

$statement = $conexion->prepare("UPDATE menciones SET leido = 1 WHERE id = :id");
$statement->execute(array(":id" => $id));


?>

However, if I modify the link to and remove the content of the href parameter, it works:

echo "<a rel='nofollow' onclick='leido(" . $id_mencion . ")' href='#'><strong>" . $informacion_hilo[0]['asunto'] . "</strong></a>";

I looked and looked back and I do not see where the error is. In fact, the link is correct.

EDIT:

This is the HTML that PHP generates:

<div class="info_hilo">
    <a rel="nofollow" onclick="leido(16)" href="foro.php?foro=Xbox%One&subforo=General&hilo=Primer%trailer%oficial%de%Destiny%2&ID=45&pagina=0"><strong>Primer trailer oficial de Destiny 2</strong></a>                                       
    <p class="creador">GoitxoCv</p>
</div>
    
asked by JetLagFox 02.04.2017 в 22:23
source

2 answers

1

The behavior of a anchor (a) in an HTML document is redirecting the browser to the resource it points to. As you are pointing to an address, the browser will be redirected obeying said a .

To avoid this, use preventDefault jQuery :

Html:

echo "<a rel='nofollow' onclick='leido(event, \"" . $id_mencion . "\")'...>"

JS:

leido = function(e, respuesta_id){
    e.preventDefault();
    ...
}

EDIT

To redirect the browser you only have to include a location.href when the ajax has returned a successful result:

$.ajax ({
    type: 'POST',
    url: 'process_leido.php',
    data: { "id_respuesta":id_respuesta },
    // A partir de aquí
    success: function(data){
        location.href = '<? echo "foro.php?foro=" . $mencion['foro'] . "&subforo=" . $mencion['subforo'] . "&hilo=" . str_replace(" ", "%",$informacion_hilo[0]['asunto']) . "&ID=" . $id_hilo . "&pagina=" . $mencion['pagina_hilo']" ?>';
    },
    error: function(err){
        console.log(err); //  O cualquier cause que quieras dar
                          //   en caso de que el AJAX fracase
    }
});
    
answered by 03.04.2017 / 21:44
source
0

When I need to pass parameters through the URL, to manipulate it in PHP, and send an answer, try to manipulate this code, the important thing is to send the correct parameters by the URL and then from the server you will achieve whatever is with the values that you come in.

<?php
       echo "<a href='leido.php' id='leido'></a>"
       ?>
        <script>
        $("#leido").click(
                function(event){
                    var cURL = $(this).attr('href')+"?foro=<?php echo $mencion['foro'] ?>"+"&subforo=<?php echo $mencion["subforto"] ?>"+"&hilo=<?php echo str_replace(" ", "%", $informacion_hilo[0]["asunto"]) ?>"+"&ID=<?php echo $id_hilo ?>"+"&pagina=<?php echo $mencion["pagina_hilo"] ?>";                   
                    $.ajax({
                        url:'process_leido.php'+''+cURL+'',
                        type:"GET",
                        data: cURL,
                        cache: false,
                        success: function(data){
                            //CODE HERE
                        },
                        error: function(data){
                            console.log(data);
                        }
                    });
                    return false;
                });
        </script>

You can debug with the function and the parameter (data) to see what the server responds to, this code always works for me, I do not know how your variables are built, but the key is also to send the parameters with an echo, of what otherwise it will not work.

PS: I'm using Jquery

    
answered by 03.04.2017 в 19:57