jquery php embedding DOM element same problem - php

When i embed or use php loops to create multiple div's with some id.
I want each of them to use with jquery. Say anything like simple hide/show interface.
But as the id is the same it wont work. I assign a variable lets say $i to php loop for the reference of uniqueness. I can assign id to a DOM element with like
<div id="element-<php echo $i ?>">Bla Bla </div>
Php echoes out here perfectly but how do i use it with jquery something like this:
$("#element"+<?php echo $i ?>).toggle();
Here it doesnt works.
How do i do it correctly and where am i going wrong ?
Sorry for bad english.
Thanks

You can try this
<script>
function togl(id)
{
$("#element"+id).toggle();
}
</script>
<?php
for ($i=0;$<10;$i++)
echo '<div id="element-'.$i.'" onclick="toggle('.$i.')">Bla Bla </div>';
?>

the proper syntax for a php code is:
<?php
//code
?>
So here you can clearly see what is the error:
<php echo $i ?>
It should be:
<?php echo $i; ?>
Updated answer:
<?php
for ($k=0;$k<=100;$k++)
echo '<div id="element-'.$k.'" onclick="toggleID('.$k.')">Here is the content of div $k</div>';
?>
<script>
function toggleID(id)
{
$("#element"+id).toggle();
}
</script>

You didn't include the dash in the jQuery code and you also don't need to concatenate the strings:
$("#element-<?php echo $i; ?>").toggle();
PHP is interpreted on the server and JavaScript is interpreted on the client. You should never consider concatenating strings between these environments since they are two different steps in serving your application.

I think your code for the javascript should be like this instead of what you posted.
$("#element-"+<?php echo $i ?>).toggle();
However I wouldn't recommend this approach as it's not very efficiant. It will trigger a lot of jQuery lookups.
You'd be better off giving all the divs in question a class and then using the class to reference them in jQuery.
<div class="toggleThis" id="element-<php echo $i ?>">Bla Bla </div>
$(".toggleThis").toggle();

Your problem is that you didnt' close your php statement:
You're missing the ";?>"
try this:
;?>
ath the end of your statement
EDITED:
plus you're missing the "-" between "element" and "id":
Ex. element-1
try including the "minus":
$("#element-"+id)

The problem is that you cannot have the same ID's. But if you just want simple show/hide functionality, you should add a class to your div instead of an ID. So..
class="toggableDiv"
and then in jQuery
$(".toggableDiv").click();

Related

How to apply jQuery function to DOM elements with similar IDs?

I got this script:
<script>
$('#zoom_01').elevateZoom({});
</script>
Where #zoom_01 is an ID of an image. I have many images with ID's like so:
zoom_01
zoom_02
zoom_03
zoom_04
and so on
How do i make so that javascript would take all ID's instead of one?
I was thinking something like this:
<script>
<?php
foreach ($ArrayAllOfIDs as $i) {
$('#<?php echo $i; } ?>').elevateZoom({});
}
?>
</script>
But it didnt work.
Although using the class attribute as mentioned above is probably your best bet, if you are forced to work with the IDs for whatever reason You can use a "starts with" selector like
$("[id^=zoom_]").elevateZoom({})
which will apply elevateZoom to all DOM elements with an id that starts with "zoom_".
Add a class to all the images that would be affected at the same time.
Ids are used to identify a unique, non repeating item. Since your images are all pretty much the same, a class can group them together.
Then, change your javascript to select the class.
$('.zoom').elevateZoom({});
I don't know what elevateZoom is, but you can likely have this syntax:
$('#zoom_01, #zoom_02, #zoom_03, ...').elevateZoom({});
Make the PHP write out the Javascript so it is available when the page is loaded in the browser.
<script>
<?php
foreach ($ArrayAllOfIDs as $i) {
echo '$(\'#zoom_'. $i .'} \').elevateZoom({});\n';
}
?>
</script>

jQuery is Commenting out my PHP Code Snippets

