0

Al intentar hacer un insert en una tabla me arroja el siguiente Notice:

Notice: Undefined variable: iva in C:\xampp\htdocs\remision\ajax\editar_facturacion.php on line 17

y no agrega el Valor del IVA

$(document).ready(function(){
            load(1);
            $( "#resultados" ).load( "ajax/editar_facturacion.php" );
        });

function load(page){
            var q= $("#q").val();
            $("#loader").fadeIn('slow');
            $.ajax({
                url:'./ajax/productos_factura.php?action=ajax&page='+page+'&q='+q,
                 beforeSend: function(objeto){
                 $('#loader').html('<img src="./img/ajax-loader.gif"> Cargando...');
              },
                success:function(data){
                    $(".outer_div").html(data).fadeIn('slow');
                    $('#loader').html('');

                }
            })
}

function agregar (id)
        {
            var precio_venta=document.getElementById('precio_venta_'+id).value;
            var cantidad=document.getElementById('cantidad_'+id).value;
            var iva=document.getElementById('iva_'+id).value;
            //Inicia validacion
            if (isNaN(cantidad))
            {
            alert('Esto no es un numero');
            document.getElementById('cantidad_'+id).focus();
            return false;
            }
            if (isNaN(precio_venta))
            {
            alert('Esto no es un numero');
            document.getElementById('precio_venta_'+id).focus();
            return false;
            }
            if (isNaN(iva))
            {
            alert('Esto no es un numero');
            document.getElementById('iva_'+id).focus();
            return false;
            }
            //Fin validacion

            $.ajax({
        type: "POST",
        url: "./ajax/editar_facturacion.php",
        data: "id="+id+"&precio_venta="+precio_venta+"&iva="+iva+"&cantidad="+cantidad,
         beforeSend: function(objeto){
            $("#resultados").html("Mensaje: Cargando...");
          },
        success: function(datos){
        $("#resultados").html(datos);
        }
            });
}

function eliminar (id)
        {

            $.ajax({
        type: "GET",
        url: "./ajax/editar_facturacion.php",
        data: "id="+id,
         beforeSend: function(objeto){
            $("#resultados").html("Mensaje: Cargando...");
          },
        success: function(datos){
        $("#resultados").html(datos);
        }
            });

        }

        $("#datos_factura").submit(function(event){
          var id_cliente = $("#id_cliente").val();

          if (id_cliente==""){
              alert("Debes seleccionar un cliente");
              $("#nombre_cliente").focus();
              return false;
          }
            var parametros = $(this).serialize();
             $.ajax({
                    type: "POST",
                    url: "ajax/editar_factura.php",
                    data: parametros,
                     beforeSend: function(objeto){
                        $(".editar_factura").html("Mensaje: Cargando...");
                      },
                    success: function(datos){
                        $(".editar_factura").html(datos);
                    }
            });

             event.preventDefault();
        });

        $( "#guardar_cliente" ).submit(function( event ) {
          $('#guardar_datos').attr("disabled", true);

         var parametros = $(this).serialize();
             $.ajax({
                    type: "POST",
                    url: "ajax/nuevo_cliente.php",
                    data: parametros,
                     beforeSend: function(objeto){
                        $("#resultados_ajax").html("Mensaje: Cargando...");
                      },
                    success: function(datos){
                    $("#resultados_ajax").html(datos);
                    $('#guardar_datos').attr("disabled", false);
                    load(1);
                  }
            });
          event.preventDefault();
        })

        $( "#guardar_producto" ).submit(function( event ) {
          $('#guardar_datos').attr("disabled", true);

         var parametros = $(this).serialize();
             $.ajax({
                    type: "POST",
                    url: "ajax/nuevo_producto.php",
                    data: parametros,
                     beforeSend: function(objeto){
                        $("#resultados_ajax_productos").html("Mensaje: Cargando...");
                      },
                    success: function(datos){
                    $("#resultados_ajax_productos").html(datos);
                    $('#guardar_datos').attr("disabled", false);
                    load(1);
                  }
            });
          event.preventDefault();
        })

