I am trying to pass this url in the String variable using HTML button within java but this is not working. Can someone help?
String URL = "http://localhost/asp"
out.append("<input type=\"button\" value=\"Refresh4\" onClick=\"window.location.reload(URL)\"/>");
Thanks
You need to concatenate the variable into the string with + URL +:
String URL = "http://localhost/asp";
out.append("<input type='button' value='Refresh4' onclick='window.location.reload(" + URL + ")'/>");
Also, no need to escape all the " you used. In Javascript, you can use '.
Related
My problem is how to properly format string in javascript function parameter list. Function call is created on the server, problem is with string single apostrophes.
Code (.NET, C#) (I want only element.cMEST_CDO2 in single quotes):
#"ng-click='DeleteElementFromSession(" + element.iMERC_KEY + "," + element.iACCO_KEY +
#",'" + element.cMEST_CDO2 + #"');'></i></div>";
This code is on the client visible like this (it throws error):
I would like to be like this:
EDIT:
What I've found out with help from Kevin is, that anything that is being rendered wiht HTML should be HTML encoded.
My solution - I've made whole string instead of single params and html encoded whole string:
string paramList = $"{element.iMERC_KEY},{element.iACCO_KEY},'{element.cMEST_CDO2}', $event";
paramList = WebUtility.HtmlEncode(paramList);
And then insert this string into parameter list:
#"ng-click='DeleteElementFromSession(" + paramList + ");'></i></div>";
What I've found out with help from Kevin is, that anything that is being rendered wiht HTML should be HTML encoded.
My solution - I've made whole string instead of single params and html encoded whole string:
string paramList = $"{element.iMERC_KEY},{element.iACCO_KEY},'{element.cMEST_CDO2}', $event";
paramList = WebUtility.HtmlEncode(paramList);
And then insert this string into parameter list:
#"ng-click='DeleteElementFromSession(" + paramList + ");'></i></div>";
this line:
return '<a href="javascript:SomeFunction('+ var1 + ',' + var2 + ')"; > Stars </a>';
renders this:
Stars
which looks like a proper anchor tag but gives this error on clicking it:
Uncaught SyntaxError: missing ) after argument list
I am sure this error is misleading as the bracket in question is right there.
What am I missing?
Thanks in advance.
As var1 contains a string value, you need quotes around it:
return ' Stars ';
If the string can contains characters that needs to be escaped to be in a string literal, or needs to be URI encoded, you need some more code:
return ' Stars ';
Generating code like this is complicated, and it's easy to get it wrong. If possible you should generate elements instead, so that you can set the properties directly instead of creating code for it. Example using jQuery:
return $('<a>', { href: '#', text: ' Stars ' }).click(function(e){
e.preventDefault();
SomeFunction(var1, var2);
});
You have mistake in double quote at the end
return '<a href="javascript:SomeFunction('+ var1 + ',' + var2 + ');" > Stars </a>';
You are not wrapping your first var (which seems to be a string) within quotes.
return '<a href="javascript:SomeFunction(\''+ var1 + '\', ' + var2 + ');" > Stars </a>';
NOTE: As pointed out in the comments by Paul S. the semicolon should be inside the double quotes as it is part of the attribute value.
As you just want to add an <a> with a href, let the browser do the escaping and encoding work for you by using a method like String.prototype.link
' Stars '.link('javascript:SomeFunction(' + JSON.stringify(var1) + ', ' + JSON.stringify(var2) + ')');
// Stars
If you're running into issues like this a lot, consider whether it would be easier to switch to working with DOM methods, i.e.
var a = document.createElement('a');
a.addEventListener('click', SomeFunction.bind(a, var1, var2));
This saves you from having to write entity encodings etc to protect yourself at each level the code will be interpreted (JavaScript, HTML, JavaScript) and means you have more direct access over the DOM tree than by writing HTML
I am trying to directly write a Javascript variable assignment code on a ASP.NET web page.
Response.Write("<script>itHtml = '");
Response.Write("<div id=\"pop_ctrl\">Select</div><ul id=\"demo_ul\">");
foreach (Article a in arts)
{
Response.Write("<li class=\"demo_li\"><a onclick=\"ShowArticleCard(" + a.Id + ",\'" + a.User + "\',\'" + a.DateString + "\'); return false\"><div>" + it.User + "</div> <div>" + it.Title + "</div></a></li>");
}
Response.Write("</ul>");
Response.Write("';</script>");
Anchor tag in this markup executes a function ShowArticleCard() on click. This function accepts one int and two string parameters. When I am trying to add a C# string variable in place of string parameters, it replaces them like a JavaScript keyword. I tried using ',\' and \", but error persists. So, are there any levels of nested quotes we can use? If not how can I resolve this?
Try wrapping the actual value (parameter) in the quotes, like this,
onclick=\"ShowArticleCard(" + a.Id + ",'" +
a.User + "','" + a.DateString + "'); // Remaining code
Changed
I have removed the single quotes from the int type param, and removed the escape slash from the string types. They can be simply put as, '. Now when the code would run, it would be considered as a string. Otherwise (if the value is numeric) then ignore these quotes and enter them as they are. Only string-type data requires to be wrapped in either ' or ". In JavaScript they are same. In C#, ' and " have different meanings, you know that well.
Tip: Also, if you are writing something for client-side rendering, like in ASP.NET, you can easily write it as,
string.Format("<a href='{0}' onclick='func({1})'>My Link</a>",
hyperlink, param);
This would be rendered as you want it to be. :) The single quotes would be converted to double quotes once rendered in your browser. Or you can use # before the string, and write " inside the string without having to escape them.
I figured out a way of doing this. I don't know why it didn't came in my mind before.
I enclosed JavaScript function's string parameters with \\'. Like this:
ShowArticleCard(" + a.Id + ",\\'" + a.User + "\\',\\'" + a.DateString + "\\');
So that the resultant code will be:
ShowArticleCard(someid,\'someUser\',\'someDateString\');
string mystring == "<input class=\"success\" type=\"button\" id=\"Delegate_New_btn\" value=\"New\" onclick=\"location.href="+mylocation+"'/>";
I have a string like above.
The problem is when I innerHTML it to a div like below, then it shows incorrect syntax error :
document.getElementById("id").innerHTML=mystring;
What I need is :
<input type="button" value"somevalue" onclick="location.href='mylocationurl'"/>
I don't know how to include this single quotes inside a double quotes. I had tried back slash method but I also failed to implement that.
Note : i had define this in my serverside C# and pass it to client side
Please help me to solve this.
More information
VM.Custombuttons_tag = "<td><input class=\"btn btn-mini btn-success\" type=\"button\" id=\"Delegate_New_btn\" value=\"New\" onclick='location.href=\'" + string.Format("{0}://{1}{2}", Request.Url.Scheme, Request.Url.Authority, Url.Content("~")) + "/ABC/Delegate/AssignListUserLevel?PeriodId=0'/></td>";
this is my full code here VM is a method and Custombuttons_tag is string so when ever i run my code it will innerHTML the code to a div and it shows some incorrect syntax error
You do not define a string using string, you define everything using var:
var myString = "I am a string";
var myNumber = 1000;
Java and JavaScript do have their differences!
You may want to try something like this ...
var input=document.createElement('input');
input.setAttribute('class','success');
input.setAttribute('type','button');
input.setAttribute('id','Delegate_New_btn');
input.setAttribute('value','New');
input.setAttribute('onclick','location.href="'+mylocation+'"');
document.getElementById('id').appendChild(input);
You have a few problems here, the first being that you do not use == when assigning variables, and the second being that you need to use var rather than string.
So, your code should look like this:
var mystring = "<input class='success' type='button' id='Delegate_New_btn' value='New' onclick='location.href=\'+mylocation+\''/>";
The only time that you need to use \' is if your single quotes are included in single quotes, like you have with the location.href part.
You can mix-match single and double quotes as long as they are nested properly.
var mystring = '<input class="success" type="button" id="Delegate_New_btn" value="New" onclick="location.href=' + mylocation + '"/>';
I have jsp code as:
onclick="showURL('${result.url}')"
${result.url} is dynamic value. When an apostrophe comes in the URL I get the error.
I have tried all the methods like escape, encodeURI, replacing the single quotes with double but nothing works.
Script call is as follows:
function showURL(name){
alert(name);
}
<%#taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>
${fn:escapeXml(myString)}
See: How can I escape special HTML characters in JSP?
You need to ensure that ${result.url} returns a valid URL. Quotes are invalid in URLs. It sounds like that you're returning an URL with a query string with unencoded parameters like follows
public String getUrl() {
return "page.jsp?foo=" + foo + "&bar=" + bar;
}
You need to change the method as follows
public String getUrl() {
return "page.jsp?foo=" + URLEncoder.encode(foo, "UTF-8") + "&bar=" + URLEncoder.encode(bar, "UTF-8");
}
You cannot fix this in the JavaScript side with escape(), etc. It's already too late then.
why not just do this:
onclick=showURL("${result.url}");
function showURL (result_url) {
alert("<c:out value='"+ result_url + "' />");
}
then you don't have to worry about escaping at all.
-tjw