problems with $().click() when generating JavaScript code with a PHP loop - php

Regards.
I am generating an .click event for every element of my table using a php loop like this:
<?php foreach ($elements as $element){ ?>
var element_id = <?= json_encode($element['element_id']));?>;
$('#'+element_id+'_button').click(function() {
$('#'+element_id+'_interval').toggle();
if ($(this).hasClass('active')){
$(this).removeClass('active');
}
else{
$(this).addClass('active');
}
});
<?php }?>
the problem is, when $('#'+element_id+'_interval').toggle(); the element is not responding but it adds and removes the classes correctly, somebody help me please.

Use a class, makes your code a lot cleaner, however if you have to do it this way you should know that your element_id variable is constantly being rewritten.
Try something like:
<button class="toggler" data-target="#interval_1"></button>
$(".toggler").click(function (ev) {
ev.preventDefault();
var target = $(this).data("target"); // would return #interval_1
$(target).toggle();
if ($(this).hasClass('active')) {
$(this).removeClass('active');
} else {
$(this).addClass('active');
}
});

I would advise you to firstly separate your php from your javascript.
Otherwise (between other) it will be difficult to maintain.
As a start, you could do the loop with javascript

Put the binding events into a seperate method, and call the method in your document.ready script:
$(document).ready(function() {
bindBtns();
});
function bindBtns()
{
<?php foreach ($elements as $element){ ?>
var element_id = <?= json_encode($element['element_id']));?>;
$('#'+element_id+'_button').click(function() {
$('#'+element_id+'_interval').toggle();
if ($(this).hasClass('active')){
$(this).removeClass('active');
}
else{
$(this).addClass('active');
}
});
<?php }?>
}

Related

Attribute from php to Jquery.click within php foreach

I've been trying out different things for a while, but nothing seems to be working. And would probably need another kind of perspective.
For the question: I got a php foreach loop going, and every object is posting the ID of that object.
But my problem in this that when i click, the object is giving me the last number of the foreach.
Ive been trying to post the value in JSON, and just plain php.
PHP
<?php
foreach ($places as $place) {
$place_id = json_encode($place['id']);
echo "<div class='placeContainer' onClick='openMessage(\'' . $place_id .
'\')'>";
?>
Jquery
$(document).ready(function () {
$('.placeContainer').click(function () {
$(this).attr(phpvar);
var myKey = JSON.parse(phpvar);
console.log(myKey);
})
});
Thanks for the help!
Try this :
PHP Code :
<?php
foreach ($places as $place) {
$place_id = json_encode($place['id']);
echo "<div class='placeContainer' data-id='".$place_id."'>";
?>
JS Code :
$(document).ready(function () {
$('.placeContainer').click(function () {
var myKey = $(this).attr('data-id');
console.log(myKey);
})
});

jQuery get value from while loop and display it in another div without click

How do I make jQuery get value from while loop and display it in another div?
I know I should do it with PHP, But I want to display it with only jQuery.
<? while($commentresult = $commentdata->fetch_array(MYSQLI_ASSOC)) { ?>
<div class="show_url"></div>
<? } ?>
$(document).ready(function() {
var getUrl = $('.get_url_comments').attr('href');
$(".show_url").text("Click This" + getUrl);
});
To do this you can set the text() of the .show_url element based on the following .get_url_comments. Try this:
$(document).ready(function() {
$(".show_url").text(function() {
return $(this).next('.get_url_comments').attr('href');
});
});
You should note though that it would be a much better idea to do this directly in PHP:
<? while($commentresult = $commentdata->fetch_array(MYSQLI_ASSOC)) { ?>
<div class="show_url"><? echo $commentresult['comment']; ?></div>
<? } ?>
Try with this..
$(document).ready(function() {
$('.get_url_comments').map(function(guc){
var el = $(guc);
var url = el.attr('href');
el.prev().text("Click This" + url);
// or
el.prev().html("Click This" + url);
});
});

Show Hide elements table element in loop by jquery

I am a learner in Jquery coding, My task is to show/hide TABLE elements on clicking SPAN element. I tried with below mentioned Jquery code which is not working..
HTML code is:
foreach($array as $key => $arrValue) {
<span id="link<?=$count?>">$key</span>
<table id="tbl<?=$count?>">
foreach($arrValueas $key => $value) {
<tr><td>$value</td></tr>
}
</table>
}
My Jquery code is:
$(function(){
// To open/close field's group div
$("span").each(function (i){
i++;
$('#link' + i).click(function (i) {
$('#tbl' + i).toggle(800);
});
});
});
Pls avoid PHP open close tags issues in HTML code..
$("span").each(function (){
$(this).click(function () {
$(this).next('table').toggle(800);
});
});
try this
$(function(){
$("span").each(function (i){
(function(i) {
$('#link' + i).click(function() {
$('#tbl' + i).toggle(800);
});
}(i));
});
});
you don't need to increment the variable with i++ oyherwise you won't set the handler on the expected link element. Each() is already incrementing the variable i
Try this way to match two different element groups:
Here is jsFiddle.
var thumbs = $('ul.thumbHolder li');
var bigImg = $('ul.imgHolder li');
thumbs.click(function() {
var target = $(this).index();
bigImg.each(function(i){
if( i != target){
$(this).fadeOut(300);
}else{
$(this).fadeIn(300);
}
});
});​

Is it possible to insert php variables into your js code? [duplicate]

This question already has answers here:
Closed 10 years ago.
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!
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>
You can do it like this :
$(location).attr('href','<?php echo $cid ?>');
The javascript code doesn't know it comes from php, it appears as a constant (a literal) for it.
Yes it is possible. All you have to do is put your <?PHP echo $cid; ?> in where you need it
<script>
$(function ()
{
$('#rc_desc<?PHP echo $cid; ?>').hover(function ()
{
$(this).toggleClass('.tr');
});
$('#rc_desc$cid').click(function ()
{
$(location).attr('href','student.php?<?PHP echo $cid; ?>');
});
});
This is possible because by the time the scrip is put into the page the cid has already been replaced by the string on the server. Since PHP is server driven, before it spits back the html/script it will be just like you put it in yourself.
There is almost no way to actually communicate PHP and JavaScript. However, the best and simplest way is to set the ID within an attribute. The new HTML5 data attributes would be perfect.
For example, have a anchor tag with
<span data-id="22">some event</a>
and then:
$(this).attr('href','student.php?'+$(this).attr('data-id'));
Or just use
<?php echo $id; ?>
if it is not external JS file
Try this code
foreach ($courses as $cid=>cinfo){
$univ = $cinfo['univ'];
$desc = $cinfo['desc'];
$size = $cinfo['size'];
$start = $cinfo['start'];
print "<div class='rc_desc' data-id='$cid' 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').click(function ()
{
$(location).attr('href','student.php?' + $(this).attr("data-id"));
// if you want to redirect the page do this
// window.location.href = 'student.php?' + $(this).attr("data-id");
});
});
</script>
I think you block should be :
<script>
$(function ()
{
<?php foreach($courses as $cid=>cinfo) : ?>
$('#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; ?>');
});
";?>
<?php endforeach; ?>
});
</script>
UPDATE
But you don't really need to do this, you have
"<div class='rc_desc' data-id='$cid' 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/>".
You can try this
$(function (){
$('.rc_desc').hover(function ()
{
$(this).toggleClass('.tr');
});
$('.rc_desc').click(function ()
{
attrId = $(this).attr("data-id");
$(location).attr('href','student.php?'+id);
});
});

