Pass Javascript variable to Global Scope variable in PHP

Asked

Viewed 181 times

0

How do I pass a Javascript/Jquery variable to a Global Scope variable in PHP? recently I needed a global scope variable in PHP to receive a javascript value, this variable would be used later on other pages, I came to use Ajax and send the variable via POST to a php page and then include the result via append on the main page, only that I would need the PHP variable that received the value to be available globally to be used in other confirmations and pages. To get around the problem I passed the value via Cookie with Jquery, but this does not seem to be the right way to do this. the code below is trying to use Ajax to try to create the global scope variable in PHP

index php.

<script>
    $(window).ready(function(){
    var variavel = "valor a ser passado para variavel de escopo global php";

       $.ajax({
       method: "POST",
       url: "script.php",
       data: { nome: variavel }
    })
      .done(function( data ){
           // resposta do servidor
           $("#conteudo").append(data)       
    });
    });
</script>

<div id='conteudo'></div>

php script.

Receives the Post JS value and is added via append on the main page

if( isset($_POST['nome'])){

    $valor = $_POST['nome'];

    $varTeste = json_encode($valor);

    $varTeste; // variável que deveria ficar disponível globalmente

    echo $varTeste;

}
  • 1

    Already studied PHP sessions?

  • I hadn’t really thought of using sessions, and now that you spoke it was obvious that it was what I should have used, thank you for the reply, soon I update with the little code that solves the problem for some other lost soul rsrrsr, vlw msm Anderson

1 answer

0


In case someone else has the same problem the solution really was to store in a php session, in case I used to store the screen size of the user taking via Jquery and sending via post by Ajax

on the page script.php added

session_start();
$_SESSION["screenWidth"]; 

Then when using just log in and store in a variable in my case on the index.php page

session_start();
$screenWidth = $_SESSION["screenWidth"];
echo $screenWidth;

I also removed the append since I had no need to bring a treated result and all I needed was to store only the variable value.

   $("#conteudo").append(data); // parte desnecessária removida

Browser other questions tagged

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