function imprimir_factura(id_factura){
            VentanaCentrada('./pdf/documentos/ver_factura.php?id_factura='+id_factura,'Factura','','1024','768','true');
        }

y aqui el Ajax:

   <?php
include('is_logged.php');//Archivo verifica que el usario que intenta acceder a la URL esta logueado
$id_factura= $_SESSION['id_factura'];
$numero_factura= $_SESSION['numero_factura'];
if (isset($_POST['id'])){$id=intval($_POST['id']);}
if (isset($_POST['cantidad'])){$cantidad=floatval($_POST['cantidad']);}
if (isset($_POST['iva'])){$iva=floatval($_POST['iva']);}
if (isset($_POST['precio_venta'])){$precio_venta=floatval($_POST['precio_venta']);}

    /* Connect To Database*/
    require_once ("../config/db.php");//Contiene las variables de configuracion para conectar a la base de datos
    require_once ("../config/conexion.php");//Contiene funcion que conecta a la base de datos
    //Archivo de funciones PHP
    include("../funciones.php");
if (!empty($id) and !empty($cantidad) and !empty($precio_venta))
{
$insert_tmp=mysqli_query($con, "INSERT INTO detalle_factura (numero_factura, id_producto, cantidad, iva, precio_venta) VALUES ('$numero_factura','$id','$cantidad','$iva','$precio_venta')");

}
if (isset($_GET['id']))//codigo elimina un elemento del array
{
$id_detalle=intval($_GET['id']);    
$delete=mysqli_query($con, "DELETE FROM detalle_factura WHERE id_detalle='".$id_detalle."'");
}
$simbolo_moneda=get_row('perfil','moneda', 'id_perfil', 1);
?>
<table class="table">
<tr>
    <th class='text-center'>CODIGO</th>
    <th class='text-center'>CANT.</th>
    <th>DESCRIPCION</th>
    <th class='text-right'>PRECIO UNIT.</th>
    <th class='text-right'>IVA</th>
    <th class='text-right'>PRECIO TOTAL</th>
    <th></th>
</tr>
<?php
    $sumador_total=0;
    $sumador_total2=0;
    $sumador_iva=0;
    $sql=mysqli_query($con, "select * from products, facturas, detalle_factura where facturas.numero_factura=detalle_factura.numero_factura and  facturas.id_factura='$id_factura' and products.id_producto=detalle_factura.id_producto");
    while ($row=mysqli_fetch_array($sql))
    {
    $id_detalle=$row["id_detalle"];
    $codigo_producto=$row['codigo_producto'];
    $cantidad=$row['cantidad'];
    $nombre_producto=$row['nombre_producto'];

    $precio_sin_iva=$row['subtotal'];
    $precio_sin_iva_f=number_format($precio_sin_iva,2);//Formateo variables
    $precio_sin_iva_r=str_replace(",","",$precio_sin_iva_f);//Reemplazo las comas
    $precio_total2=$precio_sin_iva_r*$cantidad;
    $precio_total2_f=number_format($precio_total2,2);//Precio total formateado
    $precio_total2_r=str_replace(",","",$precio_total2_f);//Reemplazo las comas
    $sumador_total2+=$precio_total2_r;//Sumador del precio sin iva

    $precio_venta=$row['precio_venta'];
    $precio_venta_f=number_format($precio_venta,2);//Formateo variables
    $precio_venta_r=str_replace(",","",$precio_venta_f);//Reemplazo las comas
    $precio_total=$precio_venta_r*$cantidad;
    $precio_total_f=number_format($precio_total,2);//Precio total formateado
    $precio_total_r=str_replace(",","",$precio_total_f);//Reemplazo las comas
    $sumador_total+=$precio_total_r;//Sumador

    $iva=$row['iva'];
    $iva_f=number_format($iva,2);//Formateo variables
    $iva_r=str_replace(",","",$iva_f);//Reemplazo las comas
    $iva_total=$iva_r*$cantidad;
    $iva_total_f=number_format($iva_total,2);//Precio total formateado
    $iva_total_r=str_replace(",","",$iva_total_f);//Reemplazo las comas
    $sumador_iva+=$iva_total_r;//Sumador iva

        ?>
        <tr>
            <td class='text-center'><?php echo $codigo_producto;?></td>
            <td class='text-center'><?php echo $cantidad;?></td>
            <td><?php echo $nombre_producto;?></td>
            <td class='text-right'><?php echo $precio_sin_iva_f;?></td>
            <td class='text-right'><?php echo $iva_f;?></td>
            <td class='text-right'><?php echo $precio_total_f;?></td>
            <td class='text-center'><a href="#" onclick="eliminar('<?php echo $id_detalle ?>')"><i class="glyphicon glyphicon-trash"></i></a></td>
        </tr>       
        <?php
    }
    $impuesto=get_row('perfil','impuesto', 'id_perfil', 1);
    $subtotal=number_format($sumador_total,2,'.','');
    $total_iva=($subtotal * $impuesto )/100;
    $total_iva=number_format($total_iva,2,'.','');
    $total_factura=$subtotal+$total_iva;
    $update=mysqli_query($con,"update facturas set total_venta='$total_factura' where id_factura='$id_factura'");
