Struts2 pass url as a string - javascript

I'm using javascript function to submit form, and in the javascript function, I'd specify form.action= "Struts2 url goes here";
Here's a snippet of my code:
var form = document.forms['myForm'];
if (form != null) {
var backURL = "ActionB!someMethodB.action?Bparam1=somevalue&Bparam2=somevalue";
form.action="ActionA!someMethodA.action?Aparam1=somevalue&Aparam2=" + backURL;
form.submit();
}
The problem is that in the action method someMethodA, the value for Aparam2 is always cut off by the first ampersand in backURL.
I tried to enclose backURL with quotes like this form.action="ActionA!someMethodA.action?Aparam1=somevalue&Aparam2='" + backURL + "'"; but it did not work. It kind of makes me feel like that the value of backURL is not treated as a whole but parsed as well.
I would like to know if there's a way to work around this.

If you want to use a parameter in the url which contains special characters they should be urlencoded.
var backURL = encodeURIComponent("ActionB!someMethodB.action?Bparam1=somevalue&Bparam2=somevalue");
Also, a hardcoded value for URL could be built on server with s:url tag.
var backURL = encodeURIComponent('<s:url action="ActionB" method="someMethodB"><s:param name="Bparam1" value="somevalue"/><s:param name="Bparam2" value="somevalue"/></s:url>');
In this case by default & is escaped to & but escaped value is used normally with the browser.

Related

Get a string in a variable to create a dynamic link in Javascript

