PHP within an Echo PHP - php

I have the following code, but the echo $jsonData[$i] line gives an error. I know you are not supposed to execute PHP within PHP. What is the correct way to accomplish this?
<?php
if( !is_user_logged_in() ){
echo 'Im online. Login to Chat';
} else {
echo '<input type=\"submit\" onclick=\"javascript:jqcc.cometchat.chatWith(' <?php echo $jsonData[$i]; ?> ');\" value=\"Chat Now\" class=\"success button small\"
\" >';
}
?>

You use the concatenation operator . instead of echo when you're already within the scope of a string:
echo '<input type="submit" onclick="javascript:jqcc.cometchat.chatWith(' . $jsonData[$i] . ');" value="Chat Now" class="success button small">';
Also, you don't need the backslashes unless you're using the same quotes to start and end the string. In your case you open/close with single quotes, so double quotes don't need to be escaped.

Once you're in PHP mode (i.e. reach the opening <?php tag), everything is read as code until you exit PHP mode (i.e. reach the closing ?> tag). So there's no need to reopen those tags when they've already been open. See the basic syntax section of the manual for more details about this.
One of PHP's best features is that it allows you to embed code in HTML, rather than having to embed HTML in code. It's actually much easier to read your code when you write it like this, for example...
<input type="submit" onclick="javascript:jqcc.cometchat.chatWith(<?= $jsonData[$i]; ?>);" value="Chat Now" class="success button small">
Notice we only use PHP to print the value of $jsonData[$i] where it's needed and everything else is just plain/text or HTML that gets printed.
Also, note I'm using the short-hand form of <?php echo which is just <?=.
To expand on this a little, one of the reasons this idea of embeding code in HTML is so useful, is that it allows you to easily and transparently separate code from data.
<?php
$loggedIn = is_user_logged_in();
if ($loggedIn) {
?>
<input type="submit" onclick="javascript:jqcc.cometchat.chatWith(<?= $jsonData[$i]; ?>);" value="Chat Now" class="success button small">
<?php
} else {
?>
<h1>ohnoes, you're not logged in :(</h1>
<?php
}

Related

Too many quote marks - How would I echo this without closing them up

Basically I want to have my spoiler thingy inside an echo, but can't get it to work due to the quotes marks confusing me, hah.
echo "<input class='spoilerbutton' type='button' value='Register' onclick='this.value=this.value=='Register'?'Cancel':'Register';'><div class='spoiler'><div>woooohoo hide this text</div></div>";
As you can see by the 'register'?'cancel' part, there are quotes that gets closed by one another.
How could I fix this the most simple way? I'm getting too confused, lol.
Don't put HTML inside PHP strings if you can help it. Turn it inside out.
if (somecondition) {
?>
<input
class='spoilerbutton'
type='button'
value='Register'
onclick="this.value=this.value=='Register'?'Cancel':'Register';">
<div class='spoiler'>
<div>woooohoo hide this text</div>
</div>
<?php
} else {
}
For that matter, don't put JavaScript inside HTML attributes if you can help it.
<input
class='spoilerbutton'
type='button'
value='Register'>
<script>
var input = document.querySelector('input.spoilerbutton')l
input.addEventListener('click', toggleValue);
function toggleValue(evt) {
this.value=this.value=='Register'?'Cancel':'Register';
}
</script>
You can escape the quotation marks like so
echo "<input class='spoilerbutton' type='button' value='Register' onclick='this.value=this.value==\"Register\"?\"Cancel\":\"Register\";'><div class='spoiler'><div>woooohoo hide this text</div></div>";

Storing button inside of php variable

I have following code:
$boxId = 1;
$explainationBox='<input type="button" id="<?php echo $boxId; ?>" value="send" onmousedown="javascript:callthis(<?php echo $buttonId; ?>);" class="button" />';
echo $explainationBox;
I am trying to save these values as html button inside of php variable explainationBox. But its not saving actual value of $boxId. It is just saving it as $boxId. As boxId is inside a for loop and will keep on changing. How can i do this?
You do not nedd <?php tag when this tag is already opened
Try this
$boxId = 1;
$explainationBox='<input type="button" id="'.$boxId.'" value="send"
onmousedown="javascript:callthis('.$buttonId.');" class="button" />';
echo $explainationBox;
PHP tags in a string are not parsed (unless given to some functions such as eval()).
Use string concatenation.
Change this...
"<?php echo $boxId; ?>"
...to...
"' . $boxId . '"
You may find it useful to enter and exit the php environment within the loop so you don't have so save that string as a variable at all.
for($i=1; $i<10; $i++){?>
<input type="button" id="ID<?=$i?>" value="send"
onmousedown="javascript:callthis('<?=$i?>');" class="button" />
<?php } ?>
So what we are doing is leaving the php environment as we open the loop (?>) then we give some raw html that will be plopped into the page as shown, no variable needed. Then while we are outside the php environment we use the <?= $variable ?> syntax to drop a php variable into the html language. And finally we re-enter the php environment by reopenning the php tags (<?php).
Note: That last ?> would go wherever you wanted to re-exit php again.
This code is working:
$boxId = 1;
$explainationBox='';
echo $explainationBox;
except for: "javascript:callthis('.$buttonId.');" call. In order to make this whole code work here is a solution for those who are looking:
$boxId = 1;
$explainationBox='';
echo $explainationBox;

unable to get my window.location to work within echo tag

