how to properly use quotes in javascript - php

I am using a bit of JavaScript like this:
echo '<a href="javascript:playSong'."('$row[artist]','$row[title]','$row[sourcefile]')".'">';
My problem is that sometimes my $row[artist] and $row[title] variables contain double qoutes.
When this happens it breaks the javascript:playSong(); function call.
For example if the line was output like this:
<a href="javascript:playSong('Danny Elfman','Beetlejuice Theme (Kamei Halloween Edit)','2009-10-31-10-52-01.4521.data','28330')">
Everything would be fine.
But sometimes the function will look like this:
<a href="javascript:playSong('Danny Elfman','Beetlejuice "Theme" (Kamei Halloween Edit)','2009-10-31-10-52-01.4521.data','28330')">
Which would then cause my site to think the command ends at the double quote before "Theme" and thus cause it to fail.
Is there a way I should be properly quoting my javascript so it treats double quotes inside the function as text and no the end of the function.
I am using addslashes() and have tried various other encodings but nothing like that seems to work.

The best solution here is to stop using href="javascript:… and start using unobtrusive JavaScript and progressive enhancement.
If you do want to continue down this route, then you need to remember that you are dealing with three different languages and generating one from the other in a chain.
Start with the JavaScript. Then make it work with the HTML. Then make it work with the PHP.
javascript:playSong('Danny Elfman','Beetlejuice "Theme" (Kamei Halloween Edit)','2009-10-31-10-52-01.4521.data','28330')
There are no syntax errors here. You just have double quotes in a string.
href="javascript:playSong('Danny Elfman','Beetlejuice "Theme" (Kamei Halloween Edit)','2009-10-31-10-52-01.4521.data','28330')"
Now you hava nested the JavaScript in an HTML attribute which is delimited with double quotes. This means that the double quotes in the JS are now a problem as it terminates the attribute value half way through the script.
Deal with these quotes in the usual way for HTML. Replace them with an HTML entity: "
href="javascript:playSong('Danny Elfman','Beetlejuice "Theme" (Kamei Halloween Edit)','2009-10-31-10-52-01.4521.data','28330')"
Then we get to the PHP:
echo '<a href="javascript:playSong'."('$row[artist]','$row[title]','$row[sourcefile]')".'">';
Dealing with quotes inside quotes inside quotes is a pain. So don't try.
href="javascript:playSong('<?php echo $row[artist] ?>','<?php echo $row[title] ?>','<?php echo $row[sourcefile]; ?>')"
You seem to have lost an argument between examples there.
Follow the normal rules for dealing with inserting content into HTML with PHP: htmlspecialchars
href="javascript:playSong('<?php echo htmlspecialchars($row[artist]); ?>','<?php echo htmlspecialchars($row[title]); ?>','<?php echo htmlspecialchars($row[sourcefile]); ?>')"

Escaping ONLY with backslash won't help you because you also need to escape them in html, try using ' for single quotes and " for double quotes in your embedded js functions.
This should do what you need.
Sinan.

Edit: Oh. You need to escape it in html. Try htmlspecialchars:

Related

PHP echo returning blank value

So I am trying to link using data I got from a function but it keeps giving me a blank value for ID. Here's my code for what I'm trying to print
<h3 style="text-align: center;">Seller: <?php $sellername =
getNameFromListingID(); $id = getIDByUsername($sellername); echo "".$sellername."";?></h3>
The functions work properly, I have tried printing both of them and it works. They're in a file called getinfo.php, which I have
Include 'getinfo.php';
At the top of my document.
The link with the name works but I always get seller.php?id=, with no value after. Any clue as to why?
You're ending the href attribute too early.
<a href=\"seller.php?id=".$id."\">
This will put the $id inside the href attribute, where it belongs.
Use single quotes in PHP, it's a good practice to get into, and it's also slightly (a teeny tiny bit) faster for PHP to process. Why? Because, when you use double quotes, you're telling PHP that your string contains variables that may need to be evaluated.
So in truth, you don't even need the quotes around variables here.
echo "$sellername";
But doing it like this would be following a best practice.
And now you don't need to escape \" double quotes that HTML uses.
echo ''.$sellername.'';
Caution: It's also a very good idea to escape special characters in anything you're outputting into HTML markup. That avoids the potential for an XSS vulnerability. See: htmlspecialchars()
echo ''.htmlspecialchars($sellername).'';