What I am trying to accomplish is to have a map that has a few locations. Whenever users click on each location, a popup will emerge with some information. I am trying to create a dynamic link inside that popup.
Below is my code in Javascript
function parseDescription(message){
var string=""
for(var i in message){
if (i=="CommunityPartner"){
string+='<span style="font-weight:bold">'+i+'</span>'+": "+message[i]+'</a>'+"<br>"
} else if (i=="WeitzCECPartner"){
string+='<span style="font-weight:bold">'+i+'</span>'+": "+message[i]+'</a>'+"<br>"
} else if (i=="PhoneNumber"){
string+='<span style="font-weight:bold">'+i+'</span>'+": "+message[i]+'</a>'+"<br>"
} else if (i=="Website"){
var link = "http://www."+message[i];
string+='<span style="font-weight:bold">'+i+'</span>'+": "+'<a href="{{link}}" >'+link+'</a>'+"<br>"
}
//string+='<span style="font-weight:bold">'+i+'</span>'+": "+message[i]+"<br>"
}
return string;
}
I keep getting this error. I think it's related to the value passed into "a href" :
Request Method: GET
Request URL: http://127.0.0.1:8000/%7B%7Blink%7D%7D
Please help
Instead of using {{link}} in the string, you can try this:
var link = "http://www." + message[i];
string += '<span style="font-weight:bold">' + i + '</span>: ' + link + '<br>';
The following syntax:
{{link}}
is incorrect, because this part was inside a string it was interpreted by the JS engine as a string.
You can use template strings (backticks `) to insert variables as string into another string. For example:
`<span style="font-weight:bold">${i}</span>:<a href="${link}" >${link}</a><br>`;
This example assumes that link and i are both variables which you want to insert dynamically into your string. If you have more questions leave a comment.
I think the problem lies in the {{link}}. Your code looks like native js and not angular or any other framework. Thus, the characters {{}} inside a string do not mean anything. The url that you get is exactly those characters, escaped. Use plain old string concatination to enter your href value.

Javascript & doesn't append next parameter value pair

I am trying to append multiple parameter value pairs to a url for an ajax request. I know that this is supposed to be done using & instead of &. Why then, does the first function work and the second one fails?
function accountByName(firstName, lastName, resultRegion) {
var baseAddress = "Bank";
var data = "firstName=" + getValue(firstName) + "&lastName=" + getValue(lastName);
var address = baseAddress + "?" + data;
ajaxResult(address, resultRegion);
}
function accountByName(firstName, lastName, resultRegion) {
var baseAddress = "Bank";
var data = "firstName=" + getValue(firstName) + "&lastName=" + getValue(lastName);
var address = baseAddress + "?" + data;
ajaxResult(address, resultRegion);
}
When I do print statements in the serverside java code the firstName variable prints fine, but the lastName variable always comes back null when I use & Both variables print fine when I just use &, but I know this is not correct XML.
So here's what your instructor meant:
In an (X)HTML page if you have something like:
Link
You should use (even though it really doesn't make a difference except to the validator)
Link
That is the ONLY time you should use an & in a query string.
You are incorrect: you are not supposed to use & as the parameter separator in a URL. The first function constructs the URL:
Bank?firstName=foo&lastName=bar
The second:
Bank?firstName=foo&lastName=bar
The 1st URL has two parameters: firstName and lastName with the values foo and bar.
The 2nd URL has two parameters: firstName and amp;lastName with the values foo and bar. (Note: I believe the second parameter name is invalid and am not sure how it'd be parsed in Java; it may be library/server dependent)
Your Java code fails printing the lastName parameter in the second case because in that case it is not set.
Your confusion seems to stem from a misunderstanding of the URL format. The URL format is unrelated to XML or HTML. It is completely separate from the two. & is an XML/HTML entity. Were the URL some form of XML, you would be correct. However, as it is not one should not expect it to follow the rules and standards of XML.
You're creating a URL, not some XML content. You have to think about what system is going to be paying attention. An XML/HTML parser is never going to look at that URL you're creating. The server, however, will certainly be interested in interpreting the URL as a URL. The XML entity syntax & is completely alien to something parsing a URL.

how to escape single quote in dynamically created HTML tag content

In my javascript code,
I have a variable which have a string. String contains ' or quote in it. Example
var name= "hi's";
I am creating a link dynamically in a code. where it is written as a string i.e a variable content will be used dynamically to create a link on html page.
content= '<a onclick="javascript:fun(\'' + name + '\');">'
Here it is giving problem that quote in variable name completes the string in content. and hence rest portion of content is not recognised..
similar problem arises if var name = 'hi"s';
i.e. if double quote is present in it.
plz help
This is how you would create an anchor properly and completely avoid the need to escape anything.
var name = "Hi's",
anchor = document.createElement('a');
// should have an href
// links will be displayed differently by some browsers without it
anchor.href = '#';
// using onclick for pragmatic reasons
anchor.onclick = function() {
fun(name);
return false;
}
anchor.innerHTML = 'hello world';
// later
mydiv.appendChild(anchor);
Btw, the onclick attribute shouldn't start with "javascript:" at all; that's already implied.
Update
If you're still interested in the inline version, variables need two steps of encoding:
The first is to serialize the variable properly; I would use JSON.stringify() for that
The second is HTML escaping; the simplest form is simply to replace double quotes with their proper encoded values.
For example:
var content = '<a href="#" onclick="fun(' +
JSON.serialize(name).replace(/"/g, '"') + ');">hello</a>';

Encoding URL (including characters like &) using jquery or native javascript function?

I have one one hidden paramter in form whose value is
custAddress=CustomerAddress.do?fisrtName=scott&lastName=Miles
I want to encode it before sending it and so that characters like & can be replaced with %26 etch
i tried using javascript built-in encodeURI("urlToencode") but does not encode characters like &?
Try this code line,
encodeURIComponent("fisrtName=scott&lastName=Miles");
Use https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/encodeURIComponent
You need to call that on each dynamic part (name and value) of the URL query string. So the question is what is the URI component in custAddress=CustomerAddress.do?fisrtName=scott&lastName=Miles That doesn't really look like a URL because you have the = before the ?
The most sense that I can make is that the full URL is something like
http://myserver/file.do?custAddress=CustomerAddress.do?fisrtName=scott&lastName=Miles
In which case, you should build your URL like
var custAddress = "CustomerAddress.do?fisrtName=scott&lastName=Miles";
var initialPath= "/path/to/file.do?";
var url = initialPath + "custAddress=" + encodeURIComponent(custAddress);
Since you mentioned jQuery, you can use a $.param, looks cleaner and does the encoding for you, and you can give it multiple query parameters at once
var url = initialPath + $.param({
custAdrress: custAddress,
otherParam: "paramVal",
// Both the param name and value need to be encoded and $.param does that for you
"funny Name & Param": "funny & value ="
});

How to encode a query string so that it is the value of another query string in javascript?

I have a javascript function which passes as a query string value another query string.
In other words, I want the query string to be:
http://www.somesite.com/?somequery=%3fkey%3dvalue1%2520%26%2520key2%3value3
However, if I redirect like this:
var url = 'http://www.somesite.com/?somequery=';
url += escape('?key=value1&key2=value2');
window.location = url;
it ends up as http://www.somesite.com?somequery=?key1=value1&key2=value2 in firefox and IE7 which means that I can't parse the query string correctly.
I also tried using encodeURIComponent which didn't work either.
Is there another function or a hack to force the redirect to keep the somequery value escaped??
encodeURIComponent will work. (You may or may not want the leading ‘?’, depending on what the script is expecting.)
var c= 'd e'
var query= '?a=b&c='+encodeURIComponent(c);
var uri= 'http://www.example.com/script?query='+encodeURIComponent(query);
window.location= uri;
Takes me to:
http://www.example.com/script?query=%3Fa%3Db%26c%3Dd%2520e
When you hover over that it may appear once-decoded in the browser's status bar, but you will end up in the right place.
escape/unescape() is the wrong thing for encoding query parameters, it gets Unicode characters and pluses wrong. There is almost never a case where escape() is what you really need.
Native escape method does that. but also you can create a custom encoder like:
function encodeUriSegment(val) {
return encodeUriQuery(val, true).
replace(/%26/gi, '&').
replace(/%3D/gi, '=').
replace(/%2B/gi, '+');
}
this will replace keys used in query strings. further more you can apply it to any other custom encodings by adding needed key-values pairs.
function downloadFile(){
var filePath = "C:/Users/HP/Desktop/Project Folder/DemoProject/";
var fileInfo = "Error_Issue Minor Cosmetic & Major Fatal Issues (Demo_Project) (2017)_GeneratedOn_12_21_2017 21924 AM.xlsx";
if((filePath != undefined && filePath.length > 0) && (fileName != undefined && fileName.length > 0)){
var downloadUrl = "../download?fileName="+encodeURIComponent(fileName)+"&filePath="+encodeURIComponent(filePath);
$window.location = downloadUrl;
}else{
alert("Please define a fileName for downloading...");
}
}
javascript:alert(escape('?key=value1&key2=value2'));
Works fine for me?

Categories