Here's the situation:
My program accepts input entered by users into a form and saves it in a MYSQL database using PHP's PDO with Prepared Statements.
The data is retrieved via an AJAX call and encoded to JSON using json_encode, like so:
echo "<script> var jsonData = '". json_encode($profileData) . "';</script>";
Then parsed using JQuery:
var Profile = jQuery.parseJSON(jsonData);
This works fine, until a user enters a ' char.
i.e. If a user enters the word
I'm
It would be escaped and stored in the DB like this: I\'m
Once retrieved from the DB, a JSON encoded string would look like this:
<script> var jsonData = '{"fname":"Daniel","about":"i\\'m a nerd"}';</script>
Although the ' is escaped, it seems to break the JSON.
I have seen people posting find/replace style work-arounds, but I would prefer to avoid this approach.
Surely there is some method that handles this, or am I initializing the JSON Object incorrectly somehow?
Any help much appreciated, any more info required just ask :)
The simplest way to solve the problem would be to omit the quotes in JS:
echo "<script> var jsonData = " . json_encode($profileData) . ";</script>";
which will result in
<script> var jsonData = {"fname":"Daniel","about":"i\\'m a nerd"};</script>
Then jsonData will already be an object and doesn't have to be parsed. Though the escaping might be a bit off then.
Once retrieved from the DB, a JSON encoded string would look like this:
<script> var jsonData = '{"fname":"Daniel","about":"i\\'m a nerd"}';</script>
Although the ' is escaped, it seems to break the JSON.
Note that JSON is here concerned about escaping the backslash. Thus, the quote is not escaped - you still have to do it so as not to mess up the quotes you put around it.
echo "<script> var jsonData = '". json_encode($profileData).replace(/'/g, "\\'" . "';</script>";
Use the JSON_HEX_APOS parameter when you are encoding the JSON
json_encode($profileData, JSON_HEX_APOS);
This will turn the single quote into a special escape value that only JSON understands
Related
$_SESSION['consequnce1']=[1,2,3]
$consequenceStr1=implode( ',', $_SESSION['consequence1']); //for storage to databases
$_SESSION['consequence1']=explode(',', $consequence1);
//$_SESSION['consequence1'] now is like["1","2","3"].
in html, I want get the array[1,2,3].
var sess = JSON.parse("<?php echo json_encode($_SESSION['consequence1']); ?>");
var num =sess[0];
but this two line code does not work, what's the problem?
thanks
Answer: do not know the reason in fact. But just change
var sess = <?php echo json_encode($_SESSION['consequence1']); ?>;
then it works.
Thanks for others' reply
That is, because json_encode provides value that can be used directly in JavaScript. It wraps strings in double quotes and takes care of other types to be valid as well. JSON.parse takes string as an argument, which is not necessary.
In your example, you had messed double quotes, like this:
JSON.parse("["1","2","3"]")
I have a form with fields and a text-area that allows any characters to be entered. I can't just submit the form, because the form is being recycled many times over, so the form values are being stored in associative arrays:
<form name='Theform'>
<input type="text" id="VISITOR_DETAILS_NAME" value="Joe">
<input type="text" id="VISITOR_DETAILS_SIZE" value="Large">
<textarea id='VISITOR_DETAILS_INFO'>
User can enter anything here including double " and single ' quotes
</textarea>
<input type="hidden" name="package" id="package" value="" />
</form>
The text-area value are stored in a JavaScript array along with the other form values:
myArray[0]['VISITOR_DETAILS_NAME'] = document.getElementById('VISITOR_DETAILS_NAME').value;
myArray[0]['VISITOR_DETAILS_SIZE'] = document.getElementById('VISITOR_DETAILS_SIZE').value;
myArray[0]['VISITOR_DETAILS_INFO'] = document.getElementById('VISITOR_DETAILS_INFO').value;
I end up with an array something like this:
{
VISITOR_DETAILS_NAME : "Joe",
VISITOR_DETAILS_SIZE : "Large",
VISITOR_DETAILS_INFO : "User can enter anything here including double " and single ' quotes"
};
I then pass this JavaScript array to the hidden form field using JSON.stringify and then POST this to PHP:
document.getElementById('package').value = JSON.stringify(myArray[0]);
Theform.submit();
(For now I'm just posting to an iframe to test that the JSON is passing the JavaScript arrays properly through POST).
When I get it on the PHP side - it seems good to go. It looks like the JSON.stringify has added the backslash to the double quote (\" ) - and now I want to store the values in MySQL. But I want to first test that I can send/reconstruct the JSON back to the javascript as an array - so I try this:
parent.myArray[0] = JSON.parse('<?php echo $_POST['package']; ?>');
I get an ERROR: SyntaxError: Expected token ')' OR SyntaxError: missing ) after argument list
This is strange to me - because when I try it without POSTING - It seems to work fine like this:
document.getElementById('package').value = JSON.stringify(myArray[0]);
now if I try to just pass back the stringified value back to the array
myArray[0] = JSON.parse(document.getElementById('package').value);
- it seems to work fine - no errors
QUESTIONS:
Why am I getting this error when trying to reconstruct the ARRAY from the
POSTED JSON.stringify() value?
Do I save this JSON.stringify() value in MySQL as is?
Or do I PHP json_decode() it first?
I want to grab the form data - handle it properly - store it in MySQL and then read it back into the form when I need it.
Thanks All :)
parent.myArray[0] = JSON.parse('<?php echo $_POST['package']; ?>');
Here you are are trying to convert a JSON text into an HTML representation of a JavaScript string representation of a JSON text, but you aren't doing anything to escape it for either.
If you have any ' characters in the JSON data, then they will terminate the JavaScript string.
If you have any " characters in the JSON data, then they will be represented as \", but \" is a JavaScript string representation of ". Since you don't do anything to escape the text you put in the JS string, the slash character will be consumed by the JavaScript parser and will be gone before it reached the JSON parser.
If you want to convert data for placing in a JavaScript string then you need to escape it.
However, JSON is a subset (almost) of JavaScript. So the process of converting a JSON text to a JavaScript string so it can be parsed into a JavaScript object is over-complicated. You can skip that can just go straight to:
<script>
var foo = <?php echo $json; ?>
</script>
However, since you are taking in the JSON from the client, echoing out directly will expose you to XSS attacks. In order to deal with this you should filter the data on the server.
This will:
Fail to parse any invalid JSON and so not output bad JSON (but it might output nothing, giving you a JSON syntax error, you should apply tests to see if the parse was successful and output a sensible default case if it fails).
Convert any </script> in the data to <\/script> making it safe to place in a script element (because that is how PHP's json_encode works
Such:
<!-- I don't do PHP, this is untested -->
<script>
var foo = <?php
$unsafe_json = $_POST['package'];
$data_structure = json_parse($unsafe_json);
$safe_json = json_encode($data_structure);
echo $safe_json;
?>;
</script>
Do I save this JSON.stringify() value in MySQL as is? Or do I PHP json_decode() it first?
That depends on what you intend to do with the data. In general when putting things into a database it is a good idea to extra the data from the data format and normalize it. That way you can run queries over it.
If you are only going to store the data and then retrieve it, you might be able to get away with not doing that and storing strings of JSON in the database. That loses you a lot of flexibility though and might bite you in the future.
I'm wondering what would be the best way to decode JSON string inside Javascript code.
I want my json string to be embeded inside my JS, like this:
var params = dojo.fromJson('<?=json_encode($this->params); ?>');
dojo.fromJson decodes my string and json_encode is a php function that encodes an object on the server side.
It seems that json encoder ignores ' chars and only converts " to \". So when one of my variables inside $this->params contains a ' character there is a Javascript error.
For example:
var params = dojo.fromJson('{"id":"11","object_type":"Let's go"}');
What is the best way to approach this ?
Thanks for help.
Since you are producing the JSON yourself, you can trust it, so you don't need to treat it as JSON and can treat it as JS instead.
var params = <?=json_encode($this->params); ?>;
PHP's JSON encoder will escape </script> for you so you don't need to worry about terminating your script element with your data.
I have a javascript variable which hold the value taken from somewhere else(lets say from a API call), taken string is given bellow,
He's the reason for this
I assign this string to a variable name 'sample'. But when I print it, it doesn't work since the string has " ' " character. I want to add " \ " before the " ' " character. I tried using this,
var sample = (get the string from a api call).replace(/'/g,"\\\'");
But it doesn't work?
in my javascript file I use window.location.href = "test.php?detail="+sample; to send the data.
Use encodeURIComponent to escape a string for inserting into a URI.
In my test.php, I use $detail = $_GET["detail"]; and echo $detail; to print it.
If you are printing it into HTML then use htmlspecialcharsto make it safe.
If you are printing it into JavaScript then use json_encode to make it safe.
You're overdoing the escape characters:
var sample = (get the string from a api call).replace(/'/g,"\\'");
Is enough, a single quote, delimited by double quotes needn't be escaped, so just escape one backslash.A sidenote, though: if the string you're checking is a return value, the single quotes shouldn't be a problem (if they are, the api code would break before returning the string). If you really really really want to be extra-super-mega-sure and the string is long:
var sample = (get the string from a api call).split('\'').join('\\\'');
//or (to avoid confusion with all that escaping
var sample = (get the string from a api call).split("'").join("\\'");
Splitting is faster for longer strings (not short strings, as the array constructor is called, an array-object is created, looped,...)
Presumably the problem is with (get the string from a api call). If you have some server-side code (PHP?) like this:
var sample = <?php echo $mystring ?>.replace(…);
…and it produces output sent to the browser like this:
var sample = 'my dad's car'.replace(…);
…then your server-side code has produced syntatically-invalid JavaScript that cannot be fixed by more JavaScript. Instead you need to fix it on the server, something like:
var sample = <?php echo json_encode($mystring); ?>;
It's impossible to help you further without your actual code details, however.
Here's my problem. I have data being returned using JSON, AJAX from my php script to my page. The data is being stored in a variable data
Using the variable data, I'm trying to construct a div using javascript. However, if the data contains a single quote, it break my js code and the page script doesn't work.
example code with data being the variable containing data "The boy's bicycle":
var newrootcomment = $("<div id='container'>" + data + "</div>");
newrootcomment.prependTo($('#wholecontainer')).hide().fadeIn(300).slideDown(1000);
How do I solve this problem?
Are you using the json_encode function available in PHP? Are are you treating the response as JSON? jQuery.parseJSON(<json-string>).
From there you interact with it simple as an object.
var resp = {};
If you don't have jQuery, most browsers support JSON.parseJSON().
Also, make sure you use double quotes for attributes.
<div id="foo"></div>
This is normally how I use json_encode:
$resp = array(
"foo"=>"foo_value",
"bar"=>"bar_value",
"foo_bar"=>array("one","two",3),
"message"=>"AWesome"
)
return json_encode($resp)
Take a look at json_encode for PHP - it'll return a quoted string with JSON-safe characters - it'll escape entities like \n, \, ". etc
Edit
Note that a single quote in JSON is not required to be escaped since it surrounded by double quotes.
From what you said in a comment to #jbcurtin's answer, about your PHP code being echo json_encode('{ "author": "'.$author.'"}'); I'd say that that is one problem. You don't need to encode the entire string, only the author variable. That line should be echo '{"author": '. json_encode($author) . '}'; instead.