I'm building a code snippet system and am using jQuery to display the editor. I noticed jQuery likes to comment out any inline PHP code. Is there a way to prevent this from happening:
<textarea id='beep'></textarea>
jQuery code:
var code = "<div>Why <?php echo 'hello'; ?> there!</div>";
var parsed = $(code).html();
$('#beep').val(parsed);
This is what I would like to see in the textarea:
Why <?php echo 'hello'; ?> there!
But instead jQuery modifies it to look like this:
Why <!--?php echo 'hello'; ?--> there!
I understand this is probably a security measure, but is there a way to stop this from happening?
I know I can use HTML entities to get around this, but due to the nature of this tool it would interfere with code snippets being posted that intentionally include html entities.
JSFiddle: http://jsfiddle.net/YB4fD/1/
Additional Node: Some answers suggest I use JavaScript to handle this without jQuery, but I need jQuery. My string contains a DOM tree that I'm using jQuery to parse.
Try this:
var code = "<div>Why <?php echo 'hello'; ?> there!</div>";
This does the trick.
var code = "Why <?php echo 'hello'; ?> there!";
document.getElementById('beep').appendChild(document.createTextNode(code));
It is not valid to use other elements inside of a textarea-element.

Updating HTML from PHP function

I am having problems updating a SPAN in my HTML with the result from a PHP file. In the HTML below the is a link that calls the php file that will update the SPAN above it with the new value.
HTML
<div class="link-votes">
<span id="v<?php echo $link_id; ?>"><?php echo $votes; ?></span>
</div>
PHP
if($_POST['id']) {
$up_value=$row['vote_count'];
$("#v"+id).html(html) = $up_value;
}
If I echo $up_value the right integer is printed. But I cannot update the value in the SPAN.\
Thanks,
You are mixing Javascript code with PHP code. You are using the html() function which looks like it might be from the JQuery library. You might want to echo() in PHP and then use Javascript to work on the return value of that echo() statement. It should work as the echo() will be done before the Javascript takes effect, as is the required flow of execution.
Thanks all, your advice helped me figure it out. What I did for other newbies reference was
echo $up_value;
at the end of the php file and then in my jquery:
success: function(html) {$("#v"+id).html(html);}
as the comments to your question show, you're mixing php & jquery code.
your php code should look something like this:
if(isset($_POST['id'])) {
$up_value=$row['vote_count'];
echo "<script>$('#v".id."').html('".$up_value."');</script>";
}

is it possible to dynamically assign ID to an element in webpage using JS/ PHP?

can i set the id of an element programatically, as in a dynamic setting of id of an element, during runtime of the webpage?
Consider this scenario -
<body id="body1">
Now, i want to set the id of this element "body" dynamically, using the value of a variable in the php code. Is this possible? something like -
<body id=" <?php echo $bodyID; ?> ">
I use php and jquery in the page; please let me know whether such dynamic id assignment is possible to the elements in the html.
thanks.
PHP is the background language, it's what produces your HTML output. So basically, what ever you output from PHP eventually becomes your HTML, meaning yes you can use PHP variables as your elemnt-ID or anything else for that matter.
<?PHP
$var = "body1";
?>
<body id="<?PHP echo $var; ?>"> Hello my ID is <?PHP echo $var; ?></body>
OR You can output all of the HTML using a single echo statement.
<?PHP
$var = "body1";
echo "<body id='$var'>Hello my ID is $var</body>";
?>
In conclusion, whatever is left after PHP is finished executing is your HTML code that the end users browser interprets... Hope this helps...
$(function() {
var variable = 'insert_id';
$('body').attr('id', variable);
});
gives (with jquery)
<body id="insert_id">
Why not? As long as you keep your randomizer ( Math.rand ) big enough there should be little chance for conflicts.
I usually do this, and then at the same time call a JS method and passing the same ID. That would require you storing the ID aside so you can pass it later.
Edit: If you are only setting this on the body then you would not need to access it later.

PHP variable as part of a jQuery function doesn't work, but plain text does

