I'm trying to echo a dynamic a tag which calls a javascript function, but the parameters are not being echoed correctly. They should retain their capitalization and not add spacing. Why is it doing this?
I've tried removing variables and just echoing a straight string with what I want, but it still displays incorrectly.
What I need:
echo '<img src="'.$info[1].'"/>'
Pure String Version:
echo '<img src="/images/calc-eng-desktop.png">'
Outputs:
<a href="/calc" onclick="redirTrackCalcBtn(" test_button_1",="" "="" calc")"="">
<img src="/images/calc-eng-desktop.png">
</a>
Should Output:
<a href="/calc" onclick="redirTrackCalcBtn("Test_Button_1", "/calc")">
<img src="/images/calc-eng-desktop.png">
</a>
I also tried:
echo "<img src=\"".$info[1]."\"/>";
But that still outputs:
<img src="/images/calc.png">
as per Dharman's response I also Tried:
echo '<a href="'.$info[0].'"
onClick=\"redirTrackCalcBtn("'.$bname.'", "'.$info[0].'")\"
><img src="'.$info[1].'"/></a>'
This outputs:
<a href="/calc" onclick="\"redirTrackCalcBtn("Test_Banner_1"," "="" calc")\"="">
<img src="/images/preguntanos-h-es.png">
</a>
Edit for context:
It's for a dynamic banner within the content of a blog powered by WordPress.
You can simplify your expressions using the following technique ...
HTML accepts single quote or double quotes for attributes.
PHP can evaluate variables inside of double quote delimited strings. This can make your expressions much more easier to understand.
So based on this, the answer would be:
<?php
echo "<a href='{$info[0]}' onClick='redirTrackCalcBtn(\"{$bname}\", \"{$info[0]}\")'><img src='{$info[1]}'/></a>";
This will give the following result ...
<a href='/calc' onClick='redirTrackCalcBtn("test_button_1", "/calc")'><img src='/images/calc-eng-desktop.png'/></a>
In your question, you have shown an Pure String Version and what you thought was a normal output. Both of those outputs are wrong. You cannot use something like onclick="redirTrackCalcBtn("Test_Button_1", "/calc")" because the double quote right after the opening parenthesis finishes the onclick attribute which become onclick="redirTrackCalcBtn(". After that, the browser will try its best to find the following attributes and their values. So the spaces that you are seeing are just the natural space between attributes.
In conclusion, there is nothing wrong with echo.
You need to escape one set of the double-quotes, otherwise they are mixed together. Since you went for single-quotes in PHP, you need to use double in HTML/JavaScript and then use single-quotes again, but this time escaped from PHP.
echo '<a href="'.$info[0].'" onClick="redirTrackCalcBtn(\''.$bname.'\', \''.$info[0].'\')" ><img src="'.$info[1].'"/></a>';
The JavaScript variables are enclosed within \'
or
echo '<a href="'.$info[0].'" onClick=\'redirTrackCalcBtn("'.$bname.'", "'.$info[0].'")\' ><img src="'.$info[1].'"/></a>';
The onlick part is now enclosed with escaped quotes, everything else stayed the same.
You have 3 languages mixed together, 3 layers:
PHP will use '
-->HTML will use "
---->JavaScript will use \'
Each one uses double or single quotes and you only have two to choose from. Therefore you need to escape one of them.
A simpler example:
echo '<a onclick="alert(\'hi\')">Hello</a>';
Perhaps a simpler way to overcome quote escaping confusion is to assign the string in a different way. You can remove one layer of quotation by using heredoc notation.
as an aside, your "correct" output is not correct:
onclick="redirTrackCalBtn("Test_Button_1, "/calc")">
<a href="/calc" onclick="redirTrackCalcBtn("Test_Button_1", "/calc")">
<img src="/images/calc-eng-desktop.png">
</a>
Your HTML should look like this:
<a href="/calc" onclick="redirTrackCalcBtn('Test_Button_1', '/calc')">
<img src="/images/calc-eng-desktop.png">
</a>
Using Heredoc notation, you don't have to concatenate and escape, just write it out the way the HTML should be:
$link =<<<LINKINFORMATION
<a href="{$info[0]}" onclick="redirTrackCalcBtn('{$bname}', '{$info[0]}')">
<img src="/images/calc-eng-desktop.png">
</a>
LINKINFORMATION;
echo $link;
Related
I'd like how i can use a lot of ' and " in a code.
Example:
echo 'document.write("<a href='$url'> <img src='{$row["image"]}' border='0' /> </a>");';
I tried but i'm getting error. Anyone can help?
so, you have multi-level problem here:
data which is echoed to html, usually should be properly escaped via htmlspecialchars
you want to see document.write("..."..."); in your finally produced html, this will trigger javascript syntax error
to avoid this error, you should use \ before " inside string
echo 'document.write("<img src=\"' . htmlspecialchars($row["image"]) . '\" border=\"0\" />");';
note: I'm using echo with single quotes, if you're using double quotes - you will have to double \\
in case of double quotes your code will look like:
echo "document.write(\"<img src=\\\"" . htmlspecialchars($row["image"]) . "\\\" border=\\\"0\\\" />\");";
Here are three ways to tackle this problem.
1. Escaping the inner double slashes
echo "document.write(' <img src=\"{$row['image']}\" border=\"0\" /> ');";
2. Closing your PHP tags and writing javascript
?>
document.write(' <img src="<?php echo $row['image']; ?>" border="0" /> ');
<?php
3. Using Heredoc syntax
echo <<<EOJS
document.write(' <img src="{$row['image']}" border="0" /> ');
EOJS;
This will work:
<?php
$url = "http://www.google.com";
$row = array("image" => "image.png");
echo "document.write(' <img src=\"".$row["image"]."\" border=0 /> ');";
// output: document.write(' <img src="image.png" border=0 /> ');
?>
You can use the heredoc syntax:
echo <<<EOT
document.write(<a href='{$url}'> <img src='{$row["image"]}' border='0' /> </a>);
EOT;
From phpdocs
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, but the escape codes listed above can still be used.
Variables are expanded, but the same care must be taken when
expressing complex variables inside a heredoc as with strings.
Also note, that
It is very important to note that the line with the closing identifier
must contain no other characters, except a semicolon (;). That means
especially that the identifier may not be indented, and there may not
be any spaces or tabs before or after the semicolon. It's also
important to realize that the first character before the closing
identifier must be a newline as defined by the local operating system.
This is \n on UNIX systems, including Mac OS X. The closing delimiter
must also be followed by a newline.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I have a series of images/links that is calling a javascript function when the image is clicked. The code below works fine in regular html, but when I try to use this inside of a php echo it doesn't work.
echo "<a href='javascript:nfllogin('nflshow');' class='black' style='font-size:12px;'><img src='images/nfl-button-index.jpg' width='177' height='145' alt=''/></a> ";
Everything appears fine but when I click the image/link it doesn't pull up the div area I am expecting to see. How can I make this work?
You'll need to escape some of the quotes to avoid nested quotes of the same type.
echo "<a href='javascript:nfllogin(\"nflshow\");' class='black' style='font-size:12px;'><img src='images/nfl-button-index.jpg' width='177' height='145' alt=''/></a> ";
Will actually output:
<a href='javascript:nfllogin("nflshow");' class='black' style='font-size:12px;'><img src='images/nfl-button-index.jpg' width='177' height='145' alt=''/></a>
Which should work better for you.
echo '<img src="images/nfl-button-index.jpg" width="177" height="145" alt=""/>';
a good practice in echoing html in php is use single quote to echo and double quotes thereafter. This save the stress of escaping string. Try the above pls.
if it doesnt respond change this: javascript:nfllogin("nflshow");
The first thing that hits my eyes is that there's a problem with single and double quotes.
echo '<a href="javascript:nfllogin(\'nflshow\');" ';
echo "class='black' style='font-size:12px;'><img src='images/nfl-button-index.jpg' width='177' height='145' alt=''/></a> ";
Since the JavaScript contains a single quote, you have to put the href into double quotes. I split the echo in two to avoid to escape quotes with backslashes.
To echo such big chunks of html, the heredoc syntax comes in handy too. This would look like:
echo <<<EOT
<a href="javascript:nfllogin(\'nflshow\');" class="black" style="font-size:12px;">
<img src="images/nfl-button-index.jpg" width="177" height="145" alt=""/>
</a>
EOT;
There are two advantages:
There's no need to escape quotes
As a consequence, you can indent your HTML code and use double quotes for the attributes. It's just a matter of clean code to quote all HTML code consistently with double quotes.
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; ?>').
please help me with this issue. I have a php file which generates XML. I have the following code that I can not escape a JS script within XML as follows:
$xml_after='<html>'.htmlspecialchars('
<div class="options" id="options_'.$tables_row['id'].'">
<a class="insidetable" href="" title="'.$lang['delete'].'"
onClick="show_confirmation(\''.$messages['delete_table'].'\',\''.$lang['close'].'\',hide_element(\'confirmation\');\''.$lang['delete'].'\',remove_table(\''.$tables_row['id'].'\');hide_element(\'confirmation\');\');return false;\" ><img src="../images/interface/icons/delete.png" />
</a></div>').'</html>';
The problem is in onclick functions..
Please help, full day losted already , thank you
Be aware that htmlspecialchars() escapes < and >, too. You have to use it on each value separately, not on the complete html fragment.
htmlspecialchars() has an option that escapes all quotes.
var_dump(htmlspecialchars("Escaping: <>&'\"", ENT_QUOTES));
Ouptut:
string(35) "Escaping: <>&'""
But it would be better to use DOM and let it take care of the escaping.
Additionally, I suggest using data-* attributes in HTML. The Javascript can read the attributes and bind the logic to the elements. This separates the actual JS logic from the HTML.
I think your code is incorrectly formatted
$xml_after='<html>'.htmlspecialchars('<div class="options"
id="options_'.$tables_row['id'].'">
<a class="insidetable" href="" title="'.$lang['delete'].'"
onClick="
show_confirmation(\''.$messages['delete_table'].'\',\''.$lang['close'].'
\', hide_element(\'confirmation\');\''.$lang['delete'].'
\', remove_table(\''.$tables_row['id'].'\');
hide_element(\'confirmation
\');
\');return false;\" >
<img src="../images/interface/icons/delete.png" />
</a></div>').'</html>';
after each of the functions inside the show_confirmation functions you have a ; which isn't valid in a function calls parameter list
On the last line of the onClick function:
\');\');return false;\" >
The second \' is unmatched and the double quote \" shouldn't be escaped as far as I can see change that and maybe it will work for you.
<a href="" onClick="return select_item(<embed src=\"player.swf\" allowfullscreen=\"true\" quality=\"high\" pluginspage=\"http://www.macromedia.com/go/getflashplayer\" FlashVars=\"id=&flv=1257568908_.flv\" type=\"application/x-shockwave-flash\" width=\"450\" height=\"371\"></embed>')>
The above returns an "unterminated string literal" error.
How to solve this issue. This function is inside smarty template.
Thanks for every answer
I've also run into situations with Smarty where it tries to evaluate Javascript as Smarty template code.
In that case, you need to surround the Javascript with {literal}{/literal} tags.
However, in your case, I think you're missing a single-quote at the beginning of select_item( and a double-quote at the end of the onClick event:
<a href="" onClick="return select_item('<embed src=\"player.swf\" allowfullscreen=\"true\" quality=\"high\" pluginspage=\"http://www.macromedia.com/go/getflashplayer\" FlashVars=\"id=&flv=1257568908_.flv\" type=\"application/x-shockwave-flash\" width=\"450\" height=\"371\"></embed>')">
I'm not 100% sure if you really need to backslash-escape the double-quotes that are part of the <embed HTML.
For that amount of markup, I find it easier to read and debug if you don't do it inline as part of the onClick event. I use PrototypeJS so I'd handle it like this
Click Here
//Handle the click event of the above a tag
Event.observe($('doSelectItem'), 'click', function(event) {
var markup = '<embed src=\"player.swf\" allowfullscreen=\"true\" quality=\"high\" pluginspage=\"http://www.macromedia.com/go/getflashplayer\" FlashVars=\"id=&flv=1257568908_.flv\" type=\"application/x-shockwave-flash\" width=\"450\" height=\"371\"></embed>';
if( select_item(markup) ) {
//select_item returns true, so let the click event continue
}else {
//select_item returned false so cancel the click event.
Event.stop(event);
}
});
If you get
unterminated string literal
then it basically means that you have started a String, but never ended it. E.g.
var foo = "bar;
Solution is obvious: terminate it:
var foo = "bar";
Another common cause is using the same quotes inside the String as with which the String is wrapped:
var foo = "my mom said "go out!" to me";
You need to escape such quotes then:
var foo = "my mom said \"go out!\" to me";
In your specific case you have " inside the HTML string which is on its turn wrapped inside another "s of the onclick attribute. So:
<a href="" onClick="return select_item('<embed src="player.swf" ...
needs to be replaced by
<a href="" onClick="return select_item('<embed src=\"player.swf\" ...
It looks like ') is missing at the end of your onClick event, hence the JavaScript error. You also need to escape the double quotes. The line should look like:
<a href="" onClick="return select_item('<embed src=\"player.swf\" allowfullscreen=\"true\" quality=\"high\" pluginspage=\"http://www.macromedia.com/go/getflashplayer\" FlashVars=\"id=&flv=1257568908_.flv\" type=\"application/x-shockwave-flash\" width=\"450\" height=\"371\">');">
There is so much confusion about escaping quotes in javascript and HTML, especially when they are mixed like this.
Straight off the bat, try to avoid this situation in the first place. HTML is for markup, Javascript is for behaviours. That said...
In Javascript, you escape quotes with a backslash. This is so that when javascript interprets the string it knows where it ends.
var name = 'O\'Reilly';
In HTML, you use ampersands and a character code.
O"Reilly
Just remember that when you are writing code in your HTML, it's not being interpreted by javascript, it's being interpreted by the HTML parser. To a HTML parser, a backslash is just a regular character.
<a onclick="foo("bar");">
Now you see why I'd recommend avoiding the situation in the first place. Here's the alternative:
<a id="myLink">
<script type="text/javascript">
document.getElementById('myLink').onclick = function() {
foo('bar');
};
</script>