echo "<form><input type='button' value='$back_label' onclick='window.location="'$url'"'/></form>";
I cant figure the whole single and double quotes thing when it comes to the window.location code because it has an extra set of single quotes to wrap around the url. I have no idea what to do. I tried escaping the quotes.
Also, can you use a relative path for this method?
Thanks
Try this
echo "<form><input type='button' value='$back_label' onclick='window.location=\"$url\"'/></form>";
A working example on http://codepad.org/K7AafokT
Can you take it out of the PHP context?
<?php $url = 'http://www.yourdomain.com'; ?>
<form>
<input type='button' value='<?php echo $back_label;?>' onclick='window.location="<?php echo $url;?>"'/>
</form>
Just change the quotes at the end to onclick='window.location="$url"'/>
echo "<form><input type='button' value='$back_label'
onclick='window.location="$url"'/></form>";
I believe to meet the HTML 'standard' the almost all attributes must use double quotes and for javascript you need to encapsulate the url so:
echo '
<form>
<input type="button" value="'.$back_label.'" onclick="window.location=\''.$url.'\'" />
</form>';
EDIT
A cleaner way to code this is to use heredoc syntax as it eliminates the need for escaping:
echo <<<EOL
<form>
<input type="button" value="$back_label" onclick="window.location='$url'" />
</form>';
EOL;
UPDATE
You are able to go down a directory structure, and I just did a quick test and it appears to work going up the hierarchy as well.

Why doesn't my PHP-generated javascript work?

i have the following javascript code
echo ' <span style="padding-left:0px"><input type="submit" name="r" style="width: 138px; font-weight:bold; " value="Add item"/></span>
';
i am trying to execute the script from within a php script. when i click on the button to execute the java part of it, nothing happens. i then try it this way
echo ' <span style="padding-left:0px"><input type="submit" name="r" style="width: 138px; font-weight:bold; " value="Add item"/></span>
';
and got this parse error: parse error, expecting '," or';".
You have to escape apostrophes in a string in php. Instead of
echo '(...) style.display='block' (...)';
do
echo '(...) style.display=\'block\' (...)';
That being said, try to split your code over multiple lines so it is at least somewhat readable. You can also write HTML in php like this:
<?php
// php code
echo 'php';
?>
<HTML code>
<?php
// more php code
echo ' <span style="padding-left:0px"><input type="submit" name="r" style="width: 138px; font-weight:bold; " value="Add item"/></span>
';
This will not work because the single quote params in the JS echo are breaking the PHP flow. Try adding break characters before each single quotation in the echo, not sure what it is in PHP but try \'
IE:
Id('items')
becomes
Id(\'items\')
This has nothing to do with PHP.
You are using " quotes to delimit JavaScript strings inside an HTML attribute values delimited using " characters.
As a result, the first " inside the JS terminates the HTML attribute value.
The quick hack is to use " instead of " inside the attribute value.
The better solution is to use unobtrusive JavaScript

How do I make my javascript character counter work inside php?

I have a javascript character counter that I use inside of a text area. It works great in normal html, but when I put the exact same code inside of a text area inside php, nothing.
Here it is in html when it works fine:
<div id="counter">
<span id="counter_airway" style="font-size:11px; color:#666666;">140 Character Limit</span>
</div>
<div id="grapvine_text">
<form name="CommentBox" method="post" action="Profile.php?id=<?php echo $prof->id; ?>">
<textarea name='airway' class='round_10px' onkeyup="limit_length(this,140,'counter_airway');"></textarea>
</form>
Here it is implemented inside my php form:
<div id="commentBoxBlog">
<form name="CommentBox" method="post" action="Profile.php?id=<?php echo $prof->id; ?>">
<?php
if($auth->id == $prof->id) {
echo "<div id='counter'>
<span id='counter_airway' style='font-size:11px; color:#666666;'>140 Character Limit</span>
</div><textarea name='airway' class='round_10px' onkeyup='limit_length(this,140,'counter_airway');'></textarea>
<input type='submit' name='commentProfileSubmit' value='Exhale' class='post'/>";
}
elseif(!$auth) {
echo "<textarea name='ProfileComment' class='round_10px' disabled>Please sign in to comment...</textarea>";
}
elseif($auth->id != $prof->id) {
echo "<textarea name='ProfileComment' class='round_10px'></textarea>
<input type='submit' name='commentProfileSubmit' value='Exhale' class='post' />";
}
?>
</form>
</div>
</div>
need to escape the quote, instead of:
onkeyup='limit_length(this,140,'counter_airway')
you can do:
onkeyup='limit_length(this,140,\"counter_airway\")'
You've got a quote nesting issue. You're surrounding the onkeyup attribute of the textarea with single quotes, but also using single quotes inside that javascript snippet. Since you're using double quotes for the PHP string, use escaped double quotes (\") within your javascript snippet.
Of course, it would be even better to separate javascript into an external file, and bind to the keyup event. You could do this easily by assigning an id to your textarea, and calling the following sometime after the DOM is ready:
var textarea = document.getElementById('myTextarea');
textarea.onkeyup = function() { limit_length(this,140,'counter_airway'); }
PHP works entirely on the server side. Your browser never sees a trace of PHP, just the HTML code generated by your PHP script. Javascript works entirely on the client side.
Whether your HTML comes from coding by hand, or a HTML script, is essentially not important. What you need to look at is the HTML that your script produced in the browser's "View Source" mode. Please post that into your question as well.
You have changed some of the double quotes to single quotes. This will cause errors, for example here:
onkeyup='limit_length(this,140,'counter_airway');'
Compare this to the original:
onkeyup="limit_length(this,140,'counter_airway');"
You need to escape the quotes rather than changing them:
onkeyup=\"limit_length(this,140,'counter_airway');\"

Categories