php/html - triple nesting quotes - javascript

I know that similar questions have been asked on Stack Overflow many times, but I am having problems with triple nested quotes in html/php. I have looked at numerous questions, but none of the solutions that I have found are working for me. Here is what I am trying to do (this is found in a php file):
echo"<div id = 'feed-element'>
<button class='username-button' type='button'>#".$currentUsername."</button>
<button class='hashtag-one-button' type='button'>".$hashtag_one."</button>
<button class='hashtag-two-button' type='button'>".$hashtag_two."</button>
<button class='play-button' id='play-button".$i."' type='button' onclick='changeImage(this.id,\'".$track_url."\')'></button>
<button class='email-button' type='button'>Contact: ".$email."</button>
</div>";
The specific line that is causing me problems is the third to last line:
<button class='play-button' id='play-button".$i."' type='button' onclick='changeImage(this.id,\'".$track_url."\')'></button>
Anyways, when I run this code I get an Uncaught Syntax: invalid or unexpected token error. What am I doing wrong?

Why not use php heredoc and skip the hassle of escaping quotes? i.e.:
echo <<< EOF
<div id = 'feed-element'>
<button class='username-button' type='button'>#{$currentUsername}</button>
<button class='hashtag-one-button' type='button'>{$hashtag_one}</button>
<button class='hashtag-two-button' type='button'>{$hashtag_two}</button>
<button class='play-button' id='play-button{$i}' type='button' onclick='changeImage(this.id,{$track_url})'></button>
<button class='email-button' type='button'>Contact: {$email}</button>
</div>
EOF;
Note:
The curly braces are optional but may help code readability.

For your error-causing code, you need to escape double quotes, not single:
<button class='play-button' id='play-button".$i."' type='button' onclick='changeImage(this.id,\"".$track_url."\")'></button>
Because you are using double quotes, you don't need to concatenate. Just insert the variable and away you go!
echo"<div id='feed-element'>
<button class='username-button' type='button'>#$currentUsername</button>
<button class='hashtag-one-button' type='button'>$hashtag_one</button>
<button class='hashtag-two-button' type='button'>$hashtag_two</button>
<button class='play-button' id='play-button$i' type='button' onclick='changeImage(this.id,\' $track_url\ ')'></button>
<button class='email-button' type='button'>Contact: $email</button>
</div>";

For using quotes to any level in PHP/HTML, use forst level as either single or double quote. After that you have two options. 1. Use double quotes 2. Use single quotes with backslash before the quote. For example, echo "This is 'In quotes'"; or echo "This is \"In quotes\"";

In order to have multiple type of quotes on a line of code use .
Example :
echo 'It\'s me, hey';

