escaping single quotes for ajax calls - javascript

I have a php page which is called via AJAX. and basically it fetches some value from my database and echos back at table with inputs etc. The problem is when the string it fetches contains quotation marks(actually only single quotes seem to be effected). So on the php page there's something like this:
$value = htmlentities($DB_result->cloumn);
echo'<input type = "button" onClick = "$(\'#something\').val(\''.$value.'\');" />'
so if $value = "hello", no problems but if: $value = 'hello', the page which I'm making the AJAX call from throws up some such error: Syntax Error: unexpected identifier.
so I guess the quotations in $value have not been escaped, which I thought it would with the htmlentities. any Ideas how to solve this much appreciated. Thank you.

The problem is that $value contains single quotes, which interfere with the correct parsing of javascript. from the manual entry for html entities:
all characters which have HTML character entity equivalents are translated into these entities.
this means that your single quotes are not escaped, they are only translated in a way browsers will better understand. You need to use addslashes():
$value = htmlentities(addslashes($DB_result->cloumn));
"'hello'" will become "\'hello\'" which in the browser will look like:
<input type = "button" onClick = "$('#something').val('\'hello\'');" />
which will attribute the string 'hello' (with the single quotes) to the value attribute of $('#something')

Try:
$value = htmlentities($DB_result->cloumn, ENT_QUOTES, "utf-8");
Passing ENT_QUOTES through as a flag will convert both double and single quotes.

Related

PHP - return confirm within PHP issue

