Capture empty JSON and avoid error

0

I have an AJAX order, which is executed when loading the ticket page, but when entering the first time there are no articles in the session. How is the exception Requested JSON parse failed avoided?

$(document).ready(function() {
   

listarDetalle();
});
function listarDetalle(){
 var accion="listar";
  
$.ajax({
 
        type: "POST",
        url: "//localhost/gestionweb/includes/php/procesoDetalle.php",
        data: { "accion":accion}, 
  dataType:"json",
  
        error: function(){
            alert("error petición ajax");
           
        },
        
        success: function(data){

         if (jQuery.isEmptyObject(data)){alert("sin articulos");}else{ 
         
            $.each(data, function(i, item) {
                       
                       var newRow =
                                        "<tr>" +
                                      
                                        "<td>" + item.id + "</td>" +
                                        "<td>" + item.cantidad + "</td>" +
                                        "<td>" + item.nombre + "</td>" +
                                        "<td>" + item.precio + "</td>" +  
                                        
                                        "<td>" + item.total + "</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("#ticket tbody"); 
                              $("#sub").text(subtotal);
                              $("#IVA").text(iva);
                              $("#total").text(subtotal);
                            
                            
});

}}      

As you can see I try but I can not get it ..

    
asked by Caruso 08.09.2018 в 21:05
source

1 answer

0

You could try

if ( json.length == 0 ) { //COMO SI CONTARAS LA LONGITUD DE CADENA
    console.log("SIN DATOS!")
}

This function can resolve "undefined", it can also be validated by such

if ( json.length == 0 || json.length == undefined ) {

O

if (!json[0]) alert("SIN DATOS!");

This code will work for you when your JSON is an object

jQuery.isEmptyObject()

More info link

Greetings:)

    
answered by 08.09.2018 в 21:13