Double quotes within php script echo - javascript

I have a line of php code that looks like this:
echo "<script>$('#edit_errors').html('<h3><em>Please Correct Errors Before Proceeding</em></h3>')</script>";
I would like to know how to add a font color to the text correctly.
If I do this:
echo "<script>$('#edit_errors').html('<h3><em><font color="red">Please Correct Errors Before Proceeding</font></em></h3>')</script>";
The word "red" is in black text and the compiler throws an error.
If I use single quotes around red, then the text does not show up at all.
Any help would be great.
Thanks

You need to escape ", so it won't be interpreted as end of string. Use \ to escape it:
echo "<script>$('#edit_errors').html('<h3><em><font color=\"red\">Please Correct Errors Before Proceeding</font></em></h3>')</script>";
Read more: strings and escape sequences

use a HEREDOC, which eliminates any need to swap quote types and/or escape them:
echo <<<EOL
<script>$('#edit_errors').html('<h3><em><font color="red">Please Correct Errors Before Proceeding</font></em></h3>')</script>
EOL;

Just escape your quotes:
echo "<script>$('#edit_errors').html('<h3><em><font color=\"red\">Please Correct Errors Before Proceeding</font></em></h3>')</script>";

You need to escape the quotes in the string by adding a backslash \ before ".
Like:
"<font color=\"red\">"

if you need to access your variables for an echo statement within your quotes put your variable inside curly brackets
echo "i need to open my lock with its: {$array['key']}";

You can just forgo the quotes for alphanumeric attributes:
echo "<font color=red> XHTML is not a thing anymore. </font>";
echo "<div class=editorial-note> There, I said it. </div>";
Is perfectly valid in HTML, and though still shunned, absolutely en vogue since HTML5.
CAVEATS
It's only valid for mostly alphanumeric and dash combinations.
Never ever do this with user input appended to attributes (those need quoting and htmlspecialchars or some whitelisting).
See also: When the attribute value can remain unquoted in HTML5
In other news: <font> specifically is somewhat outdated however.

Related

Embed Javascript in php file, syntax

Using ajax I post data to php file where I have loop with code below.
Part of my code where I can't properly format onclick event:
$result .= '<a href="#" onclick="$("#element").dialog("open");" ></a>';
I tried to escape double quotes with backslash, but no luck. Using backslashes, in console I see: Somehow from nowhere "=" appears, also all backslashes are printed. Code doesn't work.
Could someone help to figure out where I made a mistake in syntax? Thank you.
In your string there are double quotes, followed by content wrapped again in double quotes. The second quotes should be single quotes, but that would terminate the string. So you will have to escape them.
The desired html code should look like this:
to achieve this, you will have to change your PHP code to the e.g. the following:
$result .= '';
When parsing the HTML, the browser will read the onclick="$("#element" part, and infer that attribute onclick equals "$(", because it thought it found the closing double quotes. So, you'll need to escape the double quote character after the $(. Since you're using $result .= 'some_string' (I want to empasize on the single quote being used here), you are unable to escape the double quote character within the single quoted string. Thus, you'll need something like this:
$result .= '<a href="#" onclick="$(\'#element\').dialog(\'open\');" ></a>';
Now, php will translate \' to just ' while rendering, so the final output of the string will be
<a href="#" onclick="$('#element').dialog('open');" ></a>
I hope this helps.
Double quotes should be escaped
$result .= '<a href="#" onclick="$(\"#element\").dialog(\"open\");" ></a>';
Another way is
$result .= `<a href="#" onclick="$('#element').dialog('open');" ></a>`;

PHP - return confirm within PHP issue

