1

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.

11
  • 6
    Java.js did you just... Commented Apr 10, 2015 at 19:38
  • have you verified that var q= is set and is not null. have you looked at http://localhost/site/file2.php?id="+id +"&q="+q after it was parsed to make sure that the q value is not empty? Commented Apr 10, 2015 at 19:41
  • 1
    Check if q is undefined if so you pass &q=undefined and you will have undefined in php. Commented Apr 10, 2015 at 19:43
  • 1
    the second variable is failing, meaning it is likely a case of a malformed get statement... does the get statement look normal try alerting it instead of importing it. Commented Apr 10, 2015 at 20:01
  • 1
    my guess is q is a string! Commented Apr 10, 2015 at 20:10

1 Answer 1

2

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 ; ?>";
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you so much, finely it worked, the 'magic' quotes solved the problem :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.