Escape single quote from last name in jQuery - javascript

I have ajax call in my jQuery code with which I am doing lookup with C# web method.
The call works normally most of the time, the user needs to enter last name and it will get all the results for that last name.
The problem happens when user will enter last name with single quote included such as O'leary.
This is the jQuery line I am using:
data: "{selectedAgent: '" + $('#<%=txtAgentNameText.ClientID %>').val() + "',
companyID: '" + $('#<%=ddlCompany.ClientID %>').val() + "'}",
The problem happens with the txtAgentNameText.ClientID value.

It looks like you are passing a JSON string to your jQuery ajax method. Why not just pass a javascript object?
var data = {
selectedAgent:$('#<%=txtAgentNameText.ClientID %>').val(),
companyID: $('#<%=ddlCompany.ClientID %>').val()
};
$.ajax({...data:data...})

Okay so the escape character is \ so you could replace \' or you could change your format so the last name is contained in double quotes! Both ways should suffice

Related

Struts2 pass url as a string

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.

issue passing a value to a function

EDIT: the 'more' link is built from here:
document.getElementById("elenco_fiveboard").insertAdjacentHTML('beforeend',
"<li>" +
"Titolo: " + valore_comando + " " +
"(<a href='javascript:getInfo("+ valore_comando +");'>" +
"more" + "</a>)" +
"</li>");
So I have to wrap valore_comando with hyphens but I get error trying to write
"(<a href='javascript:getInfo(""+ valore_comando +"");'>" +
or
"(<a href='javascript:getInfo('"+ valore_comando +"');'>" +
Sorry but I am not so strong with JS syntax and I am starting from some code that is not my own.
I have this simple JS function:
getInfo = function(title){
worker.port.postMessage("maggiori_informazioni:" + title);
}
I run it passing to the variable title a value but I always get an error. If title is 'example' then JS try to run
getInfo = function(example)
and I get the error:
Reference Error: example is not defined.
If title has more than one word: 'first example'
then JS will try to run
getInfo = function(first example)
and I get the error:
Syntax error: missing ) after argument list (looking for parentesys
after 'first').
What am I missing here??
This code is part of my first test with webSockets. If you want to see the full code you can open this index page and put a value on the first alert you see. That value is the title that you will see on the dashboard page.
The error can be reproduced trying to hit 'More' after each defined title in dashboard.
Sorry for italian in the site but it's a user requirement.
getInfo having reference to your function. So you can call this by:
getInfo(value);
Use quotes if you are passing string value and if you are passing
integer value you can simply pass.
For instance:
getInfo("Message Title"); //string
getInfo(3); // Integer
DEMO
You can also call like this:
getInfo = function(title){
alert("maggiori_informazioni:" + title);
}("String");
DEMO
Updates:
You can use this:
"(<a href='"+getInfo(valore_comando)+";'>" +
the function has been assigned to getInfo so please call getInfo()
string should be enclosed with ''
So the code should be
getInfo('example')
You're going to have to escape some quotation marks.
"(<a href=\"javascript:getInfo('"+ valore_comando +"');\">" +
The \ character before the quotation marks for the href attribute tells the JavaScript parser that they're part of the string instead of the beginning or end of a string.
The problem is that example is not defined. If you wanted to call the function with example as input it needs either single quotes or double quotes around it. "example" or 'example'.
getInfo("example"); // Works as intended
Another option is to create a variable containing the string, and pass that to the function.
var myVariable = "example";
getInfo(myVariable); // Still works, myVariable is a string with value "example"

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.

Trying to covert a variable into its value within a URL

I'm trying to insert a variable's value into a url, but it's not working; I'm just getting the variable not the value
'myid' and 'verif' are the variables and their values are integers.
This code inserts the url into a hidden field in a form
$('#return').val(http://pegdown.com/index.php?option=com_joom_creditspack&controller=paypal&view=paypal&layout=return&task=checkout&myid=myid&packid=1&verif=verif&jcode=xxx111xxx);
How do I write the following url so the variables 'myid' and 'verif' are converted to their values?
Well you are missing quotes so your code would not work at all.
$('#return').val("http://pegdown.com/index.php?option=com_joom_creditspack&controller=paypal&view=paypal&layout=return&task=checkout&myid=" + myid + "&packid=1&verif=" + verif + "&jcode=xxx111xxx");
You should probably use encodeURIComponent()
You need to quotes " " the strings and concat the variables +
Try
$('#return').val("http://pegdown.com/index.php?option=com_joom_creditspack&controller=paypal&view=paypal&layout=return&task=checkout&myid="+myid+"&packid=1&verif="+verif+"&jcode=xxx111xxx");
JavaScript does not support string interpolation. Try something like this.
myIdVal = encodeURIComponent(myId);
verifVal = encodeURIComponent(verif);
var url = "http://pegdown.com/index.php?option=com_joom_creditspack&controller=paypal&view=paypal&layout=return&task=checkout&myid=" + myidVal + "&packid=1&verif=" + verifVal + "&jcode=xxx111xxx";
$('#return').val(url);
A simple string works for me:
given index = 2,
`a.setAttribute("href", "myDirectory/" + index + ".jpg");` links the anchor to
"myDirectory/2.jpg", ie. the file number is taken from variable index.
Not sure if the setAttribute tolerates multiple tokens in its second parameter, but generally, this works.

Updating multiple parameters in a groovy string from a javascript function

OK, I'm a javascript/grails novice and I'm not sure what to do here.
Basically I have a javascript function that is being called with multiple parameters and I want to substitute them into a grails parsable string.
I have a number of grails drop downs that call a javascript function to link to another page with multiple parameters that need to be passed (item number and quantity).
Here is the select:
<g:select optionKey="key" optionValue="value" value="${item.getQty()}" name="qty" from="[1:1,2:2,3:3,4:4,5:5,6:6,7:7,8:8,9:9]"
onchange="goToPage('qty${item.id}',this.value)"></g:select>
The javascript function:
<script type="text/javascript">
function goToPage(itemId, val){
window.location.href="${createLink(controller:'GOrder' ,action:'updateShoppingCart' params:[item: "", qty: ""])}" + itemId + val;
}
So, it takes the itemId and val, concats them and replaces the last set of quotes with that concatenated value. What I want to happen is for each of the parameters to replace one of the sets of quotes.
I really don't understand how what looks like concatenating a string actually substitutes a value.
Thanks!
You're getting your server and client sides mixed up here. The
${createLink(controller:'GOrder' ,action:'updateShoppingCart' params:[item: "", qty: ""])}
is evaluated by Grails on the server side when rendering the GSP into HTML, so what you end up with in your JavaScript will be something like
function goToPage(itemId, val){
window.location.href="/myapp/GOrder/updateShoppingCart?item=&qty=" + itemId + val;
}
What you probably want instead is to generate just the base URL up to the question mark on the Grails side, then add the query parameters on the client side in JavaScript
function goToPage(itemId, val){
window.location.href=
"${createLink(controller:'GOrder', action:'updateShoppingCart'
).encodeAsJavaScript()}?item=" + encodeURIComponent(itemId)
+ "&qty=" + encodeURIComponent(val);
}
Note the way I've added encodeAsJavaScript() - you should always use this when generating values that are to be included in a JavaScript string literal, it will backslash-escape anything that needs it. Similarly any JavaScript string you're adding to a URL needs to be encoded using the JavaScript encodeURIComponent function - if the value of itemId were "item one", for example, you need to append item%20one to the URL.

Categories