Javascript inside php not working properly - php

<div class="interactionLinksDiv">
REPLY
</div>
I have call the javascript function toggleReplyBox with five parameters. This code is written inside the php tags. But this code is not executing properly and the parameters are not being passed properly. If I call the function toggleReplyBox here with no parameters it works fine but thats not what I want.
<div class="interactionLinksDiv">
REPLY
</div>
When I copied this code to the html part of my php file It works fine and the parameters are passed and the function executes properly.
But I want to know why the function is not able to work inside of the php tags when everything is the same.
function toggleReplyBox(sendername,senderid,recName,recID,replyWipit) {
$("#recipientShow").text(recName);
document.replyForm.pm_sender_name.value = sendername;
document.replyForm.pmWipit.value = replyWipit;
document.replyForm.pm_sender_id.value = senderid;
document.replyForm.pm_rec_name.value = recName;
document.replyForm.pm_rec_id.value = recID;
document.replyForm.replyBtn.value = "Send";
if ($('#replyBox').is(":hidden")) {
$('#replyBox').fadeIn(1000);
} else {
$('#replyBox').hide();
}
}
Inside the php tags I changed the code :
print <<<HTML
<div class="interactionLinksDiv">
REPLY
</div>
HTML;
And it is still showing the error
Parse error: syntax error, unexpected T_VARIABLE in C:\xampp\htdocs\Fluid Solution\fluid-solution-website-template\interact\profile1.php on line 130
Line 130 is the <a href... line.

The first version of your code is neither PHP (javascript/HTML tags are "naked") nor Javascript: the "." string concatenation operator won't work in Javascript, nor will the $variable expansion.
You can get it to work in PHP like this:
<?php
$fullname = "Test";
$current_id = 15;
$id = 9;
$thisRandNum = 42;
// All lines beyond this point, and...
print <<<HTML
<div class="interactionLinksDiv">
<a href="javascript:toggleReplyBox('$fullname','$current_id',
'$current_id','$id','$thisRandNum')">REPLY</a>
</div>
HTML;
// ...up to here, start at the first column (i.e. they are not indented).
?>
Note that within the here-document (area between <<<HTML and HTML), you can't use the string concatenation operator "." (or any other).
Or you can do as you did in the second version of your code, replacing only the variables with <?php echo $variablename; ?> and leaving all the rest as HTML.
As a simpler example let's consider an alert() box with message sent from PHP. This means that:
1) the script is executed server side; anything between <?php ?> tags is executed, and its output replaces the tags themselves.
After this phase, we no longer have PHP but a mix of HTML and Javascript, which can be executed by the client it's sent to. So we want to have a HTML like
<script type="text/javascript">
alert('Hello, world');
</script>
To do this we can generate all the HTML in PHP:
echo '<script type="text/javascript">';
echo "alert('$message');"; // or also: echo 'alert("' . $message . '");';
echo '</script>';
Or we can do it with a here-document, where operators do not work, but $variables do:
echo <<<HEREDOCUMENT
<script type="text/javascript">
alert('$message');
</script>
HEREDOCUMENT;
Or we can run it all in HTML, and only rely on PHP to generate the lone variable:
<script type="text/javascript">
alert('<?php echo $message; ?>');
</script>
But always you need to keep separated what it's being done in PHP, what in Javascript, and what is in the HTML markup.

Related

How to echo javascript code which contains php tags inside?

