Red Virus
Red Virus

Reputation: 1707

Assign JavaScript Variable value into PHP Variable

I have this JavaScript below which does few things on my website. I need to assign the value from JavaScript into PHP Variable to be used in a SESSION.

   <script type="text/javascript">
        function CallbackReverse(what) {
            rand = get_rand();
            text = "416-05-201-XXX";
            text = text.replace("XXX", rand);
            //Store it in session
            <?php $_SESSION["pin_number"] = "text"; ?>
        }
    </script>

Please help.

Upvotes: 0

Views: 1077

Answers (2)

lucasgehin
lucasgehin

Reputation: 127

You can't insert PHP code in javascript code, PHP is a server language and Javascript is a client language

The solution to do what you want is using AJAX and call a PHP page which execute your action - you can send parameters (i.e. text)

with jQuery :

$.ajax({
    type: 'POST',
    url: 'mypage.php',
    data: {text: text},
}).done(function () {
    /* success code here */
});

Your script PHP called :

$text = $_POST['text'];
$_SESSION['pin_number'] = $text;

Upvotes: 4

Luigi Caradonna
Luigi Caradonna

Reputation: 1064

You can't do that. Javascript lives on the browser, PHP lives on the server, when you see the page (so when JS is executed), PHP doesn't exist anymore.

You should change the logic of your code.

Upvotes: 2

Related Questions