Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I am trying to create a site where someone can create an "item" and the database will store an id and php generates a url for that id. So next time when the person comes back with that url it will remember the person's settings (variables). Now the problem is that in my site javascript need to know these variables.

So what is the best solution for this? passing the variables in the superglobal "GET" or maybe cookies? Or is there a better way to pass these variables to javascript?

share|improve this question

2 Answers

up vote 4 down vote accepted

just use php to print some dynamic javascript

<script>
var myVar = "<?php echo json_encode($_COOKIE['somevalue']);?>";
</script>
share|improve this answer
3  
You can access cookies from JS directly too. –  Furicane Aug 21 '11 at 23:38
3  
Unless you're very sure what kind of value is in some value you better JSON escape/encode it. –  deceze Aug 21 '11 at 23:42
3  
I think it would be better to use <?php echo json_encode($_COOKIE['somevalue']); ?> than "<?php echo $_COOKIE['somevalue']; ?>". –  icktoofay Aug 21 '11 at 23:42
 
I definitely agree about the json_encode. I'll update the answer. Thanks. –  dubvfan87 Aug 22 '11 at 0:25
 
@Furicane Not when HttpOnly cookies are being used. –  Jack Oct 15 '12 at 9:40

There are multiple methods for providing the data to the client, such as:

  1. Echo the variables in your javascript, var userid = <?php echo $userid; ?>
  2. JSON'fy your variables and supply them to your javascript via AJAX/jQuery: $.getJSON(url, function(data){ var userid = data.userid; });

I typically utilize JSON as much as possible when trying to present server-side data to the client-side, as it helps to separate the different layers.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.