?>
<tr>
    <td class='text-right' colspan=4>SUBTOTAL <?php echo $simbolo_moneda;?></td>
    <td class='text-right'><?php echo number_format($sumador_total2,2);?></td>
    <td></td>
</tr>
<tr>
    <td class='text-right' colspan=4>IVA <?php echo $simbolo_moneda;?></td>
    <td class='text-right'><?php echo number_format($sumador_iva,2);?></td>
    <td></td>
</tr>
<tr>
    <td class='text-right' colspan=4>AGREGADO (<?php echo $impuesto;?>)% <?php echo $simbolo_moneda;?></td>
    <td class='text-right'><?php echo number_format($total_iva,2);?></td>
    <td></td>
</tr>
<tr>
    <td class='text-right' colspan=4>TOTAL <?php echo $simbolo_moneda;?></td>
    <td class='text-right'><?php echo number_format($total_factura,2);?></td>
    <td></td>
</tr>

</table>

y aqui la estructura de la base base

Y aca el Input

<?php
include('is_logged.php');//Archivo verifica que el usario que intenta acceder a la URL esta logueado
/* Connect To Database*/
require_once ("../config/db.php");//Contiene las variables de configuracion para conectar a la base de datos
require_once ("../config/conexion.php");//Contiene funcion que conecta a la base de datos