You'e all crazy. Just end the php block and write whatever then start it up again.
Example
I want to dynamically create 3 different div elements, each one with two parameters: $ID and $TEXT which represent the dom element ID and the innerHTML.
Now to make it truely complex, I want to dynamically insert these elements into a Javascript Function, so that they will load when I call the JS function.
Here's how to do that: You simply end the PHP tag and then enter your desired content as if the PHP tag never existed, and it will parse it as if it was specified within PHP without having to escape anything
<?php
/* define regular function to generate dynamic element with PHP */
function create_my_div($ID, $TEXT) {
/* end the PHP tag and start just regularly entering code
?>
<div id='<?=$ID;?>'>
<?php print_r(htmlspecialchars($TEXT)); ?>
</div>
<?php
/* we started up the PHP tag again, followed by a } to end the function
}
?>
Now anytime we call create_my_div("someID", "some text"); with PHP it will create our DIV element.
Lets say we wanted to populate a javascript function's DIV elements server-side and put them into the Javascript Function create_my_divs()
We first would need to have a way to ensure that our DIV elements are properly escaped as mentioned in the other answers, which can be done with this PHP code:
<?php
function escapeJavaScriptText($string)
{
return str_replace("\n", '\n', str_replace('"', '\"', addcslashes(str_replace("\r", '', (string)$string), "\0..\37'\\")));
}
?>
And then finally, all we have to do is this on our web page:
<script type="text/javascript">
/* target element is where the DIVS will be created in */
function create_my_divs(target_element) {
target_element.innerHTML += "<?=escapeJavascriptText(create_my_div("DIV1", "THIS IS DIV1"));?>";
target_element.innerHTML += "<?=escapeJavascriptText(create_my_div("DIV2", "THIS IS DIV2"));?>";
target_element.innerHTML += "<?=escapeJavascriptText(create_my_div("DIV3", "THIS IS DIV3"));?>";
}
</script>
This method will allow you to include javascript code or whatever without worrying about triple nesting
Here's another use case for this method:
Dynamically adding Javascript code:
<?php
function loop_start($varName) {
?>
for (var i=0; i<<?php print_r($varName);?>.length; i++) {
<?php
}
?>
Now your Javascript code could look like this:
<script>
<?php
loop_start("myArray");
?>
console.log(myArray[i]);
}
</script>
Which would result in the following to be rendered:
<script>
for (var i=0; i<myArray.length; i++) {
console.log(myArray[i]);
}
</script>
Conclusion
Stop worrying about trying to triple escape or double escape, or even escape at all.
With the tricks outlined in this answer, you can avoid escaping all together.
(Escape the confusion if you will)

Related

Does Javascript methods auto-escape quotes?

I want to know if javascript methods auto-escape quotes, because this code work:
Example #1
<?php $foo ="hey a quote ' "; ?>
<input type="text" value="<?php echo $foo; ?>" id="foo" />
<script>
bar = document.getElementById('foo').value;
alert(bar+'there is a quote, will it work? ,');
</script>
It displays the alert fine, but this one:
Example #2
<?php $foo ="hey a quote ' "; ?>
<button onclick="alert('<?php echo $foo; ?>');">test</button>
...doesn't.
Obviously, it's because the quote isn't escaped with a \.
But then again, neither is it in the first example, so why is that so ?
Does javascript's method auto-escape quote when it picked stuff from DOM ?
Or is it just the value() method maybe ?
I've found nothing, so if you have even the beginning of an answer, I''ll be glad.
PHP is processed on the server, producing HTML (including embedded javascript in this case). This happens before the HTML is sent to the browser to interpret, including any JS.
You will see if you inspect the generated HTML source, that your second example becomes:
<button onclick="alert('hey a quote ' ');">test</button>
which isn't valid JS syntax.
Your first version works basically because you do not have an extraneous single quote in the code your PHP string is inserted into. The insertion instead produces:
<input type="text" value="hey a quote ' " id="foo" />
which is perfectly fine. And that value is then passed on to the alert call in the JS.
The difference is really that in the first code example, the quote appears in a context where there are no wrapping single quotes, so there is no ambiguity. If you would have wrapped the HTML attribute values with single quotes (which is valid HTML also), you'd have a problem:
<?php $foo ="hey a quote ' "; ?>
<input type='text' value='<?php echo $foo; ?>' id='foo' />
In that case the single quote should have been escaped as an HTML entity: &apos;:
<?php $foo ="hey a quote &apos; "; ?>
<input type='text' value='<?php echo $foo; ?>' id='foo' />
Now in the second code example you provided, the single quote will appear in wrapped single quotes (for the string literal passed to alert). This is an issue, because the single quote will now end the string literal, and the characters following it will lead to a syntax error.
Here the quote appears in a JavaScript string literal (the alert code), not as in the HTML context of the first example. In JavaScript string literals, single quotes can be escaped with the backslash.
So in both cases (HTML or JavaScript) you could need a form of escaping. They are different.
Note that none of this is related to PHP.

How can I use window.open in my string echo'd from PHP?

Through a $_POST request I query a database and return info in a string as follows:
$output .='<div class="searchdiv"> <b>'.$tit.' </b>- '.$art.' <br> watch full tutorial</div>';
My problem is the "window.open" statement. It works as follows in a plain html doc as inline JS:
$output .='<div class="searchdiv"> <b>'.$tit.' </b>- '.$art.' <br> watch full tutorial</div>';
But I think my problem in the PHP string is the single and double quotation marks.What am I doing wrong?
You need quotes around the URL.
$output .= '... <a href="#" onclick="window.open("' . $prev . '", "_blank", ...
// ---------------------------------------- here ^ -- and here ^
You would be able to notice this pretty quick if you looked at your HTML source, to see what was generated.
It seems that you've messed up the quotes in there slightly...
$output .='<div class="searchdiv"> <b>'.$tit.' </b>- '.$art.' <br> watch full tutorial</div>';
You used " to define the onclick event, however you've used " inside of that event, which made it invalid. Replace the " inside of the event with \', which will escape the quote and not mess up your PHP.
$output .='<div class="searchdiv"> <b>'.$tit.' </b>- '.$art.' <br> watch full tutorial</div>';
And, if $prev is not referring to a variable in JS (if it will end up as a string), you need those quotes around that as well.
\''.$prev.'\'

html onClick open url stored in a php variable

Following is my code, am getting Uncaught SyntaxError: Unexpected token }, but i don't see any } in my code. window.open is expecting url in quotes, I tried different combinations of single and double quotes but not working and unable to escape the double quote in echo either.Please help
Thanks..
<?php
$a = "https://www.google.co.in/";
?>
<html>
<body>
<form>
<input type="button" width="100" onClick="window.open(<?php echo '"'; echo $a; echo '"'; ?>)" height="100%" value="Edit Record"/>
</form>
</body>
</html>
You are outputting " characters into your onClick attribute value. Since you use those characters to delimit the value, the first one ends the script in the middle of the statement.
Use " instead.
But that's a quick and dirty hack. There are better approaches.
Do not try to generate JavaScript strings by mashing PHP strings together. Use a robust escaping function. json_encode will give you the JavaScript literal (including quote characters where needed) for any simple data structure.
Do not try to generate HTML by mashing strings together. Use a robust escaping function. htmlspecialchars will do all you need.
Such:
onClick="window.open(<?php echo htmlspecialchars(json_encode($a)); ?>)"
But don't use JavaScript when HTML will do:
<a href="<?php echo htmlspecialchars($a); ?>" target="_blank">
You should use echo "'$a'". The main problem is that you would habe double-double quotes in your onclick attribute. Or even better window.open('<?php echo $a; ?>').

