Preserving single quotes

When I pull data from a source with Javascript I don’t have an issue with single quotes, but when I go to save data and it has a single quote the ajax call fails.

I don’t want to have to save this to the database: I'm happy!

I want to safely pass the string through with the single quote and preserving it in the database. What’s the best method for this?


Just where is the problem occurring? From your description it sounds like it is with the database call on the server rather than the JavaScript/Ajax.

The best way to handle quotes in data with database calls is to keep the SQL and data separate using a prepare statement for the SQL and a bind statement for the data - then there is no issue with the data containing quotes.

The problem is happening when a string containing a single quote gets passed into the URL used for the AJAX call. The call fails when the status doesn’t return 200. For example…

var ProductName = document.getElementById('ProductName').value; // Has a product name with a single quote for the value

// Function I created to make calls
ajax('mypage.asp?productname=' + ProductName);

If no single quotes are present then the call works as expected.

You could do:

var ProductName = document.getElementById('ProductName').replace(/'/g, "\\\\'");
ajax('mypage.asp?productname=' + ProductName);

but that feels hacky.

I would be tempted to use jQuery for AJAX functionality, as it abstracts a lot of the syntax away:

data{ "ProductName": ProductName},

If you’re worried about including a whole library for this, you can just create a custom build

I ended up dealing with the single quotes by using prepared SQL statements instead of trying to escape them in Javascript, which is probably the best approach anyway. The scripts are on a secure network with no risk of SQL injections so I wasn’t going to mess with doing a prepared statement but it’s solving the quote issue so I’m happy.

I had suspected that the problem was the SQL rather than the JavaScript from the way you described the problem.

There are a number of reasons for using prepare statements. That they prevent injection is a side effect and not their purpose. That they keep the data separate from the SQL means that you don’t need to use mysqli_real_escape_string to escape those characters that are valid in the data but which would otherwise break the sql - in this case the quote.