could somebody please help me with the below:
echo ('<font color="FFFFFF"><b>Click here to claim ticket</b></font>');
I know there is an issue with some " ' " but can't figure this out. I am getting a syntax error just before the 'Are'. The line of code was working as expected before I added the:
onclick="return confirm('Are you sure you want to claim this ticket?');"
Thanks!
If you want to use the same quotes you opened the string with inside the string itself, you should escape it.
For instance:
$var = 'Hello, let's go!';
echo $var;
This code will throw a parse error because this is how PHP sees the code:
) New variable $var.
) Is a string, declared using single quotes '.
) After the opening quote we have 'Hello, let'
) Now PHP expects some kind of valid code operators, like ., and next string or ;, but it gets some characters, which are treated as instructions rather than strings because they are outside the quotes, and
) PHP throws a parse error.
To fix this, you can use the backslash \ a.k.a 'escaping' character.
For example, to fix your problem:
echo
('<font color="FFFFFF"><b>Click here to claim ticket</b></font>');
See the baskslashes \ surrounding the single quotes inside the confirm JavaScript function? This tells PHP to treat these quotes as normal characters instead of string start/end declarations. Same thing works for reversal when you use double quotes as string declarators.
For example, when you want to show the actual representation of $ or any characters that have special meaning in a double quoted string, which allows direct insertion of variables (and some other's, like class properties) values you would use the escaping character.
For example:
$apples = 12;
$talk = "I have $apples \$apples. Thanks, now have a backlash! \\!";
echo $talk;
This will output I have 12 $apples. Thanks, now have a backslash! \!
Now, you are not actually required to escape the escaping character (it will show just as well if it does't have anything to escape after it).
Read this: PHP Manual - About Strings
You can also switch your single quotes on the edges of your echo statement with regular quotes, which will allow you to insert the $id variable easier. Then, you just have to escape the quotes around your JavaScript in onClick and switch all the other quotes to single quotes.
echo "<a href='assign.php?id=$id' onclick=\"return confirm('Are you sure you want to claim this ticket?');\" style='text-decoration: none'><font color='FFFFFF'><b>Click here to claim ticket</b></font></a>";
However, there is a better way.
Interpolate PHP into HTML
(Instead of HTML into PHP)
The best way to do this is to write HTML as HTML, and interpolate PHP variables into the HTML. This is best practice as it allows syntax highlighting in IDE's, and looks much cleaner/easier to read.
Just write the entire element as HTML, and then echo the $id variable inside the HTML (instead of writing all of the HTML in a PHP echo statement).
<a href="assign.php?id=<?=$id;?>" onclick="return confirm('Are you sure you want to claim this ticket?');" style="text-decoration: none">
<font color="FFFFFF">
<b>
Click here to claim ticket
</b>
</font>
</a>
With this method, you don't have to worry about escaping quotes, and it will allow you to use regular quotes throughout your entire element.
You need to escape the nested ' by doing \'
echo ('<font color="FFFFFF"><b>Click here to claim ticket</b></font>');
Note that all the stuff inside the single quotes is considered as string by the PHP interpreter.
Docs: PHP: Variables - Manual

Passing PHP variables as strings to javascript

Somehow my php function, which creates a button, which calls a javascript function, does not pass the php variables as strings.
function addTableEntry($id, $name)
{
echo('<tr>
<td>'.$id.'</td>
<td>'.$name.'</td>
<td>Manage group
</tr>');
}
addTableEntry(1,"livingroom");
The function activateGroupSettingsOverlay() always gets called with (1, livingroom) whenever it is clicked and i get an error "livingroom is undefined".
How can i pass $name as a String? I tried to put quotes around it (like this: '.$id.',"'.$name.'", but that did not work.
You have to "escape" quotes inside a string if you want them to persist:
echo '..... onClick="activateGroupSettingsOverlay('.$id.',\''.$name.'\')"....'
The important thing are the backslashes before the (single) quotes.
The reason it wasn't working is because you were not including quotes in the javascript.
While other answers "fix" the issue they don't really explain it, to be clear this line
<td>Manage group
Is output like this
<td>Manage group
As is, the livingroom does not have quotes and so javascirpt is treating it as a variable, hence the undefined error. To fix it you want it to look like this when output.
<td>Manage group
Modifying this line is all you have to change
<td>Manage group
Adding the single quotes \' with escaping.
Personally for things like this I like to use what is called a HEREDOC or NEWDOC
<<<HTML HTML; and <<<'HTML' HTML; respective. HEREDOC is like using a " and new doc is like using ' in that you cannot use php variables within a NEWDOC but you can within the HEREDOC if you enclose them in { } braces. Because of this we'll want to use a HEREDOC so we can use php variables in the output.
function addTableEntry($id, $name)
{
echo <<<HTML
<tr>
<td>'.$id.'</td>
<td>'.$name.'</td>
<td>Manage group
</tr>
HTML;
}
addTableEntry(1,"livingroom");
http://php.net/manual/en/language.types.string.php - scroll down to where it says HEREDOC
The advantage to doing this is that you don't have to escape the single quotes, which makes it way more readable IMO. The trick with HEREDOC, or NEWDOC, is the ending HTML; has to start a new line and can be the only thing on that line, no leading or trailing spaces, or it won't work properly..
For this case it is probably simple enough to get away with how you are doing it, but if you needed to use concatenation in javascript, the quotes would become a hassle. For example say you wanted to add a html image tag using javascript with a javascirpt variable for the image name, but use php to get the server host name( html and variables in javascript ).
echo '
var foo = "image.jpb";
$(body).html( \'<img src="'.$_SERVER['HTTP_HOST'].'\'+foo+\'" />\' );
';
This quickly becomes unmanageable because ( not even sure if I have that right, anyway ). Compare how much cleaner this is, because you are not wasting the quotes in php....
echo <<<HTML
var foo = "image.jpb";
$(body).html( '<img src="{$_SERVER['HTTP_HOST']}'+foo+'" />' );
HTML;
Please try with this code:-
function addTableEntry($id, $name)
{
echo("<tr>
<td>".$id."</td>
<td>".$name."</td>
<td>Manage group
</tr>");
}
addTableEntry(1,"livingroom");
Change
onClick="activateGroupSettingsOverlay('.$id.','.$name.')"
to
onClick="activateGroupSettingsOverlay('.$id.',"'.$name.'")"
#chandresh_cool was kind of right, you have to "force" the quotes
onClick="activateGroupSettingsOverlay('.$id.',\''.$name.'\')"

how to put single double quotes together?

I have the following php code.
$msg .='<span>reply</span>';
When I click this anchor tag, I get the following error in console.
SyntaxError: illegal character # in myemail#company.com
I know the problem is due to single double quotes but don't know how to put the correct quotes.Can anyone help me please.
You can use backslash to use quotes as part of string
And in javascript, when passing str data to function it need to be in quotes.
$msg .='<span>reply</span>';
You can escape them with: "

PHP generated JavaScript onClick, with PHP array, quotes problem

echo '<a onClick="articleDeleteConfirm("'.
$row["title_$lang"].'","'.$_GET["editPage"]).'">';
The main problem is with: $row["title_$lang"], I have to use $lang variable inside. " and ' just not enough.
The problem you describe actually has nothing to do with your PHP variables, those are all being output as expected. The problem is that you need to escape the " inside of the <a> and you've misplaced a ).
Your original would output:
<a onClick="articleDeleteConfirm("value1","value2">
That is not valid HTML (even the highlighter dislikes it). Now, notice the \'s in the following (and that the paren was moved into the string).
echo '<a onClick="articleDeleteConfirm(\''
.$row["title_".$lang."].'\',\''.$_GET["editPage"].'\')">';
The escaped version outputs:
<a onClick="articleDeleteConfirm('value1','value2')">
It uses single quotes inside of double quotes to provide easy to read (and valid) html. Now, you have another issue with your code.
Any time you output a $_REQUEST variable to the browser, you risk something called cross-site-scripting. Someone could put JavaScript into $_GET["editPage"] and it would smell bad. The easy way to avoid it? Use htmlentities($_GET["editPage"])
I had same problem too, I don't know exactly why but I had syntax error no matter what I did, So I tried this and got answer.
The problem is that you're using a double quotation to open onClick and again you're using another double quotation to open an string.
Use this and you'll get answer.
echo '<a onClick="articleDeleteConfirm('.char(39).$row["title_$lang"].char(39).','.char(39).$_GET["editPage"]).char(39).'>';

Categories

Resources