1

This is a simple syntax question.

I declare a variable:

<script type="text/javascript">
            var id_1= '<?php echo $id; ?>';
    </script>

And then in a externally loaded js file im trying to call a function using the variable (the external js file is loaded after the ^^ variable declaration:

 loadComments(id_1);

The id_1 is being passed literally as 'id_1', not recognizing it should be a variable. What am I doing wrong?

4
  • what value does the $id hold in php.. add an alert(id_1); right after assigning the variable... what does it alert ? Commented Jul 11, 2012 at 14:57
  • @gaby 2 .. the php isnt the problem Commented Jul 11, 2012 at 14:58
  • Your code should be fine as it stands. Probably it's some kind of scope problem. What is the error message? Commented Jul 11, 2012 at 14:59
  • can you post the loadComments code ? and do you get an error or just wrong results ? Commented Jul 11, 2012 at 15:00

2 Answers 2

2
var id_1 = '<?php echo $id; ?>';

Will echo something like this:

var id_1 = '10';

Which is treated as a string in JavaScript. You want to do this instead, so that you assign a number to id_1:

var id_1 = <?php echo $id; ?>;

This will print out something like this:

var id_1 = 10;
Sign up to request clarification or add additional context in comments.

6 Comments

Alternatively, keep the quotes and run something like parseInt() in the variable.
@Christoph That would work, but there's no need to do so; if you can assign an integer verbatim, why go through the hassle of casting a string to an integer?
For example when $id; can be more then just a number? Then it would throw an error, while keeping the quotes, parsing it and checking for a number would not.
If it is, but you want to assign a number to a JS variable and you have full control over the script that generates $id, then you're doing something wrong if you assign 20foo to id_1.
Well, I understand your point, but still these were only implications made from your side and not confirmed by the OP;)
|
1

The php code is recognized only by a .php file.

Put your code in a .php file and run it on you local server

1 Comment

That isnt the problem, the php code is being processed just fine. What the browser sees is var id_q = '2'

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.