$action = (isset($_REQUEST['action'])&& $_REQUEST['action'] !=NULL)?$_REQUEST['action']:'';
if($action == 'ajax'){
    // escaping, additionally removing everything that could be (html/javascript-) code
     $q = mysqli_real_escape_string($con,(strip_tags($_REQUEST['q'], ENT_QUOTES)));
     $aColumns = array('codigo_producto', 'nombre_producto' );//Columnas de busqueda
     $sTable = "products";
     $sWhere = "";
    if ( $_GET['q'] != "" )
    {
        $sWhere = "WHERE (";
        for ( $i=0 ; $i<count($aColumns) ; $i++ )
        {
            $sWhere .= $aColumns[$i]." LIKE '%".$q."%' OR ";
        }
        $sWhere = substr_replace( $sWhere, "", -3 );
        $sWhere .= ')';
    }
    include 'pagination.php'; //include pagination file
    //pagination variables
    $page = (isset($_REQUEST['page']) && !empty($_REQUEST['page']))?$_REQUEST['page']:1;
    $per_page = 5; //how much records you want to show
    $adjacents  = 4; //gap between pages after number of adjacents
    $offset = ($page - 1) * $per_page;
    //Count the total number of row in your table*/
    $count_query   = mysqli_query($con, "SELECT count(*) AS numrows FROM $sTable  $sWhere");
    $row= mysqli_fetch_array($count_query);
    $numrows = $row['numrows'];
    $total_pages = ceil($numrows/$per_page);
    $reload = './index.php';
    //main query to fetch the data
    $sql="SELECT * FROM  $sTable $sWhere LIMIT $offset,$per_page";
    $query = mysqli_query($con, $sql);
    //loop through fetched data
    if ($numrows>0){

        ?>
        <div class="table-responsive">
          <table class="table">
            <tr  class="warning">
                <th>Código</th>
                <th>Producto</th>
                <th><span class="pull-right">Cant.</span></th>
                <th><span class="pull-right">Precio</span></th>
                <th><span class="pull-right">IVA</span></th>
                <th class='text-center' style="width: 36px;">Agregar</th>
            </tr>
            <?php
            while ($row=mysqli_fetch_array($query)){
                $id_producto=$row['id_producto'];
                $codigo_producto=$row['codigo_producto'];
                $nombre_producto=$row['nombre_producto'];
                $precio_venta=$row["precio_producto"];
                $precio_venta=number_format($precio_venta,2,'.','');
                $iva=$row["iva"];
                $iva=number_format($iva,2,'.','');
                ?>
                <tr>
                    <td><?php echo $codigo_producto; ?></td>
                    <td><?php echo $nombre_producto; ?></td>
                    <td class='col-xs-1'>
                    <div class="pull-right">
                    <input type="text" class="form-control" style="text-align:right" id="cantidad_<?php echo $id_producto; ?>" value="1" >
                    </div></td>
                    <td class='col-xs-2'><div class="pull-right">
                    <input type="text" class="form-control" style="text-align:right" id="precio_venta_<?php echo $id_producto; ?>" value="<?php echo $precio_venta;?>" readonly >
                    </div></td>
                    <td class='col-xs-2'><div class="pull-right">
                    <input type="text" class="form-control" style="text-align:right" id="iva_<?php echo $id_producto; ?>" value="<?php echo $iva;?>" readonly>
                    </div></td>
                    <td class='text-center'><a class='btn btn-info'href="#" onclick="agregar('<?php echo $id_producto ?>')"><i class="glyphicon glyphicon-plus"></i></a></td>
                </tr>
                <?php
            }
            ?>
            <tr>
                <td colspan=5><span class="pull-right">
                <?php
                 echo paginate($reload, $page, $total_pages, $adjacents);
                ?></span></td>
            </tr>
          </table>
        </div>
        <?php
    }
}
?>

Espero Me puedan ayudar por que llevo horas rompiéndome el coco con esto. De antemano muchas gracias.

8
  • 1
    te recomiendo que empieces a depurar paso a paso... de principio al fin.. y así destacas donde puede estar el fallo... también echaría un vistazo sobre SQLi... el 11 dic. 2017 a las 6:48
  • ¿Puedes poner el html en el que debería haber un input con el "iva_venta"? el 11 dic. 2017 a las 7:45
  • Listo! Muchisimas Gracias, ya estuve revisando linea por linea y no encuentro el problema. P.D. La variable la Cambie solo por IVA en la base de datos tambien el 11 dic. 2017 a las 8:46
  • Te faltó explicar que el error te lo da en el ajax. Los otros scripts son más bien de presentación de data
    – ffflabs
    el 11 dic. 2017 a las 11:44
  • Traté de indentar un poco mejor el código...
    – ffflabs
    el 11 dic. 2017 a las 11:47

1 respuesta 1

0

No veo la consulta que haces a la base de datos, pero creo que tu problema está en el nombre del campo dela base de datos.

En la base de datos el campo se llama "iva_venta" y tu lo estas intentando sacar con sólo "iva".

Cambia $iva=$row["iva"]; por $iva=$row["iva_venta"];

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge you have read our privacy policy.

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.