4

I'm wondering if it's possible to store a number generated from a javascript script into a PHP SESSION variable. I basically want to store my code '+.res.id+' and '+.res.level+' into a PHP SESSION. Those 2 javascript codes generate a random number and inputs that number in a html form. IS there anyway I could take that number and store it in a PHP SESSION? For example

<script>
JAVASCRIPT CODING

'+res.level+'
'+res.id+' // BTW it actually does generate a number I just can't echo it in another      page or store it in a SESSION 
</script>

<?php
$_SESSION['.res.id.'] = $idnum;
$_SESSION['.res.level.'] = $levelnum;
?>

Then after in a seperate page I want to call that SESSION and echo the number that the code generated. But my only problem is that when I echo the $_SESSION it echo's as ".res.id." instead of the randomly generated number. How do I fix this to make it echo the random generated number?

4
  • PHP is running on the server and Javascript in the browser. All PHP will execute on the server and then the output is sent to the browser. The browser will then find all Javascript code and run that. Commented May 13, 2014 at 2:43
  • You will have to send the data back to the webserver via an AJAX call. Otherwise setting cookies in Javacript will be read by the PHP on next execution. Commented May 13, 2014 at 2:45
  • Thanks Scuzzy, but is it secure to set cookies? @Scuzzy Commented May 13, 2014 at 2:47
  • is about c# MVC but is related to it stackoverflow.com/a/23444765/1874460 Commented May 13, 2014 at 3:02

1 Answer 1

9

First of all javascript is running on a client side and php is running on a server side. It means you can't just store the generated number. But there is a workaround on that. You can do that by means of AJAX request.

In your js you can do this.

var res_id = your_random_number;
var res_level = your_random_number

$.post("/any/url/that/contains/your/php/code", {res_id:res_id, res_level:res_level});

In your php.

$_SESSION["res_id"] = $_POST["res_id"]; 

$_SESSION["res_level"] = $_POST["res_level"];
Sign up to request clarification or add additional context in comments.

3 Comments

Simple and straight forwards, +1
In php-code at first line should be session_start();
I am total newbie in JS. Could somebody explain me how to use that "$"? Do I need to include jQuery or smth? I'm totally confused on how to work with AJAX, and I've no idea where to read about it :\

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.