JQuery Updating Status

I am writing some jquery to call an ajax script every 2 seconds to get the result and update the page. I am mostly a backend programmer and could use some help on this.
This is the code I have now:
<script language="javascript">
function downloadProgress(id) {
$("#" + id + "").load("index.php?_controller=download&_action=getDownloadProgressAjax",
{
downloadId: id
}
);
setTimeout(downloadProgress(id), 2000);
}
</script>
<?php
foreach ($downloads as $dl) {
?>
<div id="<?php echo $dl["download_id"]; ?>">
<script language="javascript">
downloadProgress(<?php echo $dl["download_id"]; ?>);
</script>
</div>
<?php
}
?>
This does not work. What am I doing wrong or would you suggest another approach?
Thanks
I think that you are confusing your PHP script by giving it both query string variables (sent as GET) and data (which is probably getting sent as POST). Try this:
$("#" + id).load("index.php?_controller=download&_action=getDownloadProgressAjax&downloadId="+id }
since you are using jquery, you can use the $.ajax function when the page is ready.
$(function () {
function function downloadProgress(id) {
$.ajax({
url: "index.php?_controller=download&_action=getDownloadProgressAjax&downloadId="+id
})
setTimeout(function () {
if (downloadnotcomplete){ // this way your script stops at some pont.
downloadProgress(id);
}
},2000);
}
});
You will attach the downloadProgress(id) function to your download button or anything else, to trigger the function the first time.
The problem you are having is that you have to provide a parameterless function and not a function call to setTimeout. Also, I would do it a little bit different and use setInterval instead of setTimeout as it relays your intention better in the code. Here is how I would do it:
<script language="javascript">
$(function() {
setInterval(downloadHandler, 2000);
});
function downloadHandler() {
// I'm not sure where the id is coming from you will probably need to put a
// class on your div's so that you can select them.
$(".MyDivClass").each(function() {
var id = $(this).attr("id");
downloadProgress(id);
});
}
function downloadProgress(id) {
$("#" + id + "").load(
"index.php?_controller=download&_action=getDownloadProgressAjax",
{ downloadId: id }
);
</script>
and then on your div:
<?php
foreach ($downloads as $dl) {
?>
<div id="<?php echo $dl["download_id"]; ?>" class="MyDivClass"/>
<?php
}
?>
Hope this helps.

Categories