generate a post with an ajax and then send another ajax with post to another

Viewed 31

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

1 Answers

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

Related