Why is my javascript failing to work?

I've been working on this code for a while. The idea is to get javascript to make a div visible based on the results of a HTML form (not on this page). However, my javascript function never works. I've isolated the problem to the script not being called in the first place. Here's my code:
<!DOCTYPE HTML>
<html>
<body>
<?php
While ($result=mysql_fetch_array($data)){ //I have mySQL code before this
$equipment= $result['safety equipment'];
$equipment2= str_replace(' ', '_', $equipment); //modified equipment name without spaces so that post can read it
$problem = $_POST[$equipment2];
?>
<div style="display:none;" id="<?php echo $equipment?>"> <!--Code that creates a div for each equipment -->
<h1>Report a problem</h1> <br>
You reported that there is a problem with the <?php echo $equipment." in ".$name;?>.<br>
Please describe the problem.
<form>
<textarea row="5" column="300" name="Issue">
</textarea>
</form>
</div>
<?php
if ($problem=="working"){
inspectRoom($UID,$equipment,null);
}else {
echo $equipment; //this part works
echo'<script type="text/javascript">'; //this part does not work
echo'console.log("test");';
echo'var test ='.$equipment.';';
echo'alert (test);';
echo'Appear(test);';
echo'</script>';
}
}
?>
<script type="text/javascript">
function Appear(equipment){
alert("hi"); //error trapping
document.getElementById(equipment).style.display='block';
}
</script>
</body>
</html>
$equipment is a string with the name of the equipment (ex: Fume Hood)
$problem is a string retrieved from the previous page. It too has the name of some equipments.
In my console I get the following error:
"SyntaxError: missing ; before statement"
What am I doing wrong?
You're dumping PHP-based text directly into a Javascript context, which is highly dangerous. Any JS metacharacters (especially ') will cause syntax errors and kill the entire JS code block.
echo'var test ='.$equipment.';';
Should be
echo 'var test = ', json_encode($equipment), This will produce syntactically valid JS code, no matter what's in `$equipment`.
Plus, you have MANY other syntax errors. Your php while is NOT contained in a <?php ... ?> code block, so it'll appear directly in your output as raw text. The html inside your while loop is now considered part of the PHP code, so that'll be yet another syntax error. etc... etc... etc.. In other words this code is utterly broken.
Talking solely about javascript since that's what your question is about, your Appear function would never been defined yet since the PHP code would have echoed out the JS that calls Appear before the function is defined.
It is not working because you are forgetting the space after echo. There are other errors also such as your while is not within tags.
For this part of the code
echo $equipment; //this part works
echo'<script type="text/javascript">'; //this part does not work
echo'console.log("test");';
echo'var test ='.$equipment.';';
echo'alert (test);';
echo'Appear(test);';
echo'</script>';
Replace it with
echo $equipment; //this part works
echo'<script type="text/javascript">'; //this part does not work
echo'console.log("test");';
echo"var test ='$equipment';";
echo'alert (test);';
echo'Appear(test);';
echo'</script>';
Th variable isn't surrounded by quotes when the value will be a string;
To start with you are missing a > on line 6.

Put JSON data into html form input hidden?

