So I have a php foreach loop as follows,
$i = 1;
foreach($rows as $record){
<div id='ytplayer".$i++."'>
</div>");
}
and then I have javascript which uses the getElementById and it needs to get the div everytime it is looped, which would essentially be an array, but how would I do that, I know what I have below wont work, but something like this, since I know this is pretty close to how you would get this to work in php
document.getElementById('ytplayer[i]');
Here you go!
http://jsfiddle.net/epinapala/5yUAx/
Assuming that your PHP writes the following divs(one,two etc are added for example sake...)
<div id='ytplayer1'>one</div>
<div id='ytplayer2'>two</div>
<div id='ytplayer3'>three</div>
<div id='ytplayer4'>four</div>
for(var i=1; i<5; i++){
var x=document.getElementById('ytplayer'+i);
alert(x.innerHTML);
}
document.getElementById('ytplayer'+i);
Related
del_id = $('.button').attr('rel');
alert(del_id)
PHP:
while ($row=mysqli_fetch_assoc($rs)) {
?>
<div class="itemsin" >
<span data-toggle="confirmation" rel="<?php echo $row['id']?>" class="button" id="rmlb">Click to Remove </span>
</div>
<?php
}
}
?>
I tried this but it's alerting only the first value out printed by loop please give me a suggestion
First of all, please post corrected and formatted code in future.
Here is what you need:
Collected all PHP output data in an JS array or object
Create a loop in JS to print all array values.
You need to be carefull with alerting each value because it will give a you a popup box for each array item and the annoying popup will never finish. I suggest outpoint them in console to see the result.
Your JS Code:
del_id = document.querySelectorAll (".button");
for(var i = 0; i < del_id.length; i++){
attrValue = $(this).attr('rel');
console.log(attrValue);
//You can also alert it if you wish to:
//alert(attrValue);
}
I am generating divs in PHP, from an array, thus:
echo "<div id='parentdiv'>";
for($counter = 0; $counter < count($list); $counter++){
echo "<div>".$list['important_info']."</div>";
}
echo "</div>";//parentdiv
I want to add some click functionality to each div independently, i.e. the action performed on clicking depends on the div, and more importantly the index of the array, $list;
I want to give each div an id based on it's index in the PHP array.
So I could do
echo "<div id='"."divindex_".$counter."'>".$list['important_info']."</div>";
where "divindex_" is just used to prevent the id form beginning with a numeric value.
Then, I think in jQuery I can write click functions for each div.
However the problem is the $list size is variable, so I don't know how many divs there are.
So what I'm thinking is something like,
$("#parentdiv div").click(function(){
var id = split($(this).attr('id').split("_")[1];//get the php index from the id
//do something with the id, e.g. ajax or whatever
});
Is there a better way to do this? If you think what I'm doing is strange and not a very good idea, then I understand. But I don't know how to do this any other way. Any help appreciated.
Simply use:
$("#parentdiv div").click(function(){
var id = $(this).index(); //index of div, 0 based
var val = $(this).text(); //content of div, if you need it
});
No need to add unique IDs :) .
Demo:
http://jsfiddle.net/q9TaJ/
Docs:
http://api.jquery.com/index/
First, make sure to properly escape your outputs:
echo '<div id="parentdiv">';
for ($counter = 0; $counter < count($list); $counter++){
echo sprintf('<div data-id="%d">%s</div>',
$counter,
htmlspecialchars($list['important_info'])
);
}
echo '</div>';//parentdiv
I'm also using a special attribute called data-id which you can easily access in jQuery with this code:
$('#parentdiv > div').on('click', function() {
var id = $(this).data('id');
});
you can pass your variables as html attributes. Then bind the click event to a single class.
<div class="divs" data-id="myid"></div>
in jquery
$('.divs').click(function(){
console.log($(this).data('id));
});
At the moment, I have an interaction that goes like this:
AJAX call to my site controller -> API content loaded through PHP and
output -> javascript outputting view directly into page
Is there a way to load in HTML from some sort of external file?
I don't want to end up doing something like this, as it makes changing the html messy.
html = '';
for (i = 0; i < jsonData.length; i++) {
html += '<div class="blah"><b>Content goes here<b><br>';
html += '<div class="blah_nested">' + jsonData[i].awesomeness + '</div>';
html += '</div>';
$("#some_div").html(html);
}
Create a php file which contains that code and takes the json response in the request.
example (data.php):
<div class="blah"><b>Content goes here<b><br>
<div class="blah_nested"><?php echo $_GET['jsondata']; ?></div>
</div>
then do:
html = "";
for (i = 0; i < jsonData.length; i++) {
$.get('data.php?jsondata=' + jsonData[i].awesomeness, function(response){
html += response;
});
}
I edited to make it match his original code more directly.
Yes, you can make an html file containing all your repeatable code.
For example in your html file called templates you may have:
<div class="blah"><b>Content goes here<b><br>
<div class="blah_nested"></div>
</div>
Then in your js you can use .get to grab that code.
$.get('templates.html', function(html){
var h = $(html);
var blah = h.find('.blah').html();
});
Now you've got your code. You'll still have to put it in a for loop, and you'll still have to put in your information which would look something like this:
$('blah_nested').text(jsonData[i].awesomeness);
But now you don't have to go to your js to make changes to html. It's a little bit more js code, but it keeps everything separate.
I have a sql query that pulls an array that contains file paths to my images.
It is store in the variable $rows and I can access individual paths by indexing throught...
IE.
$rows[0]...$rows[n]
How can I utilize java script to step through this.
Final goal is for the picture to appear with a "Next" "Previous" button under it.
Hitting next would show the next image (without a refresh)
echo $rows[0];
would print
images/a.png
Maybe using PHP's json functions you can convert your PHP array to a js array... and then use javascript functions to control which picture to show
<script type="text/javascript">
var images = <?php echo json_encode($rows) ?>, counter = 0;
function prevImage() {
counter = (counter<=0)?images.length-1:counter-1;
var i = document.getElementById('myImage');
i.src = images[counter];
}
function nextImage() {
counter = (counter==images.length-1)?0:counter+1;
var i = document.getElementById('myImage');
i.src = images[counter];
}
</script>
and
<img src="img/0.jpg" id="myImage" />
Previous - Next
Here is a little example to move your php array to a javascript array:
<?php
$row = array("image/image1","image/image2","image/image3");
?>
<html>
<head>
<title>Sample Array</title>
<script>
var jsArray = new Array();
<?php
for ($i=0; $i<3; $i++)
{
echo "jsArray[$i] = '$row[$i]';";
}
?>
for(i = 0; i < jsArray.length;i++)
{
alert(jsArray[i]);
}
</script>
</head>
<body>
<span>Sample Array</span>
</body>
</html>
Good luck!
Get your PHP array (server-side) to Javascript (clientside)
There are quite a few ways to go about doing this, but I'd recommend JSON. It has numerous advantages, but the most obvious one is you can store arrays and javascript objects as a string. If you're not familiar with it, this would be an excellent time to start including it in your workflow, considering you have to deal with Javascript.
PHP
Turn Array to JSON:
$jsonResults = json_encode($arrayOfResults);
Get JSON from PHP to Javascript:
<script>
var myAppsData = {};
myAppsData.slideshowJSON = JSON.parse($jsonResults);
</script>
Now your JSON object is accessible to Javascript at myAppsData.slideshowJSON.
The rest of the work is as simple as iterating through the object with a for loop (just like you would in PHP), grabbing the content and doing what you want with it.
Cheers!
I have this jquery code in a foreach loop. Basicaly the variable $perf gets a new value with every loop. How can I use jquery to display the different $perf value with each loop? Is it possible?
foreach ($perfs as $perf):
<script type="text/javascript">
$(document).ready(function(){
var performerName = $(".transparency").data('title');
var divcontent = $(".transparency").html();
if ( divcontent == ' ' ){
$(".transparency").html(''+performerName+'');
}
});
</script>
<div class="transparency" data-title="<? echo $perf; ?>"> </div>
endforeach;
You should do it like this:
<?
foreach ($perfs as $perf):
?>
<script type="text/javascript">
$(document).ready(function(){
var $perf = "<? echo $perf; ?>"; //Get from php
alert($perf); //Show it
//Here goes the rest of your script
var performerName = $(".transparency").data('title');
var divcontent = $(".transparency").html();
if ( divcontent == ' ' ){
$(".transparency").html(performerName);
}
});
</script>
<div class="transparency" data-title="<? echo $perf; ?>"> </div>
<?
endforeach;
?>
That's it. It works.
(I tried to modify your code at least as possible, cause I don't know if I can remove parts)
PS: There would be more 'elegant' solutions, do you want one? or this is enough?
Can you please describe what you are trying to do? I'm about 90% sure there is zero reason for any javascript, jQuery or otherwise.
Why not just do this?
<?php
foreach($perfs as $perf)
{
echo "<div class='transparency' data-title='$perf'>$perf</div>";
}
?>
Unless there is something more you are trying to do, you don't need javascript at all. And even if you do need javascript, take the function out of the loop and call it once each iteration. you dont need the exact same function defined multiple times.
I suggest you look into the relationship between server and client-side scripting. For starters - take a look at the HTML source generated by your PHP and see if thats anything close to what you want. Also, read up about ajax. It seems that you are trying to do combine PHP/javascript in such a way that it needs additional HTTP Requests (ajax calls)
It is impossible to have PHP and javascript interact directly without AJAX, and it is difficult to answer the question without more knowledge of what, exactly, you want to happen.
If you want a different transparacy div for each value of $perfs you can use:
<?php foreach ($perfs as $perf) { ?>
<div class="transparency" data-title="<?php echo $perf; ?>"> </div>
<?php } ?>
And they you can use the jquery .each() to iterate over the divs
$(".transparency").each( function() {
var performerName = $(this).data('title');
// do stuff //
});
If all you want is to pass the values in $perfs to you javascript function you can use
var perfs = <?php echo json_encode($perfs); ?>;
OK I think I see what you are trying to do now. You'll want something like this:
<script type="text/javascript">
$(document).ready(function(){
var perfs = <?php echo json_encode($perfs); ?>;
$.each( perfs, function( index, value ) {
$( ".transparency" ).append( value+'<br>' );
} );
} );
</script>
<div class="transparency"></div>
This will output each value of $perfs inside of the transparency div.
Using JQuery each and append.
You will never want to wrap an entire script in a foreach loop, as that will create a separate script for each element in the array. Using json_encode you will change the PHP array into a javascript object & you can do whatever you want to with it.
Remember javascript is only able to access elements written to the page using echo or something similar. Whatever you can see when you look at 'view page source' in your browser is all your script will be able to use.