I have the following jQuery code in my PHP file (edited Jan 19 2010 # 10:40 MST):
<?php
$count = 0;
foreach($attachments as $attachment) :
echo '<script type="text/javascript">
$(\'#a_'.$count.'\').click(function() {
$(\'#d_'.$count.'\').show(200);
});
// if "no" is clicked
$(\'#d_'.$count.' .no\').click(function() {
$(\'#d_'.$count.'\').hide(200);
});
// if "yes" is clicked
$(\'#d_'.$count.' .yes\').click(function() {
$(\'#d_'.$count.'\').hide(200);
// update database table -- this is why I need the script inside the for loop!
var jsonURL = \'http://path/to/update_db_script.php\';
$.getJSON(jsonURL, {\'post_id\' : '.$attachment->ID.'}, function(data) {
alert(\'Thank you. Your approval was received.\');
});
$(\'#a_'.$count.'\').replaceWith(\'<span>Approved</span>\');
});
</script>';
echo '<li>';
if($attachment->post_excerpt == 'approved') {
// Check the proof's status to see if it reads "approved"
echo '<span>Approved</span>';
} else { ?>
// If not yet approved, show options
<a class="approve" id="a_<?php echo $count; ?>" href="#">Click to Approve</a>
<div class="confirm-approval" id="d_<?php echo $count; ?>">
<p>Please confirm that you would like to approve this proof:</p>
<a class="yes" href="#">Yes, I approve</a>
<a class="no" href="#">No, not yet</a>
</div><?php
} ?>
</li>
<?php $count++;
endforeach; ?>
The page in question is available here. The "click to approve" links do not work (that's my problem).
When I view source, the PHP variables appear to have echoed properly inside the jQuery:
<script type="text/javascript">
$('#a_0').click(function() {
$('#d_0').show(200);
});
... etc ...
</script>
This looks correct, but nothing happens when I click any of the links. However, when I replace the PHP echo statements with plain numbers (0, 1, etc.) the click functions work as expected.
You may be asking: why on earth do you have this inside a for loop? The reason is that I need to retrieve the attachment->ID variable and pass it to an external PHP script. When someone clicks "approve" and confirms, the external script takes the attachment->ID and updates a database value to read "approved".
Why won't the click function fire when PHP is in place? Is there some kind of greater force at work here (e.g., hosting limitation), or am I missing a fundamental piece of how PHP and JavaScript interact?
Since you didn't post your HTML its a little hard to troubleshoot.
First, I am not sure why one is working and the other is not since the code it is outputting looks correct. Either way, I still would make some changes. Move your a_0,a_1, etc and d_0,d_1, etc into the id attribute instead of a class:
<div>Click Me</div>
<div class="confirm_approval" id="d_0">Show Me</div>
<div>Click Me</div>
<div class="confirm_approval" id="d_1">Show Me</div>
Now, instead of outputting your code in a loop in PHP, place this jQuery code once on your page:
$(document).ready(function(){
$("a.approve[id^='a_']").click(function(e){
var id = this.id.replace('a_',''); // Get the id for this link
$('#d_' + id + '.confirm-approval').show(200);
e.preventDefault();
});
});
This code finds any a element with the approve class that has an id that starts with a_. When this is clicked, it grabs the number off the id a_0 = 0 and uses that id to find the confirm-approval element and show it.
Since the javascript is run on the client and has no way of knowing whether the script was generated using PHP or not, I think that particular part is a wild goose chase...
When I replace the PHP echo statements
with plain numbers (0, 1, etc.) the
click function works as expected.
Do this again and compare the actual output using view-source in a browser. I'll bet you find that there is a difference between the working and failing scripts, other than one of them being generated by PHP.
It seems that the problem is in jQuery selectors. Instead of dynamically binding click() events on multiple objects with an output of PHP code, use just one class selector and bind to objects with this class. And you can specify an id attribute to make them unique.
Something strange too is to have the script tag and the
$(document).ready(function()
in the loop. I don't know if this causes any problems, but it's sure not very efficient, one time is enough.

Categories