Pass Javascript parameter to PHP

Asked

Viewed 7,203 times

2

I want to pass 2 (two) parameters from my javascript page to a PHP page. I’ve searched the net, and only find this logic when PHP is on the same javascript page.

Does anyone know if this is possible? and how to do?

3 answers

1


Is not possible, unless you are trying to requisition HTTP (ajax, forms, etc).

This is why Javascript runs client side (browser) while PHP runs server side (server) and the only path to JavaScript (client) up to the PHP (server) is through request HTTP.

Example - Ajax:

ajax.html

$.ajax({
  type: "POST",
  url: "algum.php",
  data: { meuParametro1: "valor 1", meuParametro2: "valor 2"},
  complete: function(data){
            // (...)
        }
});

Example - Form:

formulario.html

<form action="algum.php" method="post">
    <<input type="text" name="meuParametro1" value="valor 1">
    <<input type="text" name="meuParametro2" value="valor 2">

    <<input type="button" name="btEnviar" value="Enviar">
</form>

algum.php

$parametro1 = $_POST['meuParametro1'];
$parametro2 = $_POST['meuParametro2'];
  • But the way you did it would be with only 1 variable. How would it be with 2 variables.

  • @Eduardof.Santos, I updated my answer with two examples!

  • @Eduardof.Santos, just use comma for more than one parameter. It is an object, so it has key (meuParametro1, without quotation marks) and value ("valor 1", quotation marks).

1

You can add as many variables as you like. Exp:

data: { parametro: "valor", prametro2: "valor", parametro3: "valor"}

Or go from PHP like this:

var valor1= '<?php echo "valor"; ?>'
var valor2 = '<?php echo "valor"; ?>'

data: { parametro: valor1, parametro2: valor2}
  • And how would I get this variable in PHP?

0

Use ajax:

$.ajax({
      type: "POST",
      data: {variavel: 'valor'} ,
      url: "arquivo.php",
      success: function(resposta){
          alert(resposta);
      }  
    }); 

That way you give a Javascript PHP pro POST.

  • In case I have two values to be passed, then it would be like this $.ajax({&#xA; type: "POST",&#xA; data: {variavel: 'valor'} ,&#xA; data1: {variavel1: 'valor1'} ,&#xA; url: "arquivo.php",&#xA; success: function(resposta){&#xA; alert(resposta);&#xA; } &#xA; });

Browser other questions tagged

You are not signed in. Login or sign up in order to post.