Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
174
rated 0 times [  180] [ 6]  / answers: 1 / hits: 45187  / 12 Years ago, fri, july 13, 2012, 12:00:00

Possible Duplicate:

passing variables from php to javascript






I'm dynamically generating a list. I want to make each row hover on mouseover and clickable to a link. I want the link to pass the id of the content of the row.



Basically:



foreach ($courses as $cid=>cinfo){ 
$univ = $cinfo['univ'];
$desc = $cinfo['desc'];
$size = $cinfo['size'];
$start = $cinfo['start'];
print <div class='rc_desc' id='rc_desc$cid'>.$desc<br/>.<b>$univ</b><br/>.
<span>Number of students</span>: $size<br/>.
<span>Started at</span>: .date('F d, Y',strtotime($start)).<br/>.
}

<script>
$(function ()
{
$('#rc_desc$cid').hover(function ()
{
$(this).toggleClass('.tr');
});
$('#rc_desc$cid').click(function ()
{
$(location).attr('href','student.php?$cid');
});
});
</script>


The issue is in the js/jquery. I want to be able to grab the $cid and pass it to the student.php page upon click. The php code above works but the js won't of course. I know the fundamental of client-side vs server-side languages. This question doesn't warrant a lecture. I know I cannot do this exactly, but it is what I want to happen ultimately. Any thoughts on how I can achieve this simply? Thanks in advance my friends!


More From » php

 Answers
1

Yes, if you include the <script> section in your PHP code, you can do something similar to the following:



<script>
var foo = <?php echo $foo; ?>;
</script>


In your case, you would be looking into the following code structure:



<script>
$(function () {
$('#rc_desc<?php echo $cid ?>').hover(function () {
$(this).toggleClass('.tr');
});
$('#rc_desc<?php echo $cid ?>').click(function () {
$(location).attr('href', 'student.php?<?php echo $cid ?>');
});
});
</script>


The reason why this is possible is because although the Javascript is run on the client-side, it's processed on the server-side first prior to being presented on the page. Thus, it'll replace all necessary instances of $cid with the one you have included.



Enjoy and good luck!



EDIT:



<script>
$(function () {
$('.rc_desc').hover(function () {
$(this).toggleClass('.tr ');
});
$('.rc_desc').click(function () {
$(location).attr('href', 'student.php?' + $(this).attr('id').split('rc_desc')[1]);
});
});
</script>

[#84268] Thursday, July 12, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
anyssaarielles

Total Points: 415
Total Questions: 107
Total Answers: 92

Location: Greenland
Member since Fri, Jul 31, 2020
4 Years ago
;