1

I have a function to save data to database and then I show a success/error message. The data gets saved as expected but the message is not shown to the user (modal doesn't appear on screen) and I have no idea why.

What I return from php is a json with two variables.

If I don't save data and just send the message the modal is shown with no error, but if I save the data, the modal does not appear on screen.

Can Someone tell me why is that?

function GrabarCompra()
{
    $GuardarModifcarFactura=$_POST['btnFactura'];

    $FK_Usuario=$_SESSION['IDUsuario'];

    $GuarMod='';
    $Respuesta=''; 

    if($GuardarModifcarFactura=='GrabarFactura')
    {
        $IDCompra=0;

        $ClaveHacienda=$_POST['NoClaveDoc'];
        $NumeroConsecutivo=substr($_POST['NoClaveDoc'],21,20);
        $TipoDocumento=ObtenerTipoDocumentoNumerico($_POST['TipoDocumento']);
        $FechaEmision= DateTime::createFromFormat('d-m-Y', $_POST['Fecha'])->format('Y-m-d H:i:s');
        $ActividadEconomica=$_POST["ActividadEconomica"];

        //Emisor

        $NombreEmisor=$_POST["NombreEmisor"];
        $CedulaEmisor=$_POST["CedulaEmisor"];

        //Receptor

        $NombreReceptor=$_POST["NombreReceptor"];
        $CedulaReceptor=$_POST["CedulaReceptor"];

        //Otros Datos
        $CondicionVenta=$_POST['CondicionVenta'];   
        $Plazo=$_POST['Plazo'];

        $CodigoMoneda=$_POST['TipoMoneda'];
        $TipoCambio=$_POST['TipoCambio'];
        $TotalServGravados=QuitarFormatoNumero($_POST['MontSGF']);
        $TotalServExentos=QuitarFormatoNumero($_POST['MontSEF']);
        $TotalServExonerados=QuitarFormatoNumero($_POST['MontSExoF']);
        $TotalMercanciasGravadas=QuitarFormatoNumero($_POST['MontGrF']);
        $TotalMercanciasExentas=QuitarFormatoNumero($_POST['MontExF']);
        $TotalMercanciasExoneradas=QuitarFormatoNumero($_POST['MontExoF']);

        $TotalGravado=bcdiv(($TotalServGravados+$TotalMercanciasGravadas),1,2);
        $TotalExento=bcdiv(($TotalServExentos+$TotalMercanciasExentas),1,2);
        $TotalExonerado=bcdiv(($TotalServExonerados+$TotalMercanciasExoneradas),1,2);

        $TotalVenta=bcdiv(($TotalGravado+$TotalExento+$TotalExonerado),1,2);
        $TotalDescuentos=QuitarFormatoNumero($_POST['MontDescF']);
        $TotalVentaNeta=QuitarFormatoNumero($_POST['MontSubF']);
        $TotalImpuesto=QuitarFormatoNumero($_POST['MontIVF']);

        $TotalComprobante= QuitarFormatoNumero($_POST['MontTF']);       

        $ImpuestoDevuelto= QuitarFormatoNumero($_POST['MontIVDF']);


       $MedioPago= "01";      

       $Terminal= substr($NumeroConsecutivo,0,3);
       $Sucursal= substr($NumeroConsecutivo,3,5);

       $Conexion = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);

        if ($Conexion->connect_error) 
        {
            die("Connection failed: " . $Conexion->connect_error);
        } 

        $sql="INSERT INTO Compra 
              (FK_Usuario,FK_Cliente,Fecha,Status,
                        ClaveLarga,
                        Secuencia,
                        ClaveHacienda,
                        NumeroConsecutivoHacienda,
               TipoDocumento,NombreEmisor,NombreComercialEmisor,TipoEmisor,NombreReceptor,CedulaReceptor,TipoReceptor,
               CondicionVenta,Plazo,MedioPago,CodigoMoneda,TipoCambio,Mensaje,TotalServGravados,TotalServExentos,
               TotalServExonerados,TotalMercanciasGravadas,TotalMercanciasExentas,TotalMercanciasExoneradas,TotalGravado,
               TotalExento,TotalExonerado,TotalVenta,TotalDescuentos,TotalVentaNeta,TotalImpuesto,TotalComprobante,
               FK_ActividadEconomica)
               VALUES
               ($FK_Usuario,'$CedulaEmisor','$FechaEmision','','','','$ClaveHacienda','$NumeroConsecutivo','$TipoDocumento',
                '$NombreEmisor','$NombreComercialEmisor','','$NombreReceptor','$CedulaReceptor','','$CondicionVenta',$Plazo,
                '$MedioPago','$CodigoMoneda',$TipoCambio,'',$TotalServGravados,$TotalServExentos,$TotalServExonerados,
                $TotalMercanciasGravadas,$TotalMercanciasExentas,$TotalMercanciasExoneradas,$TotalGravado,$TotalExento,
                $TotalExonerado,$TotalVenta,$TotalDescuentos,$TotalVentaNeta,$TotalImpuesto,$TotalComprobante,
                $ActividadEconomica);";

        if($Conexion->query($sql) === TRUE) 
        { 
            $Respuesta="Documento guardado correctamente";           
            $GuarMod='Guardo';
        }
        else
        {
          $Respuesta= "Error al guardar el documento";
          $GuarMod='Error';
        }
    }
            $users_arr[] = array( 
                             "Respuesta"=>$Respuesta,
                             "GuarMod"=>$GuarMod,
                         );

        // encoding array to json format
        echo json_encode($users_arr);
        exit;    
}