I'm building a rich web application that uses a lot of data. When I'm building it I found that I was repeating myself over and over.
This is the problem. I need to put hidden application logic into HTML elements to represent the data being viewed by the client.
This is a solution I found some time ago:
<a href="bla" data-itemId="1" .... more data.
There are two problems with this method.
I can't represent arrays.
It's just ugly.
I searched for a solution but did not find anything. I also went to facebook, opened firebug,
and found this:
{"actor":"19034719952","target_fbid":"454811929952","target_profile_id":"19034719952","type_id":"7","source":"1","assoc_obj_id":"","source_app_id":"","extra_story_params":[],"content_timestamp":"1324385453","check_hash":"9eabc3553e8a2fb6"}
This json was inside an input[type=hidden] element.
I tried to do the same thing with json_encode();
<input type="hidden" name="track" value="{"_id":{"$id":"4eee908f615c2102e9010000"},"link":"george-wassouf-flag-of-my-heart-longing","file":"\/m\/tracks\/t.4eee908daca2a3.49941874.mp3","lyrics":null,"freezed":false,"hits":0,"images":{"large":"\/assets\/static\/default.track.large.jpg","thumb":"\/assets\/static\/default.track.thumb.jpg","icon":"\/assets\/static\/default.track.icon.jpg"},"duration":"300","created":{"sec":1324257423,"usec":78000},"albums":[{"_id":{"$id":"4eee8d63615c21f6e7000000"},"names":{"ar":"\u0643\u0644\u0627\u0645\u0643 \u064a\u0627 \u062d\u0628\u064a\u0628\u064a","en":"Kalamak ya Habibi"},"link":"george-wassouf-kalamak-ya-habibi","images":{"original":"\/m\/pics\/albums\/o.4eee8d612c3183.11879972.jpg","poster":"\/m\/pics\/albums\/p.4eee8d63967072.02645896.jpg","large":"\/m\/pics\/albums\/l.4eee8d63a89111.20372767.jpg","small":"\/m\/pics\/albums\/s.4eee8d63b18927.47242533.jpg","thumb":"\/m\/pics\/albums\/t.4eee8d63b7f1f4.11879932.jpg","icon":"\/m\/pics\/albums\/i.4eee8d63bf1304.59902753.jpg"}},{"_id":{"$id":"4eee8d63615c21f6e7000000"},"name":"Kalamak ya Habibi","link":"george-wassouf-kalamak-ya-habibi"}],"name":"Flag of my heart longing","title":"Flag of my heart longing","mp3":"\/m\/tracks\/t.4eee908daca2a3.49941874.mp3","poster":"\/m\/pics\/artists\/p.4eee85cd7ed579.65275366.jpg","artists":[{"_id":{"$id":"4eee85cd615c21ece6000000"},"name":"George Wassouf","link":"george-wassouf"}]}" />
But when I try getting the value I get this {.
I have tried all constants like JSON_HEX_TAG and did not find any questions of this type.
How can I put JSON into HTML correctly and then get it with jquery/javascript?
Your string is correct, but it cannot be defined in HTML because it contains double quotes.
HTML requires you to escape double quotes when you are defining a String that is itself enclosed within double quotes. The appropriate way of doing this is using the HTML entity:
value="""
From PHP:
Use htmlspecialchars or htmlentities (http://www.php.net/manual/en/function.htmlspecialchars.php). In any case, you normally should be using this over EVERY value you write to the client browser (not doing so may result in security risks).
From Javascript:
If you need to do this from Javascript, you can programatically set the value of the hidden element (provided your JSON string is already contained in a Javascript variable). This way you don't have to worry about encoding the string literal:
hiddenElement.value = yourString;
In order to get an escape function you can use, maybe check this thread: Escaping HTML strings with jQuery .
Best way for me was to use html & quot;
for example i do this:
<input type="hidden" id="v" value="[{"id":"1"}]" >
instead of
<input type="hidden" id="v" value="[{"id":"1"}]" >
in your input tag, the value attribute in which you are trying to put json array. Look at it. you are putting ". Second " is ending the attribute value. thus it is being interpreted as value = "{". you need to escape those ". Use single quotes ' instead. And check then
It seems my answer is late, but I want to contribute to those who come later.
Before coming here you have the concept of HTML.Use single quotes ' , Should not do that, although it still works, it is against the HTML principle .
The best way is: Use htmlspecialchars or htmlentities. #jjmont said above.
I have a small example:
<input id="jsondata" value="<?php echo htmlspecialchars( json_encode($data), ENT_COMPAT ); ?>" >
||
<input id="jsondata" value="<?php echo htmlspecialchars( json_encode($data), ENT_NOQUOTES ); ?>" >
php
set array in
<input type="checkbox" name="deviceInfo" value="<?php print_r(json_encode(array_filter($array_data), JSON_FORCE_OBJECT));?>" />
?>

Categories