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?
2 Answers 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;
6 Comments
$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.$id, then you're doing something wrong if you assign 20foo to id_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
var id_q = '2'
$idhold in php.. add analert(id_1);right after assigning the variable... what does it alert ?loadCommentscode ? and do you get an error or just wrong results ?