Fixing An "Unterminated String Literal" Error In An AJAX JavaScript HttpRequest

So you’ve written your first AJAX program, tested it, and it seems to work. Except sometimes, when your “helper script” is supposed to return some data from your database, you get this error:

Unterminated string literal

What gives? Basically, you’ve run into a quote mark in your data — and because it doesn’t know any better, JavaScript thinks you mean for it to end a string.

Of course, that’s not what you meant. As a result, you have more text appearing after what JavaScript considers the end of a string.

And when JavaScript sees that extra text, it wants it to start and end with quotes. Since, as far as JavaScript is concerned, that extra text isn’t fully enclosed in quotes, it’s unterminated — thus, an “unterminated string literal.”

Let’s look at this more closely, and see how simple it is to clear up.

Let’s assume we have a MySQL table that holds a VARCHAR field called p_name and an INT field called p_age; and let’s assume we’re going to get those fields to use in an AJAX request that will update a DIV on our page.

First, let’s look at the PHP we might use to pass database results as plain text to our AJAX code:

ob_start();
if(!$link = mysql_connect('localhost', 'username', 'password')) {
	$output = "alert('Error connecting to db server');\n";
}
elseif(!mysql_select_db('database')) {
	$output = "alert('Error selecting database');\n";
}
else {
	if(!$rs = mysql_query("SELECT * FROM table WHERE record_id = 1")) {
		$output = "alert('Database error executing query');\n";
	}
	elseif(mysql_num_rows($rs) == 0) {
		$output = "alert('No matching records found');\n";
	}
	else {
		$row = mysql_fetch_array($rs);
		$output = "var personName = '$row[p_name]'\n;";
		$output .= "var personAge = '$row[p_age]'\n;";
	}
}

header('Content-type: text/plain');
echo $output;
ob_end_flush();

The line that’s going to cause our unterminated string literal error is this one:

$output = "var personName = '$row[p_name]'\n;";

Note that we’re directly taking the p_name column from the database.

This is fine if the name is, say, Bob Smith or Tony Peña. But if the name contains a single-quote — say, Mike O’Shea — then to JavaScript, the first line of the results sent by our helper page will look like this:

var personName = 'Mike O'Shea';

If we add a space, it becomes clearer why JavaScript has a problem:

var personName = 'Mike O' Shea';

JavaScript sees ‘Mike O’ and considers it a string. Then it sees Shea’;.

There are two problems at this point: Shea’ is clearly a string, but it doesn’t have an opening quote, making it an unterminated string literal as far as JavaScript is concerned.

There’s also no string concatenation — we haven’t joined the two strings together with a + sign — but that error happens after the unterminated string literal, which is fatal as far as JavaScript is concerned, so the concatenation error doesn’t get reported.

OK, now that we know what the problem is, how do we fix it? Simple.

In PHP, we simply escape all fields we are sending with the addslashes() function:

$row = mysql_fetch_array($rs);
$output = "var personName = '" . addslashes($row['p_name']) . "'\n;";
$output .= "var personAge = '" . addslashes($row['p_age']) . "'\n;";

As the documentation for addslashes() notes, the function escapes “characters that need to be quoted in database queries etc.”

Conveniently, those are the same characters we need to escape when calling JavaScript’s eval() function on HTTP request response text, such as we might do in a response handler function:

function responseHandler(httpRequest) {
	if(httpRequest.readyState == 4) {
		if(httpRequest.status == 200) {
			eval(httpRequest.responseText);
		}
		else {
			alert('Error getting request.');
		}
	}
}

In ASP.NET, we might use a regular expression or, more simply, the String object’s Replace() method to clean up our text, like this:

Dim p_name As String = objReader("p_name").ToString()
p_name = p_name.Replace("'", "''")
Response.Write("var personName = '" & p_name & "';\n" & vbCrLf)

2 thoughts on “Fixing An "Unterminated String Literal" Error In An AJAX JavaScript HttpRequest

  1. Darren

    Hi Doug,
    Thanks for this article! I’m getting the ‘Unterminated string literal’ error message when trying to view the records of a particular client. I think I need to add the ‘addslashes’ to ‘site_name’ somehow but as I’m a newbie to php I’m not sure exactly how to do it. Could you take a look at the code and advise me please?

    The error message is flagging up this piece of code: $myarray=array();
    ——————————————–

    Thanks!

Leave a Reply