Return array of objects by AJAX

0

I am developing a sales system, and in the ticket window I have the search button that allows me to go to another page with the list of articles. This consists of two buttons. One is adding that adds the product in question to an array of details of the ticket object (work with MVC and POO), and the other one that returns to the previous window

Class ticket and detail.

<?php
require_once ("includes/claseConexion.php");
require_once ("claseProducto.php");

class detalleTicket{
    
    private $idp;
    private $precio;
    private $cantidad;
    private $nombre;
    private $subtotal;
    
   
   public function __construct($id,$pu,$cant,$nom){
    
    
    $this->idp=$id;
    $this->precio=$pu;
    $this->cantidad=$cant;
    $this->nombre=$nom;
    $this->subtotal= ($this->cantidad * $this->precio);
   
   }
   public function setSubtoal($sub){
    
    $this->subtotal=$sub;
    
   }
   public function actualizaCantidad($nueva){
    
    $this->cantidad=$this->cantidad + $nueva;
    $sub= $this->cantidad * $this->precio;
     $this->setSubtoal($sub);    
    
   }
}
class Ticket{
  private $id;
  private $detalle = array();
  private $fecha;
  private $hora;
  private $total;
  private $stm;
  private $vuelto; 
  
  public function __construct($f,$h){
    
    $this->fecha=$f;
    $this->hora=$h;
    
  }
  public function agregaDetalle($d){
    
    $this->detalle[] = $d;
  } 
  public function setTotal($val){
    
    $this->total=$val;
    
  }
public function listarArt(){
    
  return $this->detalle();
}
public function registrar(){
    //me conecto a la bd
    $conexion = Conexion::singleton_conexion(); 
 try{

    $conexion->beginTransaction();
    $queryid="select comprobante from identificadores;"; 
     $array=$conexion->query($queryid);
   foreach($array as $a){
    $id = $a['comprobante'];
      }
 
  $qnuevoid="UPDATE identificadores SET comprobante=".++$id.";";
  $conexion->query($qnuevoid);
  
        $queryticket="insert into despensa.ticket (idticket, fecha, total,vuelto) values (".$id.",'".$this->fecha."',56,88);";
		$conexion->query($queryticket);

   $conexion->commit();
   
 }catch(Exception $e){
   $conexion->rollBack();
     echo "Fallo: " . $e->getMessage(); 
 }
 

    
}
}


?>

The problem I have is that I want to list the items added to the cart when I return to the page and it gives me a JSON parsing error: REQUESTED JSON PARSE FAILED.

For the same thing I have an intermediate jquery code and a file of poroceso:

$(document).ready(function() {
listarDetalle();

});
function listarDetalle(){
     var accion="listar";
    $.ajax({
       
            type: "POST",
            url: "../gestionweb/includes/php/procesoDetalle.php",
            data: { "accion":accion}, 
            dataType: "json",
            error: function(){
                alert("error petición ajax");
            },
            
            success: function(data){
           content=data;
               for (var i = 0; i < data.length; i++) {
          
                var newRow =
                    "<tr>" +
                    "<td>" + data[i].idproducto + "</td>" +
                    "<td>" + data[i].nombre + "</td>" +
                    "<td>" + data[i].marca + "</td>" +
                    "<td>" + data[i].categoria + "</td>" +
                    "<td>" + data[i].precio + "</td>" +
                    "<td><input type='radio' id='"+data[i].idproducto+"' name='seleccion'/></td>"+
                    "</tr>";
                $(newRow).appendTo("#resultado tbody");                 
       
    
               
            }
        
  

        } 
        
}).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);

  }

});;

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

Bone in the ready of the document ready the articles but it gives me error:

<?php

include ("claseTicket.php");
$ticket = new Ticket($fecha,$hora);

function listarProductos(){
    $arrayarticulos=$ticket->listarArt();
     echo json_encode($arrayarticulos);
    
}
if (isset($_POST['accion'])){
   if ($_POST['accion']="listar"){
       $arrayarticulos=$ticket->listarArt();
     echo json_encode($arrayarticulos);
    
   }else if ($_POST['accion']="agregar"){
    $id = $_POST['id'];
    $precio = $_POST['precio'];
    $cant=$_POST['cantidad'];
    $nom=$_POST['nombre'];
    $registro = new detalleTicket($id,$precio,$cant,$nom);
    $ticket->agregaDetalle($registro);
   } 
}

?>

I really do not know what it can be ... the error is: Error in the request ajax..Requested JSON parse failed.

    
asked by Caruso 18.07.2018 в 19:38
source

4 answers

1

You need to tell the browser that the return headers are formatted with this header('Content-Type: application/json'); instruction Remember that for there to be no errors the array in PHP is recommended be an associative arrangement For example

header('Content-Type: application/json');
$arr = array('foo'=>'Valor foo', 'bar' => 'Valor bar');
echo json_encode( $arr );

This would be your driver code

<?php  
    header('Content-Type: application/json');
    include ("claseTicket.php");
    $ticket = new Ticket($fecha,$hora);

    function listarProductos(){
        $arrayarticulos=$ticket->listarArt();
         echo json_encode($arrayarticulos);

    }
    if (isset($_POST['accion'])){
       if ($_POST['accion']="listar"){
           $arrayarticulos=$ticket->listarArt();
         echo json_encode($arrayarticulos);

       }else if ($_POST['accion']="agregar"){
        $id = $_POST['id'];
        $precio = $_POST['precio'];
        $cant=$_POST['cantidad'];
        $nom=$_POST['nombre'];
        $registro = new detalleTicket($id,$precio,$cant,$nom);
        $ticket->agregaDetalle($registro);
       } 
    }

    ?>

That it serves you

    
answered by 18.07.2018 в 21:58
0

Try formatting the json.

 function listarDetalle(){
     var accion="listar";
    $.ajax({
            type: "POST",
            url: "../gestionweb/includes/php/procesoDetalle.php",
            data: JSON.stringify({accion}), 
            dataType: "json",
            error: function(){
                alert("error petición ajax");
            },
            success: function(data){
           content=data;
               for (var i = 0; i < data.length; i++) {
                var newRow =
                    "<tr>" +
                    "<td>" + data[i].idproducto + "</td>" +
                    "<td>" + data[i].nombre + "</td>" +
                    "<td>" + data[i].marca + "</td>" +
                    "<td>" + data[i].categoria + "</td>" +
                    "<td>" + data[i].precio + "</td>" +
                    "<td><input type='radio' id='"+data[i].idproducto+"' name='seleccion'/></td>"+
                    "</tr>";
                $(newRow).appendTo("#resultado tbody");    
            }
        } 
    
answered by 18.07.2018 в 20:10
0

Try doing a parse to data in the success method:

content = JSON.parse(data);
    
answered by 18.07.2018 в 21:37
0

I found some errors that I autocorrijo, the method add detail the variable $ d is type detalleticket:

 public function agregaDetalle(detalleTicket $d){
    
    $this->detalle[] = $d;
  } 
In listArt, it does not have parentheses because it is not a function, it is a variable:

public function listarArt(){
    
  return $this->detalle;
}
Then the array of articles is declared with square brackets:

$arrayarticulos[]=$ticket->listarArt();

And another question is if I want to add several ticket details that I have to change so that the value is not stepped

    
answered by 25.07.2018 в 10:30