Alex Rivera | Logout

Single quotes in string with jQuery ajax

Asked 2009-12-04T04:51:35.993
10

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.

Edit
Report

1 Answer

0

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.

answered 2010-03-03T17:28:29.963

Your Answer