Read elements of a JSON in shopping cart session

0

I have a class code that works perfectly coded, along with AJAX adds and elminates articles, and works with sessions.

But it happens that I want to add a client to the operation either for a discount, or to associate the sale.

In the ready of my .js I have

$(document).ready(function() {
    $('#factura').on('click','input', function(evt){
    var idp=$('input:radio[name=seleccionado]:checked').val()
    alerta(idp);
});
listarDetalle();
listarCliente();

where listDetail shows the articles and listClient the associated customer if it exists. They both call the same script:

function listarCliente(){
    var accion="obtener";
    
    $.ajax({
            type: "POST",
            url: "//localhost/gestionweb/includes/php/procesoFactA.php",
            data: { "accion":accion}, 
        dataType:"json",

            error: function(){
                alert("error petición ajax");
               
            },
            
            success: function(cli){
              console.log(cli);
                        
              
                                
}
   
}).fail( function( jqXHR, textStatus, errorThrown ) {

  if (jqXHR.status === 0) {

    alert('Not connect: Verify Network.');

  } else if (jqXHR.status == 404) {

    alert('Requested page not found [404]');
  

  } else if (jqXHR.status == 500) {

    alert('Internal Server Error [500].');

  } else if (textStatus === 'parsererror') {

    alert('Requested JSON parse failed.');

  } else if (textStatus === 'timeout') {

    alert('Time out error.');

  } else if (textStatus === 'abort') {

    alert('Ajax request aborted.');

  } else {

    alert('Uncaught Error: ' + jqXHR.responseText);

  }

});

        
    
}
function listarDetalle(){
     var accion="listar";
      
    $.ajax({
     
            type: "POST",
            url: "//localhost/gestionweb/includes/php/procesoFactA.php",
            data: { "accion":accion}, 
      dataType:"json",
      
            error: function(){
                alert("error petición ajax");
               
            },
            
            success: function(data){
                            
            if (typeof data==="object"){
                $.each(data, function(i, item) {
                        base=item.total * item.alicuota /100;
                        totalgral=base + item.total;
                           var newRow =
                                            "<tr>" +
                                          
                                            "<td>" + item.id + "</td>" +
                                            "<td>" + item.cantidad + "</td>" +
                                            "<td>" + item.nombre + "</td>" +
                                            "<td>" + item.precio + "</td>" +  
                                            
                                            "<td>" + item.total + "</td>" +
                                            "<td>" + item.alicuota + "</td>" +
                                            "<td>" + base + "</td>" +
                                              "<td>" + totalgral + "</td>" +
                                          
                                            "<td><input type='radio' id='"+item.id+"' name='seleccionado' value='"+item.id+"'/></td>"+
                                            "</tr>";
                                    subtotal=subtotal + item.total; 
                                     iva=(subtotal *0.21);     
                                     total=subtotal - iva;
                                        $(newRow).appendTo("#factura tbody"); 
                                        if (item.alicuota==10.50){
                                            ali1=ali1 + base;
                                        }else if (item.alicuota==21.00){
                                            ali2=ali2 + base;
                                        }else if (item.alicuota==27.00){
                                            ali3=ali3 + base;
                                        }
                                        totalfact=totalfact + totalgral;
                                  $("#sub1").text(ali1);
                                  $("#sub2").text(ali2);
                                  $("#sub3").text(ali3);
                                  $("#IVA").text(iva);
                                  $("#total").text(totalfact);
                                });
                                
}}}).fail( function( jqXHR, textStatus, errorThrown ) {

  if (jqXHR.status === 0) {

    alert('Not connect: Verify Network.');

  } else if (jqXHR.status == 404) {

    alert('Requested page not found [404]');
  

  } else if (jqXHR.status == 500) {

    alert('Internal Server Error [500].');

  } else if (textStatus === 'parsererror') {

    alert('Requested JSON parse failed.');

  } else if (textStatus === 'timeout') {

    alert('Time out error.');

  } else if (textStatus === 'abort') {

    alert('Ajax request aborted.');

  } else {

    alert('Uncaught Error: ' + jqXHR.responseText);

  }

});

};

But I get undefined in a row of the detail table of the invoice. This is because the client that remains in the data is not an object of invoice type or JSON chain. It is a loose data.

In what way can I not list it and use it or how should I model the code:

 <?php

session_start();
include_once ($_SERVER['DOCUMENT_ROOT'].'/gestionweb/models/claseCliente.php');

class Carritoa
{
    //aquí guardamos el contenido del carrito
    private $carrito = array();
    //seteamos el carrito exista o no exista en el constructor
    public function __construct()
    {
        if(!isset($_SESSION["carritoa"]))
        {
            $_SESSION["carritoa"] = null;
            $this->carrito["precio_total"] = 0;
            $this->carrito["articulos_total"] = 0;
        }
        $this->carrito = $_SESSION['carritoa'];
    }
    //añadimos un producto al carrito
    public function add($articulo = array())
    {
        //primero comprobamos el articulo a añadir, si está vacío o no es un 
        //array lanzamos una excepción y cortamos la ejecución
        if(!is_array($articulo) || empty($articulo))
        {
            throw new Exception("Error, el articulo no es un array!", 1);
        }
        //nuestro carro necesita siempre un id producto, cantidad y precio articulo
        if(!$articulo["id"] || !$articulo["cantidad"] || !$articulo["precio"])
        {
            throw new Exception("Error, el articulo debe tener un id, cantidad y precio!", 1);
        }
        //nuestro carro necesita siempre un id producto, cantidad y precio articulo
        if(!is_numeric($articulo["id"]) || !is_numeric($articulo["cantidad"]) || !is_numeric($articulo["precio"]))
        {
            throw new Exception("Error, el id, cantidad y precio deben ser números!", 1);
        }
        //debemos crear un identificador único para cada producto
        $unique_id = md5($articulo["id"]);
        //creamos la id única para el producto
        $articulo["unique_id"] = $unique_id;
        //si no está vacío el carrito lo recorremos 
       if(!empty($this->carrito))
        {
            foreach ($this->carrito as $row)
            {
                //comprobamos si este producto ya estaba en el 
                //carrito para actualizar el producto o insertar
                //un nuevo producto    
                if($row["unique_id"] === $unique_id)
                {
                    //si ya estaba sumamos la cantidad
                    $articulo["cantidad"] = $row["cantidad"] + $articulo["cantidad"];
                }
            }
        }
        //evitamos que nos pongan números negativos y que sólo sean números para cantidad y precio
        $articulo["cantidad"] = trim(preg_replace('/([^0-9\.])/i', '', $articulo["cantidad"]));
        $articulo["precio"] = trim(preg_replace('/([^0-9\.])/i', '', $articulo["precio"]));
        //añadimos un elemento total al array carrito para 
        //saber el precio total de la suma de este artículo
        $articulo["total"] = $articulo["cantidad"] * $articulo["precio"];
        //primero debemos eliminar el producto si es que estaba en el carrito
        $this->unset_producto($unique_id);
        ///ahora añadimos el producto al carrito
        $_SESSION["carritoa"][$unique_id] = $articulo;
        //actualizamos el carrito
        $this->update_carrito();
        //actualizamos el precio total y el número de artículos del carrito
        //una vez hemos añadido el producto
        $this->update_precio_cantidad();
    }
    //método que actualiza el precio total y la cantidad
    //de productos total del carrito
    private function update_precio_cantidad()
    {
        //seteamos las variables precio y artículos a 0
        $precio = 0;
        $articulos = 0;
        //recorrecmos el contenido del carrito para actualizar
        //el precio total y el número de artículos
        foreach ($this->carrito as $row)
        {
            $precio += ($row['precio'] * $row['cantidad']);
            $articulos += $row['cantidad'];
        }
        //asignamos a articulos_total el número de artículos actual
        //y al precio el precio actual
        $_SESSION['carrito']["articulos_total"] = $articulos;
        $_SESSION['carrito']["precio_total"] = $precio;
        //refrescamos él contenido del carrito para que quedé actualizado
        $this->update_carrito();
    }
    //método que retorna el precio total del carrito
    public function precio_total()
    {
        //si no está definido el elemento precio_total o no existe el carrito
        //el precio total será 0
        if(!isset($this->carrito["precio_total"]) || $this->carrito === null)
        {
            return 0;
        }
        //si no es númerico lanzamos una excepción porque no es correcto
        if(!is_numeric($this->carrito["precio_total"]))
        {
            throw new Exception("El precio total del carrito debe ser un número", 1);
        }
        //en otro caso devolvemos el precio total del carrito
        return $this->carrito["precio_total"] ? $this->carrito["precio_total"] : 0;
    }
    //método que retorna el número de artículos del carrito
    public function articulos_total()
    {
        //si no está definido el elemento articulos_total o no existe el carrito
        //el número de artículos será de 0
        if(!isset($this->carrito["articulos_total"]) || $this->carrito === null)
        {
            return 0;
        }
        //si no es númerico lanzamos una excepción porque no es correcto
        if(!is_numeric($this->carrito["articulos_total"]))
        {
            throw new Exception("El número de artículos del carrito debe ser un número", 1);
        }
        //en otro caso devolvemos el número de artículos del carrito
        return $this->carrito["articulos_total"] ? $this->carrito["articulos_total"] : 0;
    }
    //este método retorna el contenido del carrito
    public function get_content()
    {
        //asignamos el carrito a una variable
        $carrito = $this->carrito;
        //debemos eliminar del carrito el número de artículos
        //y el precio total para poder mostrar bien los artículos
        //ya que estos datos los devuelven los métodos 
        //articulos_total y precio_total
        unset($carrito["articulos_total"]);
        unset($carrito["precio_total"]);
        return $carrito;
    }
    //método que llamamos al insertar un nuevo producto al 
    //carrito para eliminarlo si existia, así podemos insertarlo
    //de nuevo pero actualizado
    private function unset_producto($unique_id)
    {
        unset($_SESSION["carritoa"][$unique_id]);
    }
    //para eliminar un producto debemos pasar la clave única
    //que contiene cada uno de ellos
    public function remove_producto($unique_id)
    {
        //si no existe el carrito
        if($this->carrito === null)
        {
            throw new Exception("El carrito no existe!", 1);
        }
        //si no existe la id única del producto en el carrito
        if(!isset($this->carrito[$unique_id]))
        {
            throw new Exception("La unique_id $unique_id no existe!", 1);
        }
        //en otro caso, eliminamos el producto, actualizamos el carrito y 
        //el precio y cantidad totales del carrito
        unset($_SESSION["carritoa"][$unique_id]);
        $this->update_carrito();
        $this->update_precio_cantidad();
        return true;
    }
    //eliminamos el contenido del carrito por completo
    public function destroy()
    {
        unset($_SESSION["carritoa"]);
        $this->carrito = null;
        return true;
    }
    //actualizamos el contenido del carrito
    public function update_carrito()
    {
        self::__construct();
    }
  public function agregaCliente($idc){
    if(!isset($_SESSION["carritoa"]))
        {
             

            $_SESSION["cliente"] = $idc;
          

   }
  
}
}

$carrito = new Carritoa();
if ($_POST['accion']=='asociar'){
    if (isset($_POST["idc"])){
        $id=$_POST["idc"];

            $_SESSION["carritoa"]["idc"] = $id;}

}
if ($_POST['accion']=='listar'){
    $c=$carrito->get_content();
    echo json_encode($c);
   
}else if ($_POST['accion']=='agregar'){

       
    $articulo = array(
    "id"=>$_POST["id"],
    "cantidad"=>$_POST["cantidad"],
    "nombre"=>$_POST["nombre"]. " " . $_POST["marca"],
    "precio"=>$_POST["precio"],
    "alicuota"=>$_POST["alicuota"],
    
    ); 
   
    $carrito->add($articulo);
}else if ($_POST["accion"]=='eliminar'){
    $id=$_POST['id'];
    $carrito->remove_producto(md5($id));
}else if ($_POST["accion"]=='obtener'){
  $idc=$_SESSION["carritoa"]["idc"];
  $cliente1=new Cliente();
  $c1=$cliente1->Obtener($idc);
  echo json_encode($c1);
    
}

?> 

Any suggestions?

    
asked by Caruso 11.09.2018 в 18:44
source

0 answers