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>';
Related
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.
I have a php array of result $bank_r. I want to perform some results in all of the results. For that I wrote :
$(function(){
//alert('<?php echo count($bank_r); ?> ');
<?php
for($i=0;$i<count($bank_r);$i++)
{
$bank_name = strtolower (str_replace(" ","",$bank_r[$i]['bank_name']));
?>
alert('<?php echo $bank_name; ?>');
<?php } ?>
-------------
----------
//Some other jquery functions
//
//
});
I was expecting to alert the $bank_name, but it is not. Even the top alert('<?php echo count($bank_r); ?> '); also not alerting anything. But If I remove the php for loop, the top alert alerts the number of results. Whats wrong ?
EDIT:
Generated javascript code:
<script>
$(function(){
//alert('5 ');
alert('ucobank
');
alert('pnb');
alert('bob');
alert('sbi');
alert('hdfc');
//Other javascripts
});
Try this,
<?php
for($i=0;$i<count($bank_r);$i++)
{
$bank_name = strtolower (str_replace(" ","",$bank_r[$i]['bank_name']));
echo '<script> alert("'.$bank_name.'");</script>';
// if you are outside the javascript then use script tag, otherwise remove the tags
}
?>
New line in first alert is problem. It causes JS parse error and because of that alerts will not appear. You have to replace newline to eg. spaces by str_replace("\n", ' ', $string);.
<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.
EDIT: What a TW*T. Sorry everyone for wasting your time. Just missed a Google jQuery link on one F'in page. Whoops.
Hi, i have a div containing 3 forms. These should be the only thing on the screen on page load. When any of them are submitted, a graph gets shown below. What i'm trying to do is within the PHP IF statement is make the div disappear that contains the forms. Sound simple?
This is my code:
if($_GET['submit1']){
echo "<script type='text/javascript'>$('#options').css('display','none');</script>";
However, when i do submit one of the forms (therefore a $_GET has occurred) the div is still there??
EDIT:
If i try people answer on one line i get this:
Parse error: syntax error, unexpected '(', expecting T_VARIABLE or '$'
But if i put in people's multiline answers, no error, but div still shows!
Why do you want to hide the forms with JavaScript?
Simply do it with PHP:
<?php
if(!isset($_GET['submit1'])) {
?>
//<form> your form HTML here
<?php
} else {
?>
<p>Your submitted data: <?php print_r($_GET); ?></p>
<?php
}
?>
So your forms are only shown if you have NOT submitted one of them. You might have to adjust the parameters if you have multiple forms, for example
if(!isset($_GET['submit1']) && !isset($_GET['submit2'])) {
Edit: If you want to keep your forms after submitting but only hide it, you could do it that way:
<?php
$formsVisible = !isset($_GET['submit1']));
$formsDisplay = $formsVisible ? 'block' : 'none';
?>
<form style="display:<?php echo $formsDisplay; ?>">
<!-- ... --->
</form>
You need to add a DOM ready event:
if($_GET['submit1']) {
echo '<script type="text/javascript">' . "\n";
echo ' $(function() {' . "\n";
echo ' $("#options").hide();' . "\n";
echo ' });' . "\n";
echo '</script>' . "\n";
}
edit
You are getting a parse error because you're using double quotes, so the php parser is reading the dollar sign as a php variable. I would switch to a single quote php syntax to make your life easier:
if($_GET['submit1']){
echo '<script type="text/javascript">
$(function(){
$("#options").css("display","none");
});
</script>';
}
Be sure to wrap your jquery code in the onLoad function $(function(){};
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>";