Get the attribute of a button with jQuery and Ajax?

4

$(document).ready(function() {

  $(".eliminar").click(function(e) {

    e.preventDefault();
    var id = $(this).attr('data-id');

    //alert(id);
    $(this).closest('.holder-cesta').remove();

    //Esta parte no me funciona.
    $.post('./php/carro_compra/eliminar.php', {
      Id: id
    }, function(a) {
      if (a == '0') {
        location.href = "./cesta";
      }
    });


  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<div class="holder-cesta">
  <h4>Product 1</h4>
  <button class="eliminar" data-id="1">Delete</button>
</div>

<div class="holder-cesta">
  <h4>Product 3</h4>
  <button class="eliminar" data-id="3">Delete</button>
</div>

<div class="holder-cesta">
  <h4>Product 2</h4>
  <button class="eliminar" data-id="2">Delete</button>
</div>

I am creating the boton of removing the products from the basket. Each added product will have a boton to eliminate.

The results of the shopping cart I keep in a session called $_SESSION['carrito'];

Here goes the code where I call the products and their delete button:

<?php
    //Array carrito de compras.
    $data = $_SESSION['carrito'];
    $total = 0;                                     

    for ($i=0; $i<count($data); $i++) {
?>

      <div class="holder-cesta">
         <h4><?php echo $data[$i]['Titulo']; ?></h4>    
         <button class="eliminar" data-id="<?php echo $data[$i]['Id']; ?>">Eliminar</button>    
      </div>
<?php
     }
?>

data-id I get the id product.

Let's look at the jQuery code:

$(document).ready(function() {

    $(".eliminar").click(function(e) {

        e.preventDefault();
        //Obtengo el id desde nuestro boton.
        var id = $(this).attr('data-id');       

        //Mi alert lanza correctamente el id associado.
        //alert(id);
        $(this).closest('.holder-cesta').remove();//Remueve correctamente           
        //AJAX
        //Aqui viene mi problema,no obtengo var id en $.post y tampoco parece que vaya a la url eliminar.php
        $.post('./php/carro_compra/eliminar.php', {
            Id:id
        },function(a) {
            if (a=='0') {
                location.href="./cesta";
            }
        });


    });
});

If I do a var_dump($_POST['Id']); in my file delete.php, I really do not know anything about that function, if I modify a bit the ajax, it sends me a NULL.

The jQuery works fine, since it correctly launches the alert and also eliminates the div.holder-basket, but the problem is as if it never goes to the url of $.post where I want to actuailzar the array through the Id as follows:

if ($arreglo[$i]['Id']!= $_POST['Id']) {

}

I also attach the file delete.php with which I want to update my shopping cart when I delete a product:

  <?php
//Session start
session_start();
//Get shoping cart data.
$arreglo = $_SESSION['carrito'];

for ($i=0; $i<count($arreglo); $i++) { 
    //Logica, si id del articulo es diferente a la variable obtenido por Ajax.
    if ($arreglo[$i]['Id']!= $_POST['Id']) {

        $datosnuevos[] = ['Id' => $arreglo[$i]['Id'], 'Titulo' =>$arreglo[$i]['Titulo'], 'Precio' => $arreglo[$i]['Precio'], 'Icon' => $arreglo[$i]['Icon'], 'Cantidad' => $arreglo[$i]['Cantidad'] ];
    }
}

if (isset($datosnuevos)) {
    //Modifico la sesion, dejando el resto de articulos comprados.
    $_SESSION['carrito'] = $datosnuevos;
    //Modificamos el valor del carro.
    $data = $_SESSION['carrito'];
    $value_carrito = count($data);
    $_SESSION['compras'] = $value_carrito;
    //Asi tambien se recarga la página con los datos actualizado
    echo "0";

} else {
    unset($_SESSION['carrito']);
    unset($_SESSION['compras']);
    echo "0";
}
?>
    
asked by D.Bulten 10.10.2016 в 20:39
source

3 answers

2

cart.php

//Carro de la compra

//Si esta definida la ID obtenido por URL
if (isset($_GET['articulo'])) {

    $id_tutorial = $_GET['articulo'];//Obtenemos el ID del tutorial añadido, para poder acer comprobaciones a mostrar otros resultados.

    //Si esta definido la sesion carro -> es decir si ay algun articulo comprado
    if (isset($_SESSION['carrito'])) {

        $arreglo = $_SESSION['carrito'];
        $encontro = false;      

        for ($i=0; $i<count($arreglo); $i++) { 

            if ($arreglo[$i]['Id'] == $_GET['articulo']) {
                $encontro = true;               
            }
        }

        if ($encontro == false) {


            $titulo = "";
            $precio = 0;
            $precioUSD = 0;
            $icon = "";

            $stmt = $c->prepare("SELECT titulo,precio,icon,id_autor FROM tutoriales WHERE page=? and status=1");
            $stmt->bind_param("i",$_GET['articulo']);
            $stmt->execute();
            $stmt->store_result();
            if ($stmt->num_rows > 0) {
                $stmt->bind_result($titulo,$precio,$icon,$id_autor);
                while ($stmt->fetch()) {

                    //Sentencia prepare -> autor proyecto
                    $stmtN = $c->prepare("SELECT autor FROM autor WHERE id_autor=?");           
                    $stmtN->bind_param("i", $id_autor);         
                    $stmtN->execute();          
                    $stmtN->bind_result($autor);            
                    $stmtN->fetch();            
                    $stmtN->close();

                    $datosnuevos = array('Id' => $_GET['articulo'], 'Titulo' => $titulo, 'Precio' => $precio, 'Icon' => $icon, 'Cantidad' => 1 );

                    /*
                        #Si se utiliza array_push() para añadir un solo elemento al array, es mejor utilizar $array[] = ya que de esta forma no existe la sobrecarga de llamar a una función. 
                    */

                    //array_push($arreglo, $datosnuevos); 
                    $arreglo[] = $datosnuevos;
                    $_SESSION['carrito'] = $arreglo;

                    $data = $_SESSION['carrito'];
                    $value_carrito = count($data);
                    $_SESSION['compras'] = $value_carrito;

                } $stmt->close();


            } else {
                $stmt->close();
            }
        }   

    } else { //Caso falso añadimos primer articulo al carro

        $titulo = "";
        $precio = 0;
        $precioUSD = 0;
        $icon = "";

        $stmt = $c->prepare("SELECT titulo,precio,icon,id_autor FROM tutoriales WHERE page=? and status=1");
        $stmt->bind_param("i",$_GET['articulo']);
        $stmt->execute();
        $stmt->store_result();
        if ($stmt->num_rows > 0) {
            $stmt->bind_result($titulo,$precio,$icon,$id_autor);
            while ($stmt->fetch()) {

                //Sentencia prepare -> autor proyecto
                $stmtN = $c->prepare("SELECT autor FROM autor WHERE id_autor=?");           
                $stmtN->bind_param("i", $id_autor);         
                $stmtN->execute();          
                $stmtN->bind_result($autor);            
                $stmtN->fetch();            
                $stmtN->close();

            } $stmt->close();

        } else {
            $stmt->close();
        }       

            $arreglo[] = array('Id' => $_GET['articulo'], 'Titulo' => $titulo, 'Precio' => $precio, 'Icon' => $icon, 'Cantidad' => 1 );

            $_SESSION['carrito'] = $arreglo;

            $data = $_SESSION['carrito'];
            $value_carrito = count($data);
            $_SESSION['compras'] = $value_carrito;

            //echo "<script>window.location.reload();</script>";


    }

} 

cesta.php Here I call the cart, and where I delete the added items

<?php //Mostramos resultados carro de la compra.

    //Resetemos el total.
    $total = 0;

    //Si esta definido la sesión.
    if (isset($_SESSION['carrito'])) {              

        //Array con datos carrito.
        $data = $_SESSION['carrito'];
        $total = 0;                                     

        //Recorremos todo el array, para salida de datos.
        for ($i=0; $i<count($data); $i++) {
?>

            <div class="holder-cesta">
                <h4><?php echo $data[$i]['Titulo']; ?></h4>
                <p><?php echo $data[$i]['Precio']; ?></p>
                <?php                   
                $total = ($data[$i]['Cantidad'] * $data[$i]['Precio']) + $total;
                ?>

                <button class="eliminar" data-id="<?php echo $data[$i]['Id']; ?>">Eliminar</button>

            </div>

<?php
        }
    } else {
        echo "0 articulos";
    } unset($arreglo);
?>

The eliminar.php file

<?php
//Session start
session_start();
//Get shoping cart data.
$arreglo = $_SESSION['carrito'];

//Reset.
$arr[] ='';


var_dump($arreglo);

//var_dump($_POST['Id']);

for ($i=0; $i<count($arreglo); $i++) { 

    if ($arreglo[$i]['Id']!= $_POST['Id']) {

        //$datosnuevos = ['Id' => $arreglo[$i]['Id'], 'Titulo' =>$arreglo[$i]['Titulo'], 'Precio' => $arreglo[$i]['Precio'], 'Icon' => $arreglo[$i]['Icon'], 'Cantidad' => $arreglo[$i]['Cantidad'] ];
        $arr[] =$arreglo[$i]
    }
}

if (isset($arr)) {

    $_SESSION['carrito'] = $arr;

    $data = $_SESSION['carrito'];
    $value_carrito = count($data);
    $_SESSION['compras'] = $value_carrito;

} else {
    unset($_SESSION['carrito']);
    unset($_SESSION['compras']);
    echo "0";
}
?>
    
answered by 11.10.2016 в 01:45
2

If the content of the cart is added by ajax and jquery, it will not work:

 $(".eliminar").click(function(e) {

Change it to:

 $(document).on("click",'.eliminar', function (event, xhr, settings) {

What is happening to you is that you have a Bind problem from the DOM and a new element.

    
answered by 05.07.2017 в 16:41
0

Good, could it be because you eliminate before doing what you want? First delete:

$(this).closest('.holder-cesta').remove();//Remueve correctamente

and then you want to check the id: Id:id but of course, it does not exist anymore, try first to do everything you want and finally delete what you want:

$(document).ready(function() {

    $(".eliminar").click(function(e) {

        e.preventDefault();
        //Obtengo el id desde nuestro boton.
        var id = $(this).attr('data-id');       

        //Mi alert lanza correctamente el id associado.
        //alert(id);         
        //AJAX
        //Aqui viene mi problema,no obtengo var id en $.post y tampoco parece que vaya a la url eliminar.php
        $.post('./php/carro_compra/eliminar.php', {
            Id:id
        },function(a) {
            if (a=='0') {
                location.href="./cesta";
            }
        });
 $(this).closest('.holder-cesta').remove();//Remueve correctamente 

    });
});
    
answered by 10.10.2016 в 21:42