Take JS Variable value and pass to PHP and send by URL

Asked

Viewed 638 times

0

I have the following code below. I want to know if there is a way to send through the URL a variable that was passed from JS to PHP. The purpose of the code is to pass the variable after clicking the button.

OBS.:The user will be directed to this page described in the link

<html>
   <head>
   
  <title>Passar Variável Javascript para PHP</title>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
   <script type="text/javascript">
     var variaveljs = 'Mauricio Programador';
  </script>
   </head>

  <body>
   
  <?php
     $nome="<script>
     $(function() {
         $('#botao').click(function () {

             document.write(variaveljs);
         });
     });</script>";


       ?>

  <div id="botao">
    <?php
     echo " <a href='pagina2.php?valor='.$nome>Botão</a>";
     ?>
   </body>
</html>
  • Why do you need to pass a JS variable to PHP to then generate a link in the same JS document with the variable? Don’t just use JS?

  • If I understand your question correctly, you can go through get using jquery: $. get( "pagina2.php", { value: variaveljs } );

  • @Márciocristian I never used this form. If I pass the data to the "pagina2" and soon after is directed to it ,I will still have access to the data ?

  • @Andersoncarloswoss Well, I need to pass the values from page 1 to page 2 and be redirected from pg1 to P2 and have access to the data on P2 to manipulate. I can only do this with JS.I tried to use ajax but ($.AJAX();) but I realized it doesn’t work because when I’m directed to P2 ,I don’t have access to the data.

1 answer

2


You don’t even need PHP for this. If the value is already on the page there will be the link, just use JS only.

Simple example:

const variavel = "SOpt";
const link = document.getElementById('link');

link.href += variavel;
<a id="link" href="pagina.php?valor=">Link</a>

This will generate the link pagina.php?valor=SOpt.

  • How can I do this with jquery? and the value switch with click? I am using this code below $('. os'). on('click', Function(){ var choice = $(this). attr('name'); $('#o'). html(choice); when I click on an image with the class . Cs it takes the value in the name attribute and switches in the click. With yours I am using so var choice = $(this). attr('name'); link.href += choice; and the value accumulates instead of alternating

Browser other questions tagged

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