How to pass a javascript variable to an external php

1

I have a javascript function in which I get a variable that I need to use in a different php file and I do not know how to do it. I show you the code of the files, thanks in advance.

JavaScript file (test1.html)

function boton() {

  var id_nombre=document.formConductor.selector.value;
  $.post("prueba2.php", [id_nombre]);
  alert (id_nombre);
}

PHP file (test2.php)

$conductor = $_POST["id_nombre"];
print $conductor;
    
asked by hayber 20.04.2018 в 17:07
source

2 answers

3

You should pass it to the $.post as an object.

function boton() {
  var id_nombre = document.formConductor.selector.value;
  $.post('prueba2.php', { id_nombre: id_nombre }, function(data) {
    // Hago algo con esa data
    console.log(data);
    // Esto te imprime en la consola el dato que le enviaste como id_nombre
  });
}

And in your PHP:

$conductor = $_POST["id_nombre"];
// siempre es conveniente hacerle un encode a json
echo json_encode($conductor);
    
answered by 20.04.2018 в 17:14
0

You can use ajax to achieve this. Below is the code that works with a click of a button or an anchor click.

HTML

<button type="button" id="boton1">Click Aqui</button>

Ajax

$('#boton1').click(function() {
var a = $('#IdElemento1').val();
var b = $('#IdElemento2').val();

$.post('/prueba2.php', {'variableA': a, 'variableB': b}, function(data) {
    var valor= JSON.parse(data);
    if (valor== 'Completo') {
       setTimeout(function () {
        window.location = '/prueba2.php';
        }, 3000);//esto redirigirá al mismo archivo.php después de 3 segundos
    }
    else
    {
        alert ('Detalles Invalidos');
    }
});
});

and then you can access your prueba2.php file like this:

$a = $_POST['variableA'];
$b = $_POST['variableB'];
    
answered by 21.04.2018 в 15:43