how to pass embed code in javascript - javascript

<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>

Related

PHP echo not producing correct result, turning string lowercase

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;

javascript onclick not working with parameters

I just want the user to click on a name and then it pops (alerts) some info. in the a tag if i don't pass any parameter it does alert something, it otherwise won't alert anything, even if i put something like this
<a href='javascript:sayThis('hi');'>
here's my html code (generated by some PHP):
PHP:
function showThis($color, $withFunctionYesOrNo, $first_levelIdFunction, $first_levelNameFunction, $first_levelLastNameFunction, $agent_email){
if($withFunctionYesOrNo == 'yes'){
$showThis = "<br>
<div>
<div style='margin-left:5%; border-left:6px solid ".$color."'>------
<a href='javascript:sayThis('".$agent_email."');'>
".$first_levelLastNameFunction.", ".$first_levelNameFunction." (ID: ".$first_levelIdFunction.")
</a>
<input type='submit' class='more' id='more' value='+' onclick='agentsBelow(".$first_levelIdFunction.")'>
</div>
<div style='margin-left:7%;' id=".$first_levelIdFunction."></div>
</div>";
}
return $showThis;
}
here is my JS code:
function sayThis(email){
alert(email);
}
First, I'd like to say that I would never use your coding practice. Not only do you have quote issues all over the place, but onclick the Event Object is passed to your Event Handler agentsBelow(). In these situations I do my code like this:
document.getElementById('more').onclick = function(e){
e = e || event; // don't even need to use the `e` argument above or this if not using the Event Object
agentsBelow('whatever');
}
Really, the style I'm showing is the way you should code, where your JavaScript is separate from your HTML. Of course, if you insist, you could just wrap your function within an Anonymous function in your HTML. Bad HTML practice:
onclick='function(){agentsBelow(\"you have String issues too\")}'
Note that you don't need to concatenate in double quotes. By the way:
onclick='agentsBelow(".$first_levelIdFunction.")'
using bad practice, should be:
onclick='function(){agentsBelow(\"$first_levelIdFunction\")}'
You are passing a variable to your JavaScript, not a String.
onclick='agentsBelow(".$first_levelIdFunction.")' could evaluate to:
onclick='agentsBelow(youFirstLevelIdFuntionVarResultIsNotaString)'
Still that wouldn't wouldn't work, since the Event Object would pass in.
Change this
<a href='javascript:sayThis('hi');'>
to this:
<a href='javascript:sayThis("hi");'>
change this
<a href='javascript:sayThis('".$agent_email."');'>
to
<a href='javascript:sayThis(\"".$agent_email."\");'>

impossible to escape single quotes in XML

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.

Enter param in inline javascript function

How can I add a param to the removeSound function in this JavaScript code?
I cannot get it to work.
var param = "111";
coder = '<a href="javascript:;" onClick="javascript: removeSound(' + param + ');" >Delete</a>'
Update
I do not know why code = was removed! This is needed to explain the problem context.
I just want to add a proper double quoting escape method to the answers as none showed a correct way to escape double quotes inside of an onClick attribute.
In HTML it is not sufficient to use only a backslash when escaping a JavaScript double quote. You need the proper HTML entity which is "
This is a live example:
Delete
However for readability I would recommend using Antony Scott's way by using single quotes.
Delete
To add the param as a variable from whatever script your HTML is generated in you should do this:
code = '<a href="javascript:;" onClick="javascript: removeSound("' + the_param + '");" >Delete</a>';
The other possible way should be:
code = '<a href="javascript:;" onClick="javascript: removeSound(\'' + the_param + '\');" >Delete</a>';
You need to use different quotes. Try something like this ...
<a href="javascript:;" onClick="javascript: removeSound('PARAM HERE');" >Delete</a>
try this
code = 'Delete';
try this
<a href="#" onClick="removeSound('121212')" >Delete</a>

Why am I losing my characters from my html string when trying to add html dynamically using javascript

I have a page that I am trying to dynamically add some links to. The links are getting added to the page fine, but the '[' and ']' at either end of the line are getting dropped. The code from my .js file is:
var html = "[ <a href='#'>Change</a> | <a href='#'>Remove </a> ]";
$(html).appendTo("#id123");
The result I want is:
[ <a href='#'>Change</a> | <a href='#'>Remove</a> ]
The result I'm getting is:
<a href='#'>Change</a> | <a href='#'>Remove</a>
If I wrap the line in a <span> tag like so:
var html = "<span>[ <a href='#'>Change</a> | <a href='#'>Remove </a> ]</span>";
$(html).appendTo("#id123");
it renders as expected. I set a breakpoint on the code and checked the html var right before the .appendTo and it contains the '[' and ']'.
Anyone know why this is happening? Are '[' and ']' special character that need escaped and I'm just forgetting that fact?
When you wrap your html variable inside of "$()", it creates a jQuery object out of it. That object removes anything that's outside of a markup tag (like <a> or <span>). You can take out the"[" and put "TESTING THIS" in it's place and you'll see it still won't show up.
So that's why you're losing it in your output.
No, those are just not valid XHTML. If you put the '[' and ']' in their own spans, like so:
"<span>[ </span><a href='#'>Change</a> | <a href='#'>Remove </a></span> ]</span>"
You would also get your expected text. jQuery will parse and create valid HTML, and the brackets aren't contained in an element.
I'm not sure why this happens. It seems like something internal to the appendTo() I tried it with append() and it worked out fine. So you could write $("#id123").append(html)

Categories