0

I am trying to print on a thermal printer, this, after performing a query and obtaining certain data, which I send to a hidden input, the problem is that I do not know how to insert and use the second ajax post to my file php for printing, I am using the Mike42 ECPOS library. would you be so kind to guide me?

function calcCredits(){
      /* variables from inputs */
      var last_credit= parseInt(document.getElementById("studentcredits").value);
      var namesec= document.getElementById("studentqr").value;
      var credits= parseInt(document.getElementById("money").value);
      var total_pay = credits * 35;
      var ttl_credits = last_credit + credits;
      /* Beggin Ajax */
        $.ajax({

          url:'addcredits.php',
          type:'post',
          data:{namesec:namesec,credits:credits},

          success:function(data){
            $.ajax({
                url: 'ticket.php',
                type: 'POST',
                success: function(response){
                      alert('Printing....');
                  } 
                }); 
            }
        });
      }

this is the php that performs the search and shows the results

<?php


require 'database.php';
$con = new Database();
$pdo = $con->conectar();
$campo = $_POST["campo"];

$sql = "SELECT * FROM students WHERE student_qr LIKE ? OR student_secondname LIKE ? ORDER BY student_secondname ASC LIMIT 0, 10";
$query = $pdo->prepare($sql);
$query->execute([$campo . '%', $campo . '%']);

$html = "";
$data_query['result'] = $html;

while ($row = $query->fetch(PDO::FETCH_ASSOC)) {
    $html .= "
    <div class=\"container-fluid \">  
        <div class=\"row\">
            <div class=\"col-lg-12\">
                <table class=\"table table-hover\">
                    <tr >
                        <th scope='col'>Grupo</th>
                        <th scope='col'>Nombre</th>
                        <th scope='col'>Créditos</th>
                    </tr>
                    <tr>
                        <td id='list_id'>".$row["student_group"]."</td>
                        <td id='list_id'>".$row["student_name"]." ".$row["student_secondname"]." ".$row["student_lastname"]."</td>
                        <td id='list_name'>".$row["student_credits"]."</td> 
                        <td id='list_credits' style=\"cursor: pointer\" onclick=\"mostrar('" .$row["student_qr"] ."'), mostrar2('" .$row["student_credits"] ."')\"><button type='button' class='btn btn-warning' id= 'show' onclick='show()' >Añadir Creditos</button></td>
                    </tr>
                </table>
            </div>
        </div>
    </div>
        
    ";
}

echo json_encode($html, JSON_UNESCAPED_UNICODE);

and this is for printing

<?php


require __DIR__ . '/ticket/autoload.php'; 
use Mike42\Escpos\Printer;
use Mike42\Escpos\EscposImage;
use Mike42\Escpos\PrintConnectors\WindowsPrintConnector;

$nombre_impresora = "POS"; 
$connector = new WindowsPrintConnector($nombre_impresora);
$printer = new Printer($connector);

$printer->setJustification(Printer::JUSTIFY_CENTER);

    $printer->setJustification(Printer::JUSTIFY_LEFT);
    $printer->text("Producto Galletas\n");
    $printer->text( "2  pieza    10.00 20.00   \n");

$printer->setJustification(Printer::JUSTIFY_CENTER);
$printer->text("Muchas gracias por su compra\n");

$printer->feed(3);

$printer->close();

?>

sorry if it is not well structured I'm still practicing, thanks

  • If I understand the issue correctly, then just make one call to some PHP file that fetches the data and prints it. If that's not what you're asking/having issues with, please clarify. It's a bit unclear since you've tagged the question with php, mysql and ajax, but only show the Ajax request (which is in JavaScript) but no PHP or MySQL. Also, is the printer connected to the client or the server? – M. Eriksson Sep 22 '22 at 22:00
  • 2
    From the code i see `location.reload()` is being called outside of the ajax success function. I suspect that may be the reason why your ajax calls fails. But need more info on the error you are facing – itssajan Sep 22 '22 at 22:17
  • Hello, the printer is connected to the server, the problem is that I don't know how to send the query data to the php for printing, I have removed the location.reload() part, for testing –  Sep 22 '22 at 23:37
  • I have added most of the code hoping you can help me –  Sep 22 '22 at 23:42
  • @GeorginaQ Can you check if this is useful for you? https://stackoverflow.com/questions/51933513/jquery-usage-of-done-then-and-when-for-making-ajax-requests-in-a-giv – Babitha Sep 23 '22 at 17:04

1 Answers1

0

After the comments and contributions that helped me a lot, I noticed that my mistake was to forward the info to another file, when the printing could be treated within the first insertion php, so I added the ticket code and that's it.

this is the ajax function

function calcCredits(){
      
          $.ajax({
            /* Se envian datos por POST a PHP */
            url:'addcredits.php',
            type:'post',
            dataType: 'json',
            data:{
              studentqr:$('#studentqr').val(),
              credits:$('#credits').val(),
            },         
          })
          .always(function(){
              console.log("complete");
          });
      }   

and then, the php insert

<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
include("conection.php");
include("ticket/autoload.php");

$credits = mysqli_real_escape_string($con, $_POST['credits']);
$studentqr = mysqli_real_escape_string($con, $_POST['studentqr']);


$stmt = $con->prepare("UPDATE students 
  SET student_credits = (student_credits + ?) 
  WHERE student_qr = ?");
$stmt->bind_param("is", $_POST['credits'], $_POST['studentqr']);
$stmt->execute();

$insert_query = $con->prepare("INSERT INTO historical_credits (id_student, credits_paid)
    SELECT id_student, ?
    FROM students
    WHERE student_qr = ?");
$insert_query->bind_param("is", $_POST['credits'], $_POST['studentqr']);
$insert_query->execute();


use Mike42\Escpos\Printer;
use Mike42\Escpos\EscposImage;
use Mike42\Escpos\PrintConnectors\WindowsPrintConnector;

$nombre_impresora = "Termica"; 
$connector = new WindowsPrintConnector($nombre_impresora);
$printer = new Printer($connector);

$printer->setJustification(Printer::JUSTIFY_CENTER);

    $printer->setJustification(Printer::JUSTIFY_LEFT);
    $printer->text("Producto Galletas\n");
    $printer->text( "2  pieza    10.00 20.00   \n");

$printer->setJustification(Printer::JUSTIFY_CENTER);
$printer->text("Muchas gracias por su compra\n");

$printer->feed(3);

$printer->close();

$archivoActual = $_SERVER['PHP_SELF'];
header("refresh:2;url= + $archivoActual ");
mysqli_close($con);

?>

thanks a lot for your time