I am trying to pass 2 variables from PHP to JavaScript and the vice versa.
I understand how to pass one variable, and it's okay, but when I tried to pass 2 variales, one of them passed, the other one didn't work.
Here is the code:
(1) file1.php:
<script type="text/javascript">
var id = <?php echo $id ; ?>
var q= <?php echo $q ; ?>
</script>
<script type="text/javascript"src="http://localhost/site/js/java.js"> </script>
(2) Java.js:
http://localhost/site/file2.php?id="+id +"&q="+q
(3) file2.php:
$id = $_GET['id']; >> it works fine
$q= $_GET['q']; >> doesn't pass (error: undefined)
I am not sure where the problem is, I just think it's in the number (2) step.
Any help will be appreciated.
jcubic
67.1k58 gold badges252 silver badges466 bronze badges
1 Answer 1
As per comments, if q is a string then it needs to be enclosed in quotes. Remember all you php code is doing is generating text.
var q= <?php echo $q ; ?>
Should be
var q= "<?php echo $q ; ?>";
answered Apr 10, 2015 at 23:17
Toby Allen
11.3k12 gold badges80 silver badges132 bronze badges
Sign up to request clarification or add additional context in comments.
1 Comment
DevManX
Thank you so much, finely it worked, the 'magic' quotes solved the problem :)
default
Java.jsdid you just...var q=is set and is not null. have you looked athttp://localhost/site/file2.php?id="+id +"&q="+qafter it was parsed to make sure that theqvalue is not empty?&q=undefinedand you will have undefined in php.