I'm trying to use php to go through an array via a for loop. I'd like to create objects of each of the items in the for loop, and when the objects are clicked, they'll turn into a different color. To do so, I'm using document.getElementId() which requires unique IDs. I've tried to generate these unique IDs as per below, but it seems that when I click the object, it's not changing color so the ID isn't exactly working. Here's the code below:
<?php $i = 0;?>
<button class = "answerchoice" id="c1"+<?php echo $i; ?>><?php echo $data['C1']; ?></button>
<script>
document.getElementById("c1"+[<?php echo $i; ?>]).onclick = function() {
document.getElementById("c1"+[<?php echo $i; ?>]).style.backgroundColor = "#abebbd";}
</script>
Your formatting is slightly off. The echo $i needs to be inside the quotes for the id attribute. The plus sign is also extraneous(you are not concatenating here, the value is literally being output. Additionally, in PHP, concatenation is performed with the "." operator).
<button class = "answerchoice" id="c1<?php echo $i; ?>"><?php echo $data['C1']; ?></button>
You may also consider the alternate echo syntax which is more concise.
<button class = "answerchoice" id="c1<?= $i ?>"><?php echo $data['C1']; ?></button>
Additionally, you could benefit from assigning the id to a local variable rather than rebuilding it in three places. The same could apply to selecting the element in JavaScript(var button=document.getElementById(...)).
Related
Beginner JS here.
I am trying to add a PHP variable to a Javascript onclick function. I converted the PHP variable to a JS variable just fine. However, when adding the JS variable to the function I'm not receiving the desired output. What am I doing wrong?
<script>
js_logo_number = "<?php echo $logo_number; ?>";
</script>
<img src='<?php echo $image1[0]; ?>' onclick="openModal();currentSlide(js_logo_number)">
You can do like this :
<img src='<?php echo $image1[0]; ?>' onclick="openModal();currentSlide(<?php echo $logo_number; ?>)">
This code works for me. Be sure you use a let or const (or the outdated var) prefix to declare js_logo_number a new variable. Also make sure that $logo_number is set like this:
<script>
let js_logo_number = <?php isset($logo_number)?$logo_number:null; ?>;
</script>
Then make sure you convert it to an integer in Javascript, if that's how you want to use it:
function currentSlide(num){
console.log('currentSlide fired', parseInt(num));
}
let js_logo_number = "5";
function openModal(){
console.log('openModal fired');
}
function currentSlide(num){
console.log('currentSlide fired', parseInt(num));
}
<img src='https://placekitten.com/200/200' onclick="openModal();currentSlide(js_logo_number)">
When PHP parses a file, it looks for opening and closing tags, which are which tell PHP to start and stop interpreting the code between them. Parsing in this manner allows PHP to be embedded in all sorts of different documents, as everything outside of a pair of opening and closing tags is ignored by the PHP parser.
See: PHP tags
1) echo
<?php echo 'if you want to serve PHP code in XHTML or XML documents, use these tags'; ?>
Solution:
<img src='<?php echo $image_src ?>'
onclick="openModal();currentSlide(<?php echo $logo_number ?>)">
2) Short echo
You can use the short echo tag to <?= 'print this string' ?>.
It's equivalent to <?php echo 'print this string' ?>.
Solution:
<img src='<?= $image_src ?>'
onclick="openModal();currentSlide(<?= $logo_number ?>)">
3) If short_open_tag is enabled
<? echo 'this code is within short tags, but will only work '
.'if short_open_tag is enabled'; ?>
Solution:
<img src='<? echo $image_src ?>'
onclick="openModal();currentSlide(<? echo $logo_number ?>)">
See: PHP tags
For some reason this code doesn't work. Adding \ to the front of the $ doesn't change anything. Can anyone see the problem?
$commentid = 2; //for example
echo "<script>";
echo "<div id = 'commentinput".$commentid."'>";
echo "</div>";
echo "$('#commentinput".$commentid."').load('editcomments2.php')";
echo "</script>";
Do it like this:
echo '$("#commentinput'.$commentid.'").load("editcomments2.php")';
I'd suggest not using echo to output HTML (in most cases anyway), but closing the PHP tag instead.
This becomes (edited with a loop example, see comments below):
<?php while ($commentid = $dbObject->dbMethod()): ?>
<div id="commentinput<?= $commentid ?>">
</div>
<script>
$('#commentinput<?= $commentid ?>').load('editcomments2.php');
</script>
<?php endwhile ?>
Note that in this case, the <script> portion should probably be outside of the loop, with a jQuery selector matching all the comment inputs.
So besides all of the other answers, I found another solution to!
When echoing out js code, like
echo '$("#commentinput'.$commentid.'").load("editcomments2.php")';
//and
echo "alert('stuff')";
it might then print it out like: $("#commentinput2").load("editcomments2.php")alert('stuff') and the code will get confused. So lastly I need to added a semicolon to prevent the program from reading all my code as just 1 line:
echo '$("#commentinput'.$commentid.'").load("editcomments2.php")';
So I didn't found what I was looking for in last two days.
To be clear I have a table "tracks" in my database.
So I can show from "tracks" the "demo" field wich is an audio file "url"..
<?= $tracks['demo']; ?>
I have multiple url's but then I need to replace the a href
<a href="<?php echo $tracks['demo'];?>"
in a logical way.
In simple terms it's like I want to click on button 1 that loads
url 1 into this a href with the ID, title field from that track.
When you press button 2 you need to load another url and replace url 1 with url2.
I tried many ways including javascript but it won't work.
Problem now is that when I list 4 items it always loads the latest "URL" i have posted in my source code. :)
When I echo out <?php echo $tracks['demo]; ?> on all items I can see the correct url's so the functionality to replace the url is my issue.
* I basically want to load many mp3 url's in a player I made in the footer of my website. It works by hardcoding the urls in the url field but this is not what it should be... *
Code:
<?php while($tracks = mysqli_fetch_assoc($muziek)) : ?>
<div class="col-md-2 viny" id="muziek">
<h4><?= $tracks['title']; ?></h4>
<img src="<?= $tracks['img']; ?>"
alt=" <?= $tracks['title']; ?> />
<p class="artist">Artist: <?= $tracks['artist']; ?></p>
</div>
<?= $tracks['demo'] = $audiourl ; ?>
<button type="button" onclick="play">Play</button>
</div>
<?php endwhile; ?>
*THIS LOOPS PERFECT FOR ALL ITEMS TRACKS ARE LISTED PERFECT *
In my player I have
<a href="<?php echo $audiourl;?>" ><?= $tracks['artist']; ?></b> - <?= $tracks['title']; ?></a>
function play(){
I'm not good at JS... And this is my issue because it now loads the latest output from the php loop...
}
I don't know how you are replacing it but
Why not pass the audio in the function. Here like this
<button type="button" onclick="play(<?= $tracks['demo'] = $audiourl ; ?>)">Play</button>
assign a id to anchor tag
<a id="someId" href="<?php echo $audiourl;?>" ><?= $tracks['artist']; ?></b> - <?= $tracks['title']; ?></a>
and in the play function, you receive it like this
function play(audioUrl){
}
and change the href like this in the play function
If you are using jquery
$('#someId').attr("href", audioUrl);
sometimes the above does not works. Can't remember why but if that does not works try this
$('#someId').href = audioUrl
If you are using javascript
document.getElementById('abcd').href = audioUrl
So I tried many things but I had many issues with the player it's js file using the same id's and so on.
The new logic I tried out seems to work:
<form action="" method="POST">
<input type="submit" value="Play" name="Play">
</form>
<?php
if (isset($_POST["Play"]))
{
echo $tracks['demo'];
}else{
echo ' ';
}
?>
There is more going on but I tried to write it down as simple as this to show the logic. All Track url's are hidden and when the page loads there is an empty $audiourl by default loaded in the a href from my audioplayer. By clicking the button play I show the url in the source but not on the site.
Then the latest $audiourl variable changes to this value.
Not sure how to do this. I get a list of projects using php and mysql.
I display the project using a loop. Then using jquery click() I wanna grab the html of the element where I displayed the project name to use the name somewhere else, but it doesn't matter what project I click, I always get only the first project of the loop.
here is the code:
<?php foreach ($projects as $project): ?>
<li class="todo-projects-item" data-projectid="<?php echo $project->project_id ?>">
<h3 id="p_name" data-proname="<?php echo $project->project_name ?>"><?php echo $project->project_name ?></h3>
<p><?php echo $project->project_body ?></p>
<div class="todo-project-item-foot">
<p class="todo-red todo-inline">Project #<?php echo $project->project_id ?></p>
<p class="todo-inline todo-float-r">32 Members
<a class="todo-add-button" href="#todo-members-modal" data-toggle="modal">+</a>
</p>
</div>
</li>
<div class="todo-projects-divider"></div>
<?php endforeach; ?>
It gives me the following:
I'm using this in my script with the click function:
pName = $('#p_name').data('proname');
alert(pName);
It doesn't matter what project I click, it always alerts "The Project", the first within my array... what am I doing wrong?
What element is the click handler on?
The issue is that you're using $('#p_name'), but you actually have many elements on the page with that same ID. This is actually a big no-no... element IDs should always be unique.
If the click handler is on the <li> tag, something like this should work better:
$('.todo-projects-item').click(function (e) {
e.preventDefault();
alert($(this).find('h3').data('proname'));
});
You should use $(this) to get the clicked element.
$("h3").click(function() {
var pName = $(this).data("proname");
alert(pName);
});
And, if you're hooking the click event to a parent of the h3, you can use $(this).find("h3") to grab it.
One ID in a page should be only once. #p_name can be used only once. If you need to use that multiple time use it as a class .p_name and in your script change it:
<h3 class="p_name" data-proname="<?php echo $project->project_name ?>"><?php echo $project->project_name ?></h3>
Im using php to collect my instagram feed however all the images php collects using the instagram api are all placed in the same location(or same div) so i recieve my images
<?php foreach ($result->data as $post): ?>
<div class="images">
<!-- Renders images. #Options (thumbnail,low_resoulution,high_resolution)-->
<a class="group" rel="group1" href="<?= $post->images->standard_resolution->url ?>"><img src="<?= $post->images->thumbnail->url ?>"></a>
<?php endforeach ?> </div>
so all the images collected are turned into links and are all placed in the div images so what i would like to do is equally distribute all 20 images received into these 3 different divs using php or js.
<div class="col-md-4"></div>,
<div class="col-md-4"></div>,
<div class="col-md-4"></div>
This is my first post, code might be awkward. Thanks for the help.
Well, I've gone ahead and built out a proper full solution. It works by first building an array of response objects, then chunking them out for display. If you want to split them up, you'll pretty definitely need to put them into a sub-buffer, like the $results buffer you see below.
<?php
$results = array();
foreach ($result->data as $post):
// Using output buffering as a simple means of building HTML.
ob_start();
?>
<a class="group" rel="group1" href="<?= $post->images->standard_resolution->url ?>">
<img src="<?= $post->images->thumbnail->url ?>">
</a>
<?php
$results[] = ob_get_contents();
ob_end_clean();
endforeach;
// Now we have an array of elements as HTML. We'll chunk them
// into 3 arrays. We could also randomize or other things here.
$chunked = array_chunk($results, 3);
?>
<div class="col-md-4"><?=implode("\n", $chunked[0])?></div>
<div class="col-md-4"><?=implode("\n", $chunked[1])?></div>
<div class="col-md-4"><?=implode("\n", $chunked[2])?></div>
You will need to split your array and then iterate it within your desired div tag.
Example:
<?php
$chunked = array_chunk($array, 3);
foreach ($chunked as $value) {
foreach($value as $v) {
echo '<div class="col-md-4">';
print_r($v);
echo '</div>';
}
}