Pass a javascript variable to php without input [duplicate]

0

Hello everyone, please, if someone can help me, I need to pass a javascript variable to php .. I have this function

    <script type="text/javascript">
     function operacion(field) {
     var form = field.parentNode; 
     var numero1 = form.cantidad.value;         
     var numero2 = form.precio.value;         
     form.total.value = ( numero1 * numero2 ); 
      }    
    </script>

and prints the result in the total input

   <td><label>Total</label></td>
   <td><input align="right" type="text" name="total"></td>

What I want is for that total javascript variable to print something like this

 <?php
  echo $total = aqui quiero que aparezca la variable total del javascript sin el input;
  ?>

If someone can help me, I thank you very much in advance ...

    
asked by Jhon Di 05.10.2018 в 16:09
source

1 answer

0

You can do it using $.ajax of jQuery, for example:

Javascript script.js

$.ajax({
  method: 'post',
  url: 'ejemplo.php',
  // estas son las variables que querés pasar a PHP
  // donde el "key" es el nombre que va a recibir
  // en el archivo php como $_POST['total']
  data: {total: 1239.32},
  // esta función se llama cuando termina de procesar el
  // request y utiliza el response para obtener la data
  // que se imprimió desde PHP
  success: function(response) {
    console.log(response);
  }
});

PHP ejemplo.php

$total = $_POST['total'];

// ejecuto lo que necesite hacer con la variable
// por ejemplo: le agrego el signo $
$total = "$" + $total;

// esta es una forma de devolverle el nuevo valor a
// javascript y lo va a agarrar el "success" del ajax
echo json_encode($total);

html

<!-- importo el jQuery para poder utilizar ajax -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!-- importo el script donde se va a ejecutar -->
<script src="script.js"></script>
    
answered by 05.10.2018 в 19:40