Dealing with javascript function which processes strings that include quotes - javascript

So, essentially I have a button being created in PHP, which runs a JavaScript function, for example
function CreateText(id, string){
alert(id + '' + string);
}
So the PHPcode looks like this
echo "<img onclick='CreateText(3,\"$userinput\")'>";
Where user input is coming from a text box. But, whenever the user inputs a string which contains quotation marks, it throws an error.
Any idea how to fix this?

You're trying to create a valid Javascript literal inside an HTML attribute. For the Javascript, use json_encode, to make that a valid HTML attribute, use htmlspecialchars:
$onclick = sprintf('CreateText(3, %s)', json_encode($userinput));
printf('<img onclick="%s">', htmlspecialchars($onclick));
See http://php.net/sprintf, http://php.net/printf, http://php.net/json_encode, http://php.net/htmlspecialchars.

Related

Building HTML as String with Variables in Javascript

I'm trying to declare a string in javascript that will consist of HTML and a javascript var to declare the ID.
My problem is that I keep seeing "The server tag is not well formed" OR "Is not a valid identifier"
I believe this has something to do with the string/quotation configuration but I can't seem to find a clear answer.
My Problem
var HTMLStr, newtbl = tbl + "Table";
HTMLStr = '<tbody id="' + newtbl + '" class="prodTbl" runat="server"><tr>';
This produces the following error:
Parser Error: '' + newtbl + '' is not a valid identifier.
I see that in the error it changes the quotations and I've tried switching the quotations multiple times between double and single quotes but nothing seems to be working.
Can anyone provide some insight as to how I might be able to write this HTML string and declare the ID with a javascript variable??
Thanks again for all your help!
________________________________Comment Answers/Edit________________________
Kolt Penny: So I am planning on assigning the string to a var which will then be assigned back to the DOM like such
$('#DOMName').html(HTMLStr);
I also tried changing the
SvenWritesCode: The value of table in this instance is the string "Salad" which was passed to the function.
Also I did change the string to the indicated
(I am using asp.net as well this string would essentially be injected as a new table row in an asp.net table and will consist of a newly constructed table itself, resulting in the following)
asp:table
asp:tablerow
asp:tablecell /
/asp:tablerow
asp:tablerow
asp:tablecell
{HTML Table injection Point}
/asp:tablecell
/asp:tablerow
/asp:table

Converting href perl variables to normal scalar variables

I have these two variables that I am trying to compare. They both have the same value, however, one is a href variable - meaning, it's being read from a file like this
<a href=http://google.com>Variable</a>
It's read like this, but displayed as an anchor tag in the browser, so when I go to compare a value using print "$collect_zids{$key} --> $temp";I see in the browser as
Variable --> Variable
How it appears in the browser. One text another link.
I'm assuming these two values are different hence why this code does not run
if($collect_zids{$key} eq $from_picture){
print "<h1>Hello</h1>";
}
Is there a way I can convert the href variable into a normal scalar variable so that I can compare them?
Thanks!
P.S. I think Javascript might be the only way, however, I don't have any experience with it.
There is no such thing as an "href variable". You have two scalar variables. One contains plain text and the other contains HTML. Your task is to extract the text inside the HTML <a> tag from the HTML variable and to compare that text with the text from the plain text variable.
One way to do that would be to remove the HTML from the HTML variable.
my $html = '<a href=http://google.com>Variable</a>';
my $text = 'Variable';
$html =~ s/<.+?>//g;
if ($html eq $text) {
say "Equal";
} else {
say "Not Equal [$html/$text]";
}
But it cannot be emphasised enough that parsing HTML using a regular expression is very fragile and is guaranteed not to work in many cases. Far better to use a real HTML parser. HTML::Strip is made for this very purpose.
#!/usr/bin/perl
use strict;
use warnings;
use feature 'say';
use HTML::Strip;
my $html = '<a href=http://google.com>Variable</a>';
my $text = 'Variable';
my $parser = HTML::Strip->new;
$html = $parser->parse($html);
if ($html eq $text) {
say "Equal";
} else {
say "Not Equal [$html/$text]";
}
It's also worth pointing out that this is answered in the Perl FAQ
How do I remove HTML from a string?
Use HTML::Strip, or HTML::FormatText which not only removes HTML but
also attempts to do a little simple formatting of the resulting plain
text.
Update: In a comment, you say
I have no way of using these methods since I am not explicitly defining the variable.
Which is clearly not true. How a variable is initialised has no bearing whatsoever on how you can use it.
I assume your HTML text is in the variable $from_picture, so you would strip the HTML with code like this:
my $parser = HTML::Strip->new;
my $stripped = $parser->parse($from_picture);
if($collect_zids{$key} eq $stripped){
print "<h1>Hello</h1>";
}
I have no idea where you got the idea that you couldn't use my solution because I was directly initialising the variables, where you were reading the data from a file. An important skill in programming is the ability to see through complex situations and extract the relevant details. It appears you need to do some more work in this area :-)
I found the answer using the Perl module HTML::FormatText;
use HTML::FormatText;
my $formatter = HTML::FormatText->new();
my $string = HTML::FormatText->format_file("path_to_the_file"); #$string variable to hold the result and the path must be for a file.
After using the HTML::FormatText module, I was able to get the raw string that was being read, instead of it being interpreted as HTML. So, I was getting <a href=http://google.com>Variable</a> returned, instead of just Variable. After getting the raw string, I could use regex to extract the parts that I needed.
Credit to - https://metacpan.org/pod/HTML::FormatText