could somebody please help me with the below:
echo ('<font color="FFFFFF"><b>Click here to claim ticket</b></font>');
I know there is an issue with some " ' " but can't figure this out. I am getting a syntax error just before the 'Are'. The line of code was working as expected before I added the:
onclick="return confirm('Are you sure you want to claim this ticket?');"
Thanks!
If you want to use the same quotes you opened the string with inside the string itself, you should escape it.
For instance:
$var = 'Hello, let's go!';
echo $var;
This code will throw a parse error because this is how PHP sees the code:
) New variable $var.
) Is a string, declared using single quotes '.
) After the opening quote we have 'Hello, let'
) Now PHP expects some kind of valid code operators, like ., and next string or ;, but it gets some characters, which are treated as instructions rather than strings because they are outside the quotes, and
) PHP throws a parse error.
To fix this, you can use the backslash \ a.k.a 'escaping' character.
For example, to fix your problem:
echo
('<font color="FFFFFF"><b>Click here to claim ticket</b></font>');
See the baskslashes \ surrounding the single quotes inside the confirm JavaScript function? This tells PHP to treat these quotes as normal characters instead of string start/end declarations. Same thing works for reversal when you use double quotes as string declarators.
For example, when you want to show the actual representation of $ or any characters that have special meaning in a double quoted string, which allows direct insertion of variables (and some other's, like class properties) values you would use the escaping character.
For example:
$apples = 12;
$talk = "I have $apples \$apples. Thanks, now have a backlash! \\!";
echo $talk;
This will output I have 12 $apples. Thanks, now have a backslash! \!
Now, you are not actually required to escape the escaping character (it will show just as well if it does't have anything to escape after it).
Read this: PHP Manual - About Strings
You can also switch your single quotes on the edges of your echo statement with regular quotes, which will allow you to insert the $id variable easier. Then, you just have to escape the quotes around your JavaScript in onClick and switch all the other quotes to single quotes.
echo "<a href='assign.php?id=$id' onclick=\"return confirm('Are you sure you want to claim this ticket?');\" style='text-decoration: none'><font color='FFFFFF'><b>Click here to claim ticket</b></font></a>";
However, there is a better way.
Interpolate PHP into HTML
(Instead of HTML into PHP)
The best way to do this is to write HTML as HTML, and interpolate PHP variables into the HTML. This is best practice as it allows syntax highlighting in IDE's, and looks much cleaner/easier to read.
Just write the entire element as HTML, and then echo the $id variable inside the HTML (instead of writing all of the HTML in a PHP echo statement).
<a href="assign.php?id=<?=$id;?>" onclick="return confirm('Are you sure you want to claim this ticket?');" style="text-decoration: none">
<font color="FFFFFF">
<b>
Click here to claim ticket
</b>
</font>
</a>
With this method, you don't have to worry about escaping quotes, and it will allow you to use regular quotes throughout your entire element.
You need to escape the nested ' by doing \'
echo ('<font color="FFFFFF"><b>Click here to claim ticket</b></font>');
Note that all the stuff inside the single quotes is considered as string by the PHP interpreter.
Docs: PHP: Variables - Manual

Passing PHP variables as strings to javascript

Somehow my php function, which creates a button, which calls a javascript function, does not pass the php variables as strings.
function addTableEntry($id, $name)
{
echo('<tr>
<td>'.$id.'</td>
<td>'.$name.'</td>
<td>Manage group
</tr>');
}
addTableEntry(1,"livingroom");
The function activateGroupSettingsOverlay() always gets called with (1, livingroom) whenever it is clicked and i get an error "livingroom is undefined".
How can i pass $name as a String? I tried to put quotes around it (like this: '.$id.',"'.$name.'", but that did not work.
You have to "escape" quotes inside a string if you want them to persist:
echo '..... onClick="activateGroupSettingsOverlay('.$id.',\''.$name.'\')"....'
The important thing are the backslashes before the (single) quotes.
The reason it wasn't working is because you were not including quotes in the javascript.
While other answers "fix" the issue they don't really explain it, to be clear this line
<td>Manage group
Is output like this
<td>Manage group
As is, the livingroom does not have quotes and so javascirpt is treating it as a variable, hence the undefined error. To fix it you want it to look like this when output.
<td>Manage group
Modifying this line is all you have to change
<td>Manage group
Adding the single quotes \' with escaping.
Personally for things like this I like to use what is called a HEREDOC or NEWDOC
<<<HTML HTML; and <<<'HTML' HTML; respective. HEREDOC is like using a " and new doc is like using ' in that you cannot use php variables within a NEWDOC but you can within the HEREDOC if you enclose them in { } braces. Because of this we'll want to use a HEREDOC so we can use php variables in the output.
function addTableEntry($id, $name)
{
echo <<<HTML
<tr>
<td>'.$id.'</td>
<td>'.$name.'</td>
<td>Manage group
</tr>
HTML;
}
addTableEntry(1,"livingroom");
http://php.net/manual/en/language.types.string.php - scroll down to where it says HEREDOC
The advantage to doing this is that you don't have to escape the single quotes, which makes it way more readable IMO. The trick with HEREDOC, or NEWDOC, is the ending HTML; has to start a new line and can be the only thing on that line, no leading or trailing spaces, or it won't work properly..
For this case it is probably simple enough to get away with how you are doing it, but if you needed to use concatenation in javascript, the quotes would become a hassle. For example say you wanted to add a html image tag using javascript with a javascirpt variable for the image name, but use php to get the server host name( html and variables in javascript ).
echo '
var foo = "image.jpb";
$(body).html( \'<img src="'.$_SERVER['HTTP_HOST'].'\'+foo+\'" />\' );
';
This quickly becomes unmanageable because ( not even sure if I have that right, anyway ). Compare how much cleaner this is, because you are not wasting the quotes in php....
echo <<<HTML
var foo = "image.jpb";
$(body).html( '<img src="{$_SERVER['HTTP_HOST']}'+foo+'" />' );
HTML;
Please try with this code:-
function addTableEntry($id, $name)
{
echo("<tr>
<td>".$id."</td>
<td>".$name."</td>
<td>Manage group
</tr>");
}
addTableEntry(1,"livingroom");
Change
onClick="activateGroupSettingsOverlay('.$id.','.$name.')"
to
onClick="activateGroupSettingsOverlay('.$id.',"'.$name.'")"
#chandresh_cool was kind of right, you have to "force" the quotes
onClick="activateGroupSettingsOverlay('.$id.',\''.$name.'\')"

json_encode() gives special charactors like '\n'..how can i replace them in PHP?

I encoded an array using json_encode() function and it gave me a string like this..
"[{"details":"power - 2000w \nac-220-240v \/ 50-60hz\n369 degree cordless base\n","model_id":"MC-EK3428 \/ MC-EK3328"}]"
as you can see it contains special characters like "\n"..I want these special characters to be replaced with "" because in javascript I am using the JSON.parse(); function to convert this string to an object..
but it gives me an error
syntaxerror : missing ) after argument list
I think this is because of the special characters in the string..how can I escape these?
Edit
php :
$view->jsonencoded_array = json_encode($array);
javascript :
var products = JSON.parse('<?php echo $jsonencoded_array; ?>');//this line gives me the error
update :
found out that the error is given in this :
'<?php echo $jsonencoded_array; ?>'
The problem here is that \n (and various other combinations) have special meaning inside a JavaScript string, and you are dumping your JSON into a JavaScript string without doing any conversion of those characters.
Since JSON is heavily inspired by JavaScript literal syntax, you can use json_encode to convert a PHP string into a JavaScript string.
There are some gotchas, the main one being that </script> can appear in a JSON text without causing any problems, but having that in the middle of your JavaScript <script> element is going to cause the HTML parser to cut off your JavaScript in the middle of the string … but PHP's default encoding rules will generate <\/script> which solves that problem.
So:
<?php
$json_array = json_encode($array);
$javascript_string = $json_encode($json_array);
?>
var products = JSON.parse(<?php echo $javascript_string; ?>);
That said. A JSON array is also a JavaScript array, so you can skip that step entirely.
<?php
$json_array = json_encode($array);
?>
var products = <?php echo $json_array; ?>;
There must something that you are missing or there is some other reason for your issue while parsing in JavaScript; because json_encode handles \n and other special characters such " \ etc. very well and escape them properly without any explicit work.
I would suggest you to check the JSON produced and you are supplying to JavaScript and see if there is something missing in between.
Note: You can do a str_replace but it is not advised. Better stick to json_encodesince its s standard function and it works well.
Edit:
You should be echoing $view->jsonencoded_array not just $jsonencoded_array, no need to parse already JSON object.
php :
$view->jsonencoded_array = json_encode($array);
javascript :
var products = <?php echo $view->jsonencoded_array; ?>;
json_encode() twice helped me to solve this issue..
$view->jsonencoded = json_encode(json_encode($array));

Append user data to url before sending request in PHP

What would be the easiest way to append form data to a json url prior to sending the request? I know next to nothing about php but Im trying either way
The PHP I have so far, I need to replace the ZIP before.json with the content im getting from $_GET['zip']
<?php
$zip = $_GET['zip'];
$zip_data = file_get_contents($zip);
$weather_data = file_get_contents("http://api.wunderground.com/api/myapi/conditions/q/ZIP.json");
echo $weather_data;
?>
In PHP if you just put the variable name inside a string that is quoted with double quotes, it puts the value into the string:
$weather_data = file_get_contents(".../q/$zip.json");
You can also put curly brackets around it to make it cleaner to read:
$weather_data = file_get_contents(".../q/{$zip}.json");
Or you can close the string, use the dot operator to concatenate, and reopen the string:
$weather_data = file_get_contents(".../q/" . $zip . ".json");
Replace
"http://api.wunderground.com/api/myapi/conditions/q/ZIP.json"
With
sprintf("http://api.wunderground.com/api/myapi/conditions/q/%s.json", $_GET['zip'])
(or whatever variable you want to take it's place)
More on string formatting with sprintf

jQuery.parseJSON throws “Invalid JSON” error due to escaped single quote in JSON

I’m making requests to my server using jQuery.post() and my server is returning JSON objects (like { "var": "value", ... }). However, if any of the values contains a single quote (properly escaped like \'), jQuery fails to parse an otherwise valid JSON string. Here’s an example of what I mean (done in Chrome’s console):
data = "{ \"status\": \"success\", \"newHtml\": \"Hello \\\'x\" }";
eval("x = " + data); // { newHtml: "Hello 'x", status: "success" }
$.parseJSON(data); // Invalid JSON: { "status": "success", "newHtml": "Hello \'x" }
Is this normal? Is there no way to properly pass a single quote via JSON?
According to the state machine diagram on the JSON website, only escaped double-quote characters are allowed, not single-quotes. Single quote characters do not need to be escaped:
Update - More information for those that are interested:
Douglas Crockford does not specifically say why the JSON specification does not allow escaped single quotes within strings. However, during his discussion of JSON in Appendix E of JavaScript: The Good Parts, he writes:
JSON's design goals were to be minimal, portable, textual, and a subset of JavaScript. The less we need to agree on in order to interoperate, the more easily we can interoperate.
So perhaps he decided to only allow strings to be defined using double-quotes since this is one less rule that all JSON implementations must agree on. As a result, it is impossible for a single quote character within a string to accidentally terminate the string, because by definition a string can only be terminated by a double-quote character. Hence there is no need to allow escaping of a single quote character in the formal specification.
Digging a little bit deeper, Crockford's org.json implementation of JSON for Java is more permissible and does allow single quote characters:
The texts produced by the toString methods strictly conform to the JSON syntax rules. The constructors are more forgiving in the texts they will accept:
...
Strings may be quoted with ' (single quote).
This is confirmed by the JSONTokener source code. The nextString method accepts escaped single quote characters and treats them just like double-quote characters:
public String nextString(char quote) throws JSONException {
char c;
StringBuffer sb = new StringBuffer();
for (;;) {
c = next();
switch (c) {
...
case '\\':
c = this.next();
switch (c) {
...
case '"':
case '\'':
case '\\':
case '/':
sb.append(c);
break;
...
At the top of the method is an informative comment:
The formal JSON format does not allow strings in single quotes, but an implementation is allowed to accept them.
So some implementations will accept single quotes - but you should not rely on this. Many popular implementations are quite restrictive in this regard and will reject JSON that contains single quoted strings and/or escaped single quotes.
Finally to tie this back to the original question, jQuery.parseJSON first attempts to use the browser's native JSON parser or a loaded library such as json2.js where applicable (which on a side note is the library the jQuery logic is based on if JSON is not defined). Thus jQuery can only be as permissive as that underlying implementation:
parseJSON: function( data ) {
...
// Attempt to parse using the native JSON parser first
if ( window.JSON && window.JSON.parse ) {
return window.JSON.parse( data );
}
...
jQuery.error( "Invalid JSON: " + data );
},
As far as I know these implementations only adhere to the official JSON specification and do not accept single quotes, hence neither does jQuery.
If you need a single quote inside of a string, since \' is undefined by the spec, use \u0027 see http://www.utf8-chartable.de/ for all of them
edit: please excuse my misuse of the word backticks in the comments. I meant backslash. My point here is that in the event you have nested strings inside other strings, I think it can be more useful and readable to use unicode instead of lots of backslashes to escape a single quote. If you are not nested however it truly is easier to just put a plain old quote in there.
I understand where the problem lies and when I look at the specs its clear that unescaped single quotes should be parsed correctly.
I am using jquery`s jQuery.parseJSON function to parse the JSON string but still getting the parse error when there is a single quote in the data that is prepared with json_encode.
Could it be a mistake in my implementation that looks like this (PHP - server side):
$data = array();
$elem = array();
$elem['name'] = 'Erik';
$elem['position'] = 'PHP Programmer';
$data[] = json_encode($elem);
$elem = array();
$elem['name'] = 'Carl';
$elem['position'] = 'C Programmer';
$data[] = json_encode($elem);
$jsonString = "[" . implode(", ", $data) . "]";
The final step is that I store the JSON encoded string into an JS variable:
<script type="text/javascript">
employees = jQuery.parseJSON('<?=$marker; ?>');
</script>
If I use "" instead of '' it still throws an error.
SOLUTION:
The only thing that worked for me was to use bitmask JSON_HEX_APOS to convert the single quotes like this:
json_encode($tmp, JSON_HEX_APOS);
Is there another way of tackle this issue? Is my code wrong or poorly written?
Thanks
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,"'","''")
Striking a similar issue using CakePHP to output a JavaScript script-block using PHP's native json_encode. $contractorCompanies contains values that have single quotation marks and as explained above and expected json_encode($contractorCompanies) doesn't escape them because its valid JSON.
<?php $this->Html->scriptBlock("var contractorCompanies = jQuery.parseJSON( '".(json_encode($contractorCompanies)."' );"); ?>
By adding addslashes() around the JSON encoded string you then escape the quotation marks allowing Cake / PHP to echo the correct javascript to the browser. JS errors disappear.
<?php $this->Html->scriptBlock("var contractorCompanies = jQuery.parseJSON( '".addslashes(json_encode($contractorCompanies))."' );"); ?>
I was trying to save a JSON object from a XHR request into a HTML5 data-* attribute. I tried many of above solutions with no success.
What I finally end up doing was replacing the single quote ' with it code ' using a regex after the stringify() method call the following way:
var productToString = JSON.stringify(productObject);
var quoteReplaced = productToString.replace(/'/g, "'");
var anchor = '<a data-product=\'' + quoteReplaced + '\' href=\'#\'>' + productObject.name + '</a>';
// Here you can use the "anchor" variable to update your DOM element.
Interesting. How are you generating your JSON on the server end? Are you using a library function (such as json_encode in PHP), or are you building the JSON string by hand?
The only thing that grabs my attention is the escape apostrophe (\'). Seeing as you're using double quotes, as you indeed should, there is no need to escape single quotes. I can't check if that is indeed the cause for your jQuery error, as I haven't updated to version 1.4.1 myself yet.

Categories

Resources