I usually echo script alert by simply
echo '<script type="text/javascript">alert("'.$my_message.'");</script>';
but how to echo the script when the script contains php tags? (see my example code)
Because of my php obfuscator script, I have to use only one <?php ?> tag. so in this case I need to echo the javascript without having <?php tags. What are the possible solutions in this case?
<?php
...some php code...
<script type="text/javascript">
jQuery(document).ready(function($){
$i = 0;
$('.wrapper_vertical_menu .megamenu_menu').append('<div class="more-wrap"><span class="more"><?php echo $this->__("More"); ?></span></div>');
$('.wrapper_vertical_menu .megamenu_menu > li.megamenu_lv1').each(function(){
$i ++;
if($i>13){
$(this).css('display', 'none');
}
});
... more js code ...
JavaScript doesn't "contain PHP tags". All your PHP code needs to do is build the resulting output string (which happens to be JavaScript code, but that doesn't matter to PHP) and echo it.
So where you have something like this:
echo "some javascript code <?php echo some_php_value; ?> more javascript code";
What you really want, quite simply, is this:
echo "some javascript code " . some_php_value . " more javascript code";
Don't try to nest <?php ?> tags within each other. Just concatenate the actual output you want and echo that output.

PHP variable inside onclick function?

I have a PHP file. In this I have to write html. Also instead of closing PHP tag every time, I just use echo 'html code';
So my code is like:
<?php
$mid = 1;
echo '<div class="message_wrap"><span onclick="viewMessage(1)">Click</span></div>';
?>
<script>
function viewMessage(id){
alert(id);
}
</script>
It gives me 1 in alert but I want to use $mid in onclick function but it breaks my code. I used this:
echo '<div class="message_wrap"><span onclick="viewMessage("'.$mid.'")">Click</span></div>';
but I got nothing on clicking and when I see generated HTML it is breaking like this
<div class="message_wrap"> <span 1")"="" onclick="viewMessage(">Click</span> </div>;
<?php
$mid = 1;
?>
<div class="message_wrap"><span onclick="viewMessage(<?php echo $mid;?>)">Click</span></div>
But I don't want to close and open PHP tag as I have large code, so it does not look good.
How can I get it to work?
It returns "Uncaught SyntaxError: Unexpected token }" error because the parameter you passed has space before it and "="" after ) because of that approach
to fix it change your
echo '<div class="message_wrap"><span onclick="viewMessage("'.$mid.'")">Click</span></div>';
to
echo '<div class="message_wrap"><span onclick="viewMessage(\''.$mid.'\')">Click</span></div>';

Order of inclusion and interpretation for php and html

I am trying to display different content on a page based on some options.
Also, I am trying to avoid using php echo for all the html output.
I came up with the following solution accidentally, and now I'm confused about how it actually works.
test.php
<?php
function get_content() {
$page = 0;
if($page == 0)
include('page0.php');
else
include('page1.php');
}
?>
<html>
<body>
<?php echo get_content() ?>
</body>
</html>
page0.php
<?php
$link = "http://www.google.ca";
$name = "GOOGLE";
?>
<?= $name ?>
page1.php
<?php
$link = "http://www.yahoo.ca";
$name = "YAHOO";
?>
<?= $name ?>
It seems like the php interpreter would end up including html tags into a <?php ?> block when it reaches the following line, but somehow, this code works, and the outputted html is valid.
include('page0.php');
Can someone explain what exactly is going on here?
When a file is included, parsing drops out of PHP mode and into HTML
mode at the beginning of the target file, and resumes again at the
end. For this reason, any code inside the target file which should be
executed as PHP code must be enclosed within valid PHP start and end
tags.
From PHP manual, include function.

How to use variable defined in one php tag in another php tag?

I wrote a php page which has two php tags and one script tag inside it .
<?php
$value = $_GET['hash'];
?>
<script>
function execute(){
<?php
$readfile = file($value);
for ($k=0;$k<=count($readfile)-1;$k++){
$cmd = $readfile[$k];
echo $cmd;}
?>
}
</script>
I want to use $value inside another php tag ( like above it has the file I want to open ), but I am not able to do it.Is the scope of variable limited to one php tag ? if yes how can I solve this problem Please help
Your code works perfectly. The variables in one PHP tag is accessible from all other tags, unless you define them inside a PHP function.
The reason you are not seeing the echo on the screen is because the echo prints to the Javascript function.
If you view the source of the generated page, the file contents will be there.
Try this:
function execute(){
<?php
$readfile = file($value);
for ($k=0;$k<=count($readfile)-1;$k++){
$cmd = $readfile[$k];
?>
alert( <?php echo $cmd; ?> );
<?php
}
?>
}
execute();
if $value is a get then you don't need to access it as a file, it should just be a short string.
just above line 7 (the one with $readfile = file...
type:
echo "alert(The hash value is: ".$value.")";
This will make an alert display (as it is in a script tag)
p.s you should have in your opening tag

PHP: using the eval function with HTML and PHP code

I currently have the following code coming from a database table:
<h1 class="widgetHeader">My Friends</h1>
<div class="widgetRepeater">
<p class="widgetHeader">Random Selection</p>
<?php
$friends = $user->getFriends();
?>
<p class="widgetContent">
<?php
for ($i=0; $i<count($friends);$i++) {
$friend = $friends[$i];
?>
<span class="friendImage" style="text-align:center;">
<?php print $friend->username; ?>
</span>
<?php
}
?>
</p>
</div>
Now, ive tried using the eval function in php but i get a parse error unexpected '<'. I've also tried using the output buffer method (ob_start) without success too. Any ideas as to how i can get this code to evaluate without giving me an error?
note: the database code is stored in a variable called $row['code'].
The PHP eval function expects PHP code to execute as it's parameter, not HTML. Try enclosing your DB values with PHP close and open tags:
eval('?>' . $row['code'] . '<?php');
eval = evil!
Especially if the eval'd code comes from a db... one mysql injection = full php execution = full control.
Rather use some placeholders and replace them (like any other good templating system does).
You could store this in your database:
<h1 class="widgetHeader">My Friends</h1>
<div class="widgetRepeater">
<p class="widgetHeader">Random Selection</p>
{%friendstemplate%}
</div>
Then str_replace the placeholders with the content they should have. In your example i would also add a subtemplate per friend like this:
<span class="friendImage" style="text-align:center;">
{%username%}
</span>
... which you could loop and insert into {%friendstemplate%}.
You cant use eval on markup code. Either save the code to a temporary file so that you can include it, or rewrite the code so that it's not markup, something like:
print "<h1 class=\"widgetHeader\">My Friends</h1>";
print "<div class=\"widgetRepeater\">";
print "<p class=\"widgetHeader\">Random Selection</p>";
$friends = $user->getFriends();
print "<p class=\"widgetContent\">";
for ($i=0; $i<count($friends);$i++) {
$friend = $friends[$i];
print "<span class=\"friendImage\" style=\"text-align:center;\">";
print $friend->username;
print "</span>";
}
print "</p>";
print "</div>";

Categories