How to use php to output this html code?

How to use php to output this html code?
The html code is this.
Piano Programs
but I want to use php to show this code
$program_name = "piano_programs";
echo "Piano Programs";
but.....doesn't work, any idea ,thanks
Backslashes to escape the quotes:
echo "Piano Programs";
You need to add slashes before onclick's two double quotes and move your single quote to the right side of .php.
echo "Piano Programs";
I like to curly-bracket my variables so that they stand out in my editor and so that they don't get mixed up with the text that immediately follows.

single qoute syntax printing in php [duplicate]

This question already has answers here:
single quote inside double quote in php
(3 answers)
Closed 9 years ago.
The below outputs
href="javascript:showBed(" a114:1')'
when I want it on the form
href="javascript:showBed('A114:1')"
in order to get javascript to work. I had a look at this site but coudn't get it to work so I gave up. Perhaps you could give me a hint on how the corrent syntax would be?
echo("<a href='javascript:showBed('" . $row['Bed'] ."')' target='main' class='larmlink'>link</a>");
Thanks =)
Your output is not what it would output, but it is how it would be interpreted (HINT: don't look at a parsed DOM tree, look at the source).
echo("<a href='javascript:showBed('" . $row['Bed'] ."')' ...
==>
echo("<a href=\"javascript:showBed('" . $row['Bed'] ."')\" ...
You really should be using the more standard double quotes around HTML element properties. As such, it is probably best to use single quotes in PHP. I would suggest this:
echo('link');
To print the double-quote character, you can escape it by doing \"
echo("<a href=\"javascript:showBed('" . $row['bed'] ."')\" target='main' class='larmlink'>link</a>");
Live demo
When you want to output variable data to JavaScript, it is good to use json_encode() so that all special characters are escaped automatically. The htmlspecialchars() escapes any values for use in the HTML attribute value.
echo '<a href="',
htmlspecialchars('javascript:showBed(' . json_encode($row['Bed']) . ')'),
'" target="main" class="larmlink">link</a>';
Note that I use single quotes for PHP string literals so that PHP doesn't have to search through my string for a variable to replace. You don't have to do this, but I recommend it.
I like to use sprintf (or printf, but sprintf is easier to refactor) for long strings like this so it's easy to see the template:
echo sprintf("<a href='javascript:showBed(\"%s\")' target='main' class='larmlink'>link</a>", $row['Bed']);
I'd also consider using addslashes on the $row['Bed'] variable in case it has quotes in it.
Using the heredoc syntax often makes code with mixed quotes easier to understand:
echo <<<EOD
link
EOD;
As others mentioned, if the value of your $row['Bed'] might contain single or double quotes, you have to escape it with addslashes.
You can use the heredoc syntax to avoid to escape anything:
echo <<<LOD
link
LOD;
Notice that if your variables contains some quotes you must use the addslashes function or str_replace before.
Another good practive is to separate systematically all the html content from php code:
<a href="javascript:showBed('<?php
echo $row['Bed'];
?>')" target="main" class="larmlink">link</a>
try this one:
echo("<a href='javascript:showBed(\"" . $row['Bed'] ."\")' target='main' class='larmlink'>link</a>");

Using innerhtml to write html with A LOT of quotes

I'm trying to call a function which writes a very long string of html to an element. The string will look similar to this;
'<div id='gaugearray8'>
<p id='ANCPUB' class='plot' style='height:100px;width:175px;float:left;' title='0.0011217599587192' onClick=LowerLevelPrint([{"NumberSelected":1,"TargetPerc":[237.5],"KpiDescription":["Contribution&nbspof&nbspExternal&nbspRevenue"],"KpiName":["revcontrubionkpi"],"ValuetoPrint":[0.0011217599587192],"ValueNow":[19],"ValueCompare":[1693767],"Target":["8"],"KpiUnits":["Pounds"],"PercentCompare":[0.0011217599587192]}]) onmouseover=TopLevelLabel({"NumberSelected":1,"Description":["Contribution&nbspof&nbspExternal&nbspRevenue"],"GroupDescription":"Ancillary&nbspService&nbspPerformance"}) onmouseout=clearnew()></p>
<p id='CSPUB' class='plot' style='height:100px;width:175px;float:left;' title='21.855170547342' onClick=LowerLevelPrint([{"NumberSelected":7,"TargetPerc":[206.03360584712,8.8767313176762,10.356186537289,12.5,12.5,237.5,10.356186537289],"KpiDescription":["Operating&nbspCost&nbspper&nbspService&nbspKm","Revenue&nbspper&nbspService&nbspKm","Total&nbspCost&nbspper&nbspService&nbspKm","Claims&nbspCost&nbspper&nbspVehicle","Claims&nbspCost&nbspper&nbspDriver","Number&nbspof&nbspClaims&nbspLodged&nbspper&nbsp100,000km","Overheads&nbspCost&nbspper&nbspService&nbspKm"],"KpiName":["opcostperkmkpi","revenueperkmkpi","totalcostperkmkpi","claimspervehkpi","claimsperdriverkpi","claimslodgedkpi","overheadskpi"],"ValuetoPrint":[110.47252736225,5.6435200058102,5.434671444334,0.35610369406272,0.35829645079956,12.666666666667,18.054408207469],"ValueNow":[10.301680292356,0.62137119223733,0.62137119223733,1,1,19,0.62137119223733],"ValueCompare":[9.32510601353,11.010348002623,11.433463800009,280.81708128079,279.09849449204,150,3.4416591510336],"Target":["5","7","6","8","8","8","6"],"KpiUnits":["Pounds&nbspper&nbspKm","Pounds&nbspper&nbspKm","Pounds&nbspper&nbspKm","Pounds&nbspper&nbspVehicle","Pounds&nbspper&nbspDriver","Claims","Pounds&nbspa&nbspkm"],"PercentCompare":[110.47252736225,5.6435200058102,5.434671444334,0.35610369406272,0.35829645079956,12.666666666667,18.054408207469]}]) onmouseover=TopLevelLabel({"NumberSelected":7,"Description":["Operating&nbspCost&nbspper&nbspService&nbspKm","Revenue&nbspper&nbspService&nbspKm","Total&nbspCost&nbspper&nbspService&nbspKm","Claims&nbspCost&nbspper&nbspVehicle","Claims&nbspCost&nbspper&nbspDriver","Number&nbspof&nbspClaims&nbspLodged&nbspper&nbsp100,000km","Overheads&nbspCost&nbspper&nbspService&nbspKm"],"GroupDescription":"Core&nbspService&nbspPerformance"}) onmouseout=clearnew()></p>
<p id='ROPTUB' class='plot' style='height:100px;width:175px;float:left;' title='9.7292765723395' onClick=LowerLevelPrint([{"NumberSelected":2,"TargetPerc":[12.5,207.23684210526],"KpiDescription":["Revenue&nbspExpenditure&nbspper&nbspPassenger&nbspJourney","Cost&nbspPer&nbspHeadcount"],"KpiName":["revexperjourneykpi","coststaffkpi"],"ValuetoPrint":[19.044041148259,0.41451199641943],"ValueNow":[1,16.578947368421],"ValueCompare":[5.2509863437855,3999.6302909519],"Target":["8","8"],"KpiUnits":["Pounds&nbspper&nbspJourney","Pounds&nbspper&nbspStaff"],"PercentCompare":[19.044041148259,0.41451199641943]}]) onmouseover=TopLevelLabel({"NumberSelected":2,"Description":["Revenue&nbspExpenditure&nbspper&nbspPassenger&nbspJourney","Cost&nbspPer&nbspHeadcount"],"GroupDescription":"Resource&nbspOptimisation"}) onmouseout=clearnew()></p></div>';
Don't worry about disecting that as it's just an example of what can be sent. I'm assuming the problem is the multitude of quotes inside this string, as the javascript on the page entirely stops working when I include this function.
The above string is actually generated in a php loops, and the function I'm trying to use calls attempts
document.getElementById('financearea').innerHTML =
'<?php $myview->PopulateContent($finance, 8, 'ub', 'UB', $a); ?>';
`
Which works correctly when its in the main page body, but won't run when using the innerHTML method.
Does anyone have any suggestions on how this could work?
This is the code on the php side - its created and echo'd in a loop
$thisgoesinfile =
"<p id='".$Group.$Depot."' class='plot' style='height:100px;width:175px;float:left;' title='".$TotalValuetoPrint."' onClick=LowerLevelPrint(".json_encode($result_set).") onmouseover=TopLevelLabel(".json_encode($Descriptions).") onmouseout=clearnew()></p>";
Edit: I tried removing all the single quotes in the php string so now the string looks like
document.getElementById('financearea').innerHTML = <div id=gaugearray8><p id=ANCPUB class=plot style=height:100px;width:175px;float:left; title=0.0011217599587192 onClick=LowerLevelPrint([{"NumberSelected":1,"TargetPerc":[237.5],"KpiDescription":["Contribution&nbspof&nbspExternal&nbspRevenue"],"KpiName":["revcontrubionkpi"],"ValuetoPrint":[0.0011217599587192],"ValueNow":[19],"ValueCompare":[1693767],"Target":["8"],"KpiUnits":["Pounds"],"PercentCompare":[0.0011217599587192]}]) onmouseover=TopLevelLabel({"NumberSelected":1,"Description":["Contribution&nbspof&nbspExternal&nbspRevenue"],"GroupDescription":"Ancillary&nbspService&nbspPerformance"}) onmouseout=clearnew()></p><p id=CSPUB class=plot style=height:100px;width:175px;float:left; title=21.855170547342 onClick=LowerLevelPrint([{"NumberSelected":7,"TargetPerc":[206.03360584712,8.8767313176762,10.356186537289,12.5,12.5,237.5,10.356186537289],"KpiDescription":["Operating&nbspCost&nbspper&nbspService&nbspKm","Revenue&nbspper&nbspService&nbspKm","Total&nbspCost&nbspper&nbspService&nbspKm","Claims&nbspCost&nbspper&nbspVehicle","Claims&nbspCost&nbspper&nbspDriver","Number&nbspof&nbspClaims&nbspLodged&nbspper&nbsp100,000km","Overheads&nbspCost&nbspper&nbspService&nbspKm"],"KpiName":["opcostperkmkpi","revenueperkmkpi","totalcostperkmkpi","claimspervehkpi","claimsperdriverkpi","claimslodgedkpi","overheadskpi"],"ValuetoPrint":[110.47252736225,5.6435200058102,5.434671444334,0.35610369406272,0.35829645079956,12.666666666667,18.054408207469],"ValueNow":[10.301680292356,0.62137119223733,0.62137119223733,1,1,19,0.62137119223733],"ValueCompare":[9.32510601353,11.010348002623,11.433463800009,280.81708128079,279.09849449204,150,3.4416591510336],"Target":["5","7","6","8","8","8","6"],"KpiUnits":["Pounds&nbspper&nbspKm","Pounds&nbspper&nbspKm","Pounds&nbspper&nbspKm","Pounds&nbspper&nbspVehicle","Pounds&nbspper&nbspDriver","Claims","Pounds&nbspa&nbspkm"],"PercentCompare":[110.47252736225,5.6435200058102,5.434671444334,0.35610369406272,0.35829645079956,12.666666666667,18.054408207469]}]) onmouseover=TopLevelLabel({"NumberSelected":7,"Description":["Operating&nbspCost&nbspper&nbspService&nbspKm","Revenue&nbspper&nbspService&nbspKm","Total&nbspCost&nbspper&nbspService&nbspKm","Claims&nbspCost&nbspper&nbspVehicle","Claims&nbspCost&nbspper&nbspDriver","Number&nbspof&nbspClaims&nbspLodged&nbspper&nbsp100,000km","Overheads&nbspCost&nbspper&nbspService&nbspKm"],"GroupDescription":"Core&nbspService&nbspPerformance"}) onmouseout=clearnew()></p><p id=ROPTUB class=plot style=height:100px;width:175px;float:left; title=9.7292765723395 onClick=LowerLevelPrint([{"NumberSelected":2,"TargetPerc":[12.5,207.23684210526],"KpiDescription":["Revenue&nbspExpenditure&nbspper&nbspPassenger&nbspJourney","Cost&nbspPer&nbspHeadcount"],"KpiName":["revexperjourneykpi","coststaffkpi"],"ValuetoPrint":[19.044041148259,0.41451199641943],"ValueNow":[1,16.578947368421],"ValueCompare":[5.2509863437855,3999.6302909519],"Target":["8","8"],"KpiUnits":["Pounds&nbspper&nbspJourney","Pounds&nbspper&nbspStaff"],"PercentCompare":[19.044041148259,0.41451199641943]}]) onmouseover=TopLevelLabel({"NumberSelected":2,"Description":["Revenue&nbspExpenditure&nbspper&nbspPassenger&nbspJourney","Cost&nbspPer&nbspHeadcount"],"GroupDescription":"Resource&nbspOptimisation"}) onmouseout=clearnew()></p></div>;
But still not working.
Use json_encode rather than wrapping the text in single quotes yourself:
document.getElementById('financearea').innerHTML = <?php echo json_encode($myview->PopulateContent($finance, 8, 'ub', 'UB', $a)); ?>;
When you pass a string into json_encode, it will get wrapped in quotes and any quotes and other special characters within it will get correctly encoded for use as a JavaScript literal string. (This is a by-product of the fact that JSON is a subset of JavaScript's literal syntax.)
(I've also added an echo there; I'm not much of a PHP-head, so remove it if it's not needed, but you're not using short-tags, so...)
Escape the single quotes in the PHP output! :)
Replace the ' with \'
Obviously you need to ensure you are escaping quotes within strings or the Javascript will break. A simple solution would be to use double-quotes inside the string, and use single-quotes to delimit the string.
'<div id="gaugearray8">'

What is the right way to create tabs and line breaks in PHP when using single quotes?

Seems like a simple question, but I haven't been able to find a solid answer anywhere. I'm outputting a ton of HTML and find escaping "s to be error prone and hard to read, but I also want to have my HTML formatted nicely.
Want something like this (though I know this won't worK):
echo '<div id="test">\n';
echo '\t<div id="test-sub">\n';
echo '\t</div>\n';
echo '</div>\n';
What is one to do?
Thanks.
did you look on HEREDOC
Heredoc text behaves just like a
double-quoted string, without the
double quotes. This means that quotes
in a heredoc do not need to be escaped
example of advantage here : http://www.shat.net/php/notes/heredoc.php
There are a lot of ways to make sure, this works just fine for example (PHP_EOL is a cross Platt form Constant for a new line Char (EndOfLine) ):
echo "<div id=\"test\">".PHP_EOL;
echo "\t<div id=\"test-sub\">".PHP_EOL;
echo "\t</div>".PHP_EOL;
echo "</div>".PHP_EOL;
I make use of a small set of classes I wrote in order to output nicely formatted HTML. If you are interested you can find it here.
To get what you want, I would end up writing something like
$mypage = page::blank();
$mypage->opennode('div', 'id="test"');
$mypage->opennode('div', 'id="test-sub"');
$mypage->closenode(2); // div, div
echo $mypage->build_output_strict();
Another alternative would be to use a full-fledged template engine, of which there are quite a few.
use double quotes
or a multi-line echo string:
echo '<div id="test">
<div id="test-sub">
</div>
</div>';
or templates.

Categories