Store javascript result in a php variable

0

There is some way to make this code work:

<script>
function getBaseURL() {
// obtenemos el hash
var jash = window.location.hash;
// lo imprimimos
return jash;
}
</script>

<?php
 $url1 = "<script>getBaseURL();</script>";
 $url = $url1
 echo $url ;
?>

I clarify what I use to get the current url that contains something like this

http://localhost/prueva.php?#access_token=EAALhZB1GcFMUBAIk7fEyHjQUT6wb0N

The problem is the # sign using window.location.hash of javascript I get what I'm looking for but I can not pass it to php

I'm looking for a way to save the result of the jash variable in javascript. In PHP variable $ url .

I hope some help thanks

    
asked by BotXtrem Solutions 14.11.2017 в 15:02
source

3 answers

1

Try it this way is a simple example:

<script type="text/javascript">
    function javascript_to_php() {
        var jsVar1 = "Hello";
        var jsVar2 = "World";
        window.location.href = window.location.href + "?w1=" + jsVar1 + 
        "&w2=" + 
        jsVar2;
    }
</script>

 <?php
  // comprobar si tenemos los parametros w1 y w2 en la URL
  if (isset($_GET["w1"]) && isset($_GET["w2"])) {
     // asignar w1 y w2 a dos variables
     $phpVar1 = $_GET["w1"];
     $phpVar2 = $_GET["w2"];

  // mostrar $phpVar1 y $phpVar2
     echo "<p>Parameters: " . $phpVar1 . " " . $phpVar1 . "</p>";
  } else {
     echo "<p>No parameters</p>";
  }
 ?>
    
answered by 14.11.2017 в 15:28
1

I hope this can help you.

You can try rescuing the variable from the url localhost /? var = 1 # hash

<?php echo parse_url("http://localhost/?var=1#hash",PHP_URL_FRAGMENT); ?>

The result will be: hash

Will it be what you need?

    
answered by 14.11.2017 в 15:31
1

What you try can not be done. PHP first processes all the text that you passed to generate an HTML.

When you do

$url1 = "<script>getBaseURL();</script>";

The value of $ url1 is exactly that string. In no case the result of the evaluation of javascript.

As you were suggested in another answer, a workaround would be to evaluate if the hash exists and redirect to another url where the hash value is presented as part of the query string.

<script>
function getBaseURL() {

    var hash = window.location.hash;

    if(hash) {
        window.location.href=window.location.href.split('#')[0]+'?hash='+hash.replace('#','');
    }

}
getBaseURL();
</script>

<?php
if (isset($_GET['hash'])) {
    echo 'hash is :' . $_GET['hash'];
}

But this is just a workaround. What do you want to do exactly with that hash? Log in from the server side? Do something in the front to validate that this session exists? Modify the behavior of the front according to the hash?

If what you want to do is the latter, you should assume that PHP will simply give you plain HTML and that the rest of the business logic (in its first layer) will occur in the front.

    
answered by 14.11.2017 в 17:32