-3

I need to change the value of a PHP variable to JavaScript code.

The value of the PHP variable has to be something out of (JavaScript) localStorage.

So it is something like this.

$variable = localStorage.anameofalocalstorage; //The localstorage part is js

How can I do this?

gen_Eric
  • 223,194
  • 41
  • 299
  • 337
Evert De Spiegeleer
  • 177
  • 1
  • 3
  • 10
  • 1
    Only JavaScript can read `localStorage`. So, if you want PHP to get the value, you need to send it from JavaScript; possibly via AJAX. – gen_Eric Jul 05 '13 at 16:29
  • You'll need to get your variable to the erver through a get or post request, eventually in Ajax... no other way – Laurent S. Jul 05 '13 at 16:29
  • Possible duplicate: http://stackoverflow.com/questions/4298091/php-javascript-variable-help?rq=1 http://stackoverflow.com/questions/1917576/how-to-pass-javascript-variables-to-php http://stackoverflow.com/questions/9836748/pass-javascript-variable-into-php-code?rq=1 – pattyd Jul 05 '13 at 16:31
  • @RocketHazmat Oh.. thanks, but i don't really know Ajax.. can you please give me the code for doing that ? – Evert De Spiegeleer Jul 05 '13 at 16:32
  • If you need to use a value set via javascript in php, and I think you are running the js at the browser, and not something like nodejs at the server-side, you must send the value set at the client (via js) to the server, as php is not executed on the client side. Is this ehat you want? – Alexander Jardim Jul 05 '13 at 16:33
  • 1
    @EvertDeSpiegeleer: There are lots of AJAX tutorials out there, have a look around :-) – gen_Eric Jul 05 '13 at 16:33

1 Answers1

0

This is an example code using jquery for the ajax call.

<?php

$variable_that_should_be_set=isset($_GET['shoudBeSet'])?$_GET['shoudBeSet']:'notSet';

?>

<html>
    <head>
        <script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>

    </head>
    <body>
        <div id="div1"><?php echo $variable_that_should_be_set;?></div>
        <a href="#" id="button">Click here to Set</a>
        <script>
            $("#button").click( function () {
                $.get("?shouldBeSet=this_is_set")   
            })
        </script>
    </body>
</html>
Alexander Jardim
  • 2,406
  • 1
  • 14
  • 22