How do I add a php variable to a onclick function argument? - javascript

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

Related

echo alert() in php show everything in the string. octobercms plugin

I'm having issue when echoing alert() in php. It show everything in the string.
echo "<script type='text/javascript'>alert('Thank you for your enquiry, we will contact you as soon as possible, have a nice day!');</script>";
Output
You can use javascript code between ending and starting php tags like below,
?>
<script type="text/javascript">
alert('Thank you for your enquiry, we will contact you as soon as possible, have a nice day!');
</script>
<?php
// rest of the php code will go here.
?>
OR try this please,
<?php
echo '<script type="text/javascript">';
echo 'alert("Thank you for your enquiry, we will contact you as soon as possible, have a nice day!");';
echo '</script>';
?>
Solution: I fixed it by removing everything. and just echo the message directly without the alert(). I'm not sure why it behave like this because this is my custom plugin. I will update if I found the source of this behavior. Thank you for all the replies.
echo 'Email Successfully Sent. We will reply soon!';

Generating unique ids via PHP for use in document.getelementID?

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(...)).

Cannot echo .load function

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")';

Javascript event not working

I have this php code below
<?php foreach($items in $item) : ?>
<a class="btn">$item</a>
<?php endforeach; ?>
and this javascript below
$('.btn').click(function() {
console.log('hello');
});
it should work when I click the <a> tag but it's not working.
So, help me please. (Sorry for bad English)
foreach($items in $item) this is wrong. php foreach uses as not in
http://php.net/manual/en/control-structures.foreach.php
Use either
<?php foreach($items as $item) :
echo "<a class='btn'>".$item."</a>"
endforeach; ?>
or
<?php foreach($items as $item):?>
<a class='btn'><?php echo $item>?></a>"
<?php endforeach; ?>
$item must be within <?php ... ?> or it's meaningless to php
Did you add jQuery library link into it? because you used "$".
Just declare jquery library before your script. It should works
https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js
p/s: also fix php syntax as Ramanlfc mentioned above

How can I use HTML code to print it in PHP?

I want to use this HTML code and print it in PHP.
In the HTML code I use this:
<button onMouseover="htmlcode('<img src=\'http://www.chinavalue.net/Special/images/20080529/image/top.jpg\'></img>');">View</button>
How should it be used it in PHP?
I've tried this code:
echo '<button onMouseover="htmlcode('<img src=\'http://www.chinavalue.net/Special/images/20080529/image/$test.jpg\'></img>');">View</button>';
But unfortunately, this is not working.
you mix up your quotes
if you use ' quotes in the echo statement, you cannot use them (or have to escape them) in the string
the best solution here is escape the single quotes in your string, so they don't mark the end of the echo command
echo('<button onMouseover="htmlcode(\'<img src=\'http://www.chinavalue.net/Special/images/20080529/image/top.jpg\'></img>\');">View</button>');
If you want to use it in some kind of an if statement then you can go for this:
<?php if( /*your condition*/ ) :?>
<button onMouseover="htmlcode('<img src=\'http://www.chinavalue.net/Special/images/20080529/image/top.jpg\'> </img>');">View</button>
<?php endif; ?>
Note this way you can write long snippets of html easily, which is not the case with echo.
If this is not conditional, then just do something like this:
<?php // some php code
// some more php
?>
<html>
Your html here
</html>
<?php // next section of php
// more php
?>
The parts between the php sections will be outputed just as if they were put into an echo statement.
If you want to see the html in the browser then you can use.
print htmlspecialchars("<button onMouseover="htmlcode('<img src=\'http://www.chinavalue.net/Special/images/20080529/image/top.jpg\'></img>');">View</button>")

Categories