Reputation: 47
I'm trying to pass a counter variable that I made in my PHP script to my .JS file. I've read on here that the best way to do this is with JSON (I'm writing with JQuery), but I'm having a hard time getting it to work with what I have.
In my PHP, I apply my counter to a td class and then send it over via JSON. So:
….
<table>
<?php $counter = 0;?>
<?php while ($counter < 20) : ?>
<tr>
...
<td class="classname<?php echo $counter; ?>"></td>
</tr>
<script type="text/javascript">
var counter = <?php echo json_encode($counter); ?>;
</script>
<?php $counter++;
endwhile; ?>
</table>
…
Now in my .js file, I have the following line that tries to put the counter that I echoed into the CSS identifier:
if...
$('td.classname' + counter).text("Text gets displayed");/* Change text in td */}
Is this the wrong way to access the variable?
Upvotes: 1
Views: 406
Reputation: 17920
No need of JSON since you are doing this on server side, just remove json_encode
and echo
the value which will assign it to js counter
.
<script type="text/javascript">
var counter = <?php echo $counter; ?>;
</script>
Upvotes: 1