Ajax

$.ajax({
                      url: 'Logica/Compra.php',
                      type: 'post',
                      data: 
                      {
                         btnFactura:TipoBoton,

                         /*Campos de encabezado de Factura*/

                         /*Emisor*/

                         CedulaEmisor:document.getElementById('Cedula').value,
                         NombreEmisor:document.getElementById('Nombre').value,

                         /*Receptor*/
                         CedulaReceptor:document.getElementById('CedulaReceptor').value,
                         NombreReceptor:document.getElementById('NombreReceptor').value,                     

                         IDFactura:document.getElementById('IDFactura').value,
                         NoFactura:document.getElementById('NoFactura').value,
                         NoClaveDoc:document.getElementById('NoClaveDoc').value,
                         Fecha:document.getElementById('Fecha').value,
                         Plazo:document.getElementById('Plazo').value,

                         ActividadEconomica:'null',

                         MedioPago:MP,

                         CondicionVenta:document.getElementById('CondicionVenta').value,
                         TipoMoneda:document.getElementById('TipoMoneda').value,
                         TipoCambio:document.getElementById('TipoCambio').value,
                         Sucursal:document.getElementById('Sucursal').value,
                         Terminal:document.getElementById('Terminal').value,
                         TipoDocumento:document.getElementById('TipoDocumento').value,/*01=Factura 02=NotaDebito 03=Nota Credito 04=Tiquete*/

                         DetalleFactura:TableData,

                         /*Campos de Calculos*/
                         MontSEF:document.getElementById('MontoSEF').value,
                         MontSGF:document.getElementById('MontoSGF').value,
                         MontSExoF:document.getElementById('MontoSExoF').value,
                         MontExF:document.getElementById('ExentoF').value,
                         MontGrF:document.getElementById('GravadoF').value,
                         MontExoF:document.getElementById('ExoneradoF').value,
                         MontSubF:document.getElementById('SubF').value,
                         MontDescF:document.getElementById('DescF').value,
                         MontIVF:document.getElementById('ImpuestoVentasF').value,
                         MontIVDF:document.getElementById('ImpuestoVentasDevueltoF').value,
                         MontOImpF:document.getElementById('OImpF').value,
                         MontTF:document.getElementById('TotalF').value,

                         Saldo: Saldo,
                      },
                      dataType:'json',
                    success : function(response){

                        var len =response.length;

                        if(len>0)
                        {
                            var Respuesta=response[0]['Respuesta'];
                            var GuarMod=response[0]['GuarMod'];

                            $("#MSJ").html(Respuesta);
                            $("#ModalMSJ").modal("show");

                            sessionStorage.setItem('GuarMod',GuarMod);
                        }
                    }
                  });

                  return false;
Roly
  • 161
  • 1
  • 5
  • 18
  • Are you sure your code enter in `if($GuardarModifcarFactura=='GrabarFactura')`? – Manzolo Aug 19 '19 at 17:42
  • I am very sure of it. I have debugged the code line by line and everyting works as expected. and even the `$users_arr[]` gets poulated. But the modal is not showing on screen and no error is shown in console either – Roly Aug 19 '19 at 17:51
  • It would really help to see your Javascript – Patrick Q Aug 19 '19 at 17:54
  • Can you post ajax call? – Manzolo Aug 19 '19 at 17:54
  • I added the AJAX code – Roly Aug 19 '19 at 17:56
  • 1
    View the response in your browser's network inspector. Make sure that there _is_ actually a response, _and_ that it is valid JSON. Also check the Javascript console for errors. – Patrick Q Aug 19 '19 at 18:09
  • take a look to [how can i use jquery to post json data](https://stackoverflow.com/questions/6255344/how-can-i-use-jquery-to-post-json-data) – gaetanoM Aug 19 '19 at 18:22
  • 1
    after the success callback add error: function (jqXHR, exception) {..... in order to see if an error happens... – gaetanoM Aug 19 '19 at 18:27
  • @gaetanoM I did what you said and the console shows this: `SyntaxError: Unexpected token < in JSON at position 0` – Roly Aug 19 '19 at 19:28
  • 1
    @Roly That means what you're getting back is HTML, not JSON. This is likely due to an error being thrown. As I already suggested, you should view the raw response in your network inspector. – Patrick Q Aug 19 '19 at 20:12
  • @PatrickQ I had no idea I could use that to see the error. Thank you so much, I was strugling with this problem since 4 days ago. My Code was right the problem was a notice from php because there was an undefined variable. – Roly Aug 19 '19 at 20:29

0 Answers0