Grails String with html code breaking javascript(cordova)

In my grails application I have this String
String description = "<p>Some long description here that shows me the message in javascript</p><span data-icon=\"pushpin\"><p>But here doesnt give me any message in javascript"</p>
But when I try to recover the String to do an alert or something in javascrip, in my cordova project:
var button = '<button type="button" onclick="getInfo("' + x.description + '")">More infomation</button>';`
It only gives me the me the first <p></p> and writes inside the button, I know its from the String "pushpin" but there's a way to fix the "" or '' ?
I'd like to not use jQuery.
I suspect your issues come from the fact the double/single quotes aren't escaped when the value is rendered. Try using the encodeAsJavascript() function. You may also want to read the documentation about this.
x.description.encodeAsJavaScript()
Or in the controller (since you aren't using GSP)
def String description = "<p>Some long description here that shows me the message in javascript</p><span data-icon=\"pushpin\"><p>But here doesnt give me any message in javascript</p>".encodeAsJavaScript()

Javascript onclick function call issue: won't pass a string

So the basic rundown is that I'm trying to create a rudimentary means of flagging inappropriate content on our web mapping application.
Within a function that dynamically creates content for the sidebar of the webmap when the user clicks on a point I have this piece of code that should generate an image of a flag.
When the user clicks the flag, I want to run the function flagContent which should pass a url string into the function. From within this function I would then be able to
write it to a database later on (though I haven't made it this far yet).
Here are some code snippets I have been working with.:
1.This is where the flag image is generated
content += "<p class='info'><img id='flag' onclick='flagContent(" + attachmentInfo.url + ")
'src='assets/flag.png' style='height:15px'>Flag as inappropriate...</p>";
This is the connected function
function flagContent(imageUrl){ console.log(imageUrl)}
So basically the url is a string and I'd like to be able to manipulate it within the flagContent function. Unfortunately I can't get it to work. When I pass a numerical parameter such as attachmentInfo.objectID I do not run into the same problem.
For what it's worth I also get this error:
Uncaught SyntaxError: Unexpected token :
Any help would be greatly appreciated. Let me know if there is additional information that could help to solve this. Thanks!
I'm assuming that attachmentInfo.url would return a URL, which should be a string and it just needs to be surrounded by quotes. Since you've already used both types of quotes, you will have to escape some quotes.
content += "<p class='info'>";
content += "<img id='flag' onclick=\"flagContent('" + attachmentInfo.url + "')\" src='file.png'/>";
content += "Flag as inappropriate...";
content += "</p>";
Doing this makes the final out put look like this:
<p class='info'>
<img id="flag" onclick="flagContent('http://example.com')" src='file.png'/>
Flag as inappropriate...
</p>
The problem you had was that the URL was not surrounded by quotes, and it saw flagContent(http://example.com) and didn't know what to do with those bare words not in a string.

How to pass a String variable containing value with hyphens as a java script function parameter

Hi I am a newbie to java script. Have issues in passing the string variable whose value contains hyphen as function parameter. Fire bug throws an error saying 'identifier starts immediately after numeric literal'
I am using flexigrid to display data. In each row have placed an image. On click of that image a java script function should be called. Setting up of flexigrid record content is done in java as below,
record.put("view","<img src='images/ic_text_document.png' onclick='view_content("+objid+")'/> ");
Value of the varible objid is something like this c2692d22-a407-4d38-85ee-5c16f25bcce7.
Firebug throws identifier starts immediately after numeric literal' error by pointing at the 14th digit (in the above example at 4).
Tried passing the variable with different combination of quotes as suggested in other posts but dint work. Can somebody help me with this?
You'll need to escape the objid before generating the html, and unescape when using the value in the javascript.
OR do something like this......
record.put("view","<img src='images/ic_text_document.png' onclick='view_content("+ COUNTER + ")'/><div style='display:none' id='objid"+ COUNTER + "'>" + objid + "</div> ");
where counter is just a different number/value for each obj/objid.
and in js:
function view_content(objidcounter){
var real_objid = document.getElementById('objid' + objidcounter).innerText;
...
...
}
You should quote the objid value, like
record.put("view","<img src='images/ic_text_document.png' onclick='view_content(\""+objid+"\")'/> ");
Because when it render it is showing up as
view_content(FOOBARSTRING)
You need quotes in there.
record.put("view","<img src='images/ic_text_document.png' onclick='view_content(\""+objid+"\")'/> ");
Ideally you would not be adding the onclick handlers in the html markup directly.

Categories