Single quotes in string with jQuery ajax
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 inter开发者_如何学Cfere 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.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
For escaping values in AJAX request, Do not write your own implementation of escape or use escape() method. (escape()
is deprecated). Instead create a JSON object and use JSON.stringify
method.
For your case it should be like (ignoring dynamic property for now):
//Create Javascript object
var obj = { SectionName: UpdateText, EntityID: EntityID };
Later in your ajax request you can do :
data: JSON.stringify(obj),
If you want to use dynamic properties with your JSON object then for your particular case you can create the object in two steps like:
var obj = { EntityID: EntityID };
obj["str_" + sectionName] = UpdateText;
This practice will save you from manually escaping single/double quotes and other invalid characters. JSON.stringify
will take care of that.
(I came here looking for a somewhat similar issue, but couldn't find a suitable working solution, so ended up posting one here)
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 \'.
Since you mentioned AJAX, there is a possibility that the strings involving single quotes are getting rejected at the server side.
Make sure you use escape string function
provided , for example by php, before inserting strings, to the database.
$user_name = $_REQUEST['username'];
$user_name = mysqli_real_escape_string($conn,$user_name);
$query = "INSERT into chat(username,message) VALUES('".$user_name."')";
This helps in escaping any single or double quotes that may appear in the '$user_name' string. Also it prevents against any kind of SQL injection atacks!
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.
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.
To escape a single quote in Javascript use
UpdateText.replace('\'', '\\\'')
To escape all single quotes use
UpdateText.replace(/'/g, '\\\'')
Thanks to mbrevoort, I elaborate more on his answer
When You are sending a single quote in a query
empid = " T'via"
empid = escape(empid)
When You get the value including a single quote
var xxx = request.QueryString("empid")
xxx = unscape(xxx)
If you want to search/ insert the value which includes a single quote in a query
xxx = Replace(empid, "'", "''")
The accepted answer should not be the solution to use.
In order to send this through AJAX to DB where request data has single quote '
in the string, do below:
- Organize your request data as an object.
var data = {
"sectionName" : sectionName,
"UpdateText" : updateText,
"EntityID" : entityID
}
- Stringfy your data to JSON and send with AJAX
data = JSON.stringify(data);
$.ajax({
url: "",
type: "POST",
data: data,
contentType: "application/json; charset=utf-8",
dataType: "json"
}).done(function (res) {
alert(res);
});
- Depends on the Database, for SQL Server, replace your single quote
'
to double quote''
to escape the single quote .
string data = date.Replace("'", "''")
精彩评论