Get POST variable in php and AJAX in the same form, PHP SELF

0

Hi, I have this problem, I have a canvas which serves as a signature for documents that are sent to the same form where you are with phpself , but at the time of doing the conversion in ajax to send it as string of image , nothing brings me the variable that I receive by POST, in simple words. this is the code:

AJAX:

jQuery(document).ready(function($){
  var canvas = document.getElementById("firma");
  var signaturePad = new SignaturePad(canvas);

  $('#limpiar').on('click', function(){
      signaturePad.clear();
  });

  $('.enviado').on('click', function(){
    var dataURI = signaturePad.toDataURL("image/jpg")
    alert(dataURI);

    $.ajax({
        method: "post",
        url: "cortesias_view.php",
        data: { firma: dataURI }
    }); 
  });
});

PHP form}:

<form id="formu" name="formu" method="post" action="<?php $_SERVER['PHP_SELF']?>">

Reception of POST variables:

if (!empty($_POST['enviado'])) {
  $fecha = $_POST['theDate'];
  $folio = $_POST['folio'];
  $concepto = $_POST['concepto'];

  $clasificacion=$_POST['clasicacion'];
  $lugar=$_POST['lugar'];
  $firma=$_POST['firma'];
  echo 'firma: '.$firma;
  $solicitante = $_POST['solicitante'];
}

Submit button:

 <td><input type="submit" name="enviado" class="enviado" id="enviado" value="GUARDAR" class="boton" /></td>

Canvas HTML:

<canvas id="firma" class="firma" name="firma" width="150" height="50" style="border: 2px solid #000;"></canvas>
    
asked by ricardo torres 07.02.2017 в 16:54
source

1 answer

2

You are using AJAX, you are not doing a usual submit. For this reason, you are only sending firma in the body of the request. Therefore, enviado does not exist in $_POST so it never enters the conditional.

You must send all the values of the form. Since you use jQuery, use serializeArray to serialize the form to an array and send it to the backend:

$('.enviado').on('click', function(){
  var dataURI = signaturePad.toDataURL("image/jpg");
  var data = $('#formu').serializeArray();

  $.ajax({
    method: "post",
    url: "cortesias_view.php",
    data: {
      data: data,
      firma: dataURI
    }
  }); 
});

In the backend you must parse this array as a string to a PHP array. You do this by using json_decode :

$data = json_decode($_POST['data']);

if ($data['enviado']) {
  $fecha = $data['theDate'];
  $folio = $data['folio'];
  $concepto = $data['concepto'];
  $clasificacion = $data['clasicacion'];
  $lugar = $data['lugar'];
  $solicitante = $data['solicitante'];
  $firma = $_POST['firma']; // aquí si usas $_POST
}
    
answered by 07.02.2017 в 17:10