Search code examples
javascriptphpajaxpostresponse

PHP dont receive data from ajax


i have a problem with ajax and PHP. When i try to send data from ajax to PHP, ajax seems work, because a alert show data correctly (although during a short time, next dissapear), but in my php file dont show any data (i inspect with developers tools and nothing result) this is my ajax script

$(document).ready(function() {
    $('#tabla_eventos').on('click', '#guardar_bt', function(e) {
        e.preventDefault(); 
        var filaactual = $(this).closest("tr"); 
        var id_evento = filaactual.find("td:eq(0)").html(); 
        var parametros = {
            id_evento : id_evento
        };
        $.ajax({
            method:  'POST', 
            data:  parametros, 
            url:   'detalle_evento.php', 
            success:  function (response) {
                        location.href='detalle_evento.php';
                        alert('bien'+' '+id_evento);
                      }
        });
    });
});

and this is my php file:

<?php
session_start();
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <h1>
    <?php
    echo $_POST['id_evento'];
    ?>
    </h1>
</body>
</html>

Solution

  • The problem is with this line in your code:

    location.href='detalle_evento.php';
    

    Just after script receive data from ajax the page is reloading with empty data in POST (because the reload is a GET request).

    If you want to use this data in this way then add this code to your HTML (in body section).

    <form action="detalle_evento.php" method="post" id="someform">
      <input type="hidden" name="id_evento" id="id_evento" value="<?= $_POST['id_evento'] ?>">
    </form>
    

    and use this JS code

    document.getElementById("id_evento").value = id_evento;
    document.getElementById("someform").submit();
    

    instead of this part of your code

    $.ajax({
            method:  'POST', 
            data:  parametros, 
            url:   'detalle_evento.php', 
            success:  function (response) {
                        location.href='detalle_evento.php';
                        alert('bien'+' '+id_evento);
                      }
        });