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.

jcubic
67.1k58 gold badges252 silver badges466 bronze badges
asked Apr 10, 2015 at 19:36
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 ; ?>";
answered Apr 10, 2015 at 23:17
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 :)

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.