views:

810

answers:

4

I have run into a problem where the user enters data and if there are single quotes at all, the script errors out.

What's the best way to handle single quotes that users enter so it doesn't interfere with the jquery/javascript?

UPDATE:

I'm sending it through ajax to a database. here is the data parameter for a json ajax call.
data: "{str_" + sectionName + " :'" + UpdateText + "',EntityID: '" + EntityID + "' }",
with update text being the string that can contain the quotes.

+5  A: 

You need to escape the quotes with a \ or depending on how you plan to use the string you can use the javascript escape and unescape functions.

alert(escape("mike's"));
alert(unescape(escape("mike's")));

Also check this out for ways to escape strings with jQuery

mbrevoort
+1  A: 

You could find one of the many String.replaceAll implementations or write your own, and just replace any single or double quotes with an escaped version like \" or \'.

Jonathon
A: 

You should really sanitize your input inside your server-side script for a variety of reasons. If you're just displaying everything the user enters then your application can likely be used to launch a cross-site scripting attack.

Cfreak
relevant xkcd http://xkcd.com/327/
thenoviceoof
I think his issue is that he's getting a javascript error, client-side, while trying to send data to the server.
Jonathon
A: 

Javascript has a built in method just for this that covers more than just single quotes. Its called encodeURIComponent, from Javascript Kit:

Used to encode the parameter portion of a URI for characters that have special meaning, to separate them from reserved characters such as "&" that act as key/value separators. More inclusive than encodeURI(), it encodes all characters with special meaning in a URL string, including "=" and "&". Use this method only on the parameter portion of a URI; otherwise, the URI may no longer be valid if it contains one of the characters that are part of a valid URI (ie: "+") yet should be escaped if part of the URI parameter.

So your code should become:

data: "{str_" + encodeURIComponent(sectionName) + " :'" + encodeURIComponent(UpdateText) + "',EntityID: '" + encodeURIComponent(EntityID) + "' }",

I encode everything I send in a query string to be safe, but encoding the EntityID could arguably be skipped because it doesn't come from the user(I'm assuming), so you know it won't have special characters.

Tilendor