The image below shows a debugging of a function in Chrome DevTools:
I realized that the data returned from the PHP file always has an arrow before the string as seen in the above. What causes this?
This poses a big issue for me. For example when comparing the string. Whenever I use
if(data == "success")
the statement in that block won't run because it would be false. The code I use in the PHP file is:
echo 'success';
That value is coming from the server. You need to fix the the code there so that it generates the correct response. It's likely you have some line breaks at the beginning of the PHP file you're calling which should be removed.
That said, you can trim whitespace from the response in JS:
if (data.trim() == 'success')
I would also suggest you amend your server code so that you return something other than plain text, because, as you've seen, text can easily be affected by whitespace.
Try returning JSON instead. You can then use a boolean flag in the response and avoid the rather ugly comparison to an arbitrary string.
Use trim() function
if (data.trim() === 'success')
Side note: Make habit of using === where possible
from API side, if accessible then check your return value
Instead of returning a string you may want to return a JSON object.
That will help you because like Rory said you can use booleans and also return multiple variables to your page. Accessing a JSON object with JS is easy.
In order to do that simply create a PHP array, add the data you want in it. Then when you want to return the array use json_encode() to return a JSON representation of your array.
PHP code (AJAX target file)
$return = array(
'status' => true
);
echo json_encode($return);
JS (callback function)
if(response.status) {
console.log('success')
}
Related
I've been searching around for security concerns about using PHP json_encode inside javascript context but I'm not exactly satisfied with the results
I got a lot of warnings about doing this but they always assume that I was going to inject data from the json_encode object directly to HTML without any type of sanitizing at all
So, I want to know if this and only this little snippet presents any security issues (like xss attacks etc)
<?php
$obj = isset($_POST['js']) ? json_encode($_POST['js']) : false;
if ($obj === false) $obj = '{}';
?>
<script>var x = <?php echo $obj ?>;</script>
EDIT:
Changed the snippet to handle json_encode returning false
With that line of code
var x = <?php echo $obj ?>;
...the server application echoes back the data that was submitted to it via the "js" key. It will be client that sent it that will receive it, so if in some way it is malicious, it will be that same client dealing with the consequences.
The actual sending to the server is in fact the irrelevant part of the chain: if one has the data to submit, one can also assign it to the variable x directly without the server's interference (e.g. through browser's dev tools).
It would be a different story if in PHP you would use the data to manipulate a server database, call a service, or otherwise change the application's state, and you would not first validate that data.
As to the use of json_encode: if indeed you verify that the argument is valid JSON (by checking that the return value is not false), it will produce a valid JavaScript object literal. The known cases of incompatibility (characters U+2028 and U+2029) will not occur, as by default json_encode escapes these characters.
It is correct as per coding. However you have to validate the variable x should not be empty or the posted value.
<script>var x = "<?php if(isset($_POST['js']))
{
echo json_encode($_POST["js"]);
}";
</script>
Sometimes json_encode returns false, if return it that js expression will broke. this will works safer.
<script>var x = JSON.parse(<?php echo (json_encode($_POST["js"]) ? json_encode($_POST["js"]) : '{}'));</script>
if json_encode returns false, var x will get just empty object.
I'm fetching JSON code stored in MySQL and it has extra slashes, which I have to remove in order to parse it in JavaScript, after I print it on the page. Right now I'm doing the following:
$save = str_replace("\n", "<br>", $save); // Replace new line characters with <br>
$save = str_replace('\\"', '"', $save); // top-level JSON
$save = str_replace('\\\\"', '\"', $save); // HTML inside top level JSON
$save = str_replace('\\\\\\\\\\"', '\\\\\"', $save); // HTML inside second level JSON
Here is an example JSON code, as it comes out from MySQL:
{\"id\":2335,\"editor\":{\"selected_shape\":\"spot-7488\"},\"general\":{\"name\":\"HTML Test\",\"shortcode\":\"html-test\",\"width\":1280,\"height\":776},\"spots\":[{\"id\":\"spot-7488\",\"x\":9.9,\"y\":22.6,\"default_style\":{\"use_icon\":1},\"tooltip_content\":{\"content_type\":\"content-builder\",\"plain_text\":\"<p class=\\\"test\\\">Test</p>\",\"squares_json\":\"{\\\"containers\\\":[{\\\"id\\\":\\\"sq-container-293021\\\",\\\"settings\\\":{\\\"elements\\\":[{\\\"settings\\\":{\\\"name\\\":\\\"Paragraph\\\",\\\"iconClass\\\":\\\"fa fa-paragraph\\\"},\\\"options\\\":{\\\"text\\\":{\\\"text\\\":\\\"<p class=\\\\\\\"test\\\\\\\">Test</p>\\\"}}}]}}]}\"}}]}
And here is how it's supposed to look in order to get parsed correctly (using jsonlint.com to test):
{"id":2335,"editor":{"selected_shape":"spot-7488"},"general":{"name":"HTML Test","shortcode":"html-test","width":1280,"height":776},"spots":[{"id":"spot-7488","x":9.9,"y":22.6,"default_style":{"use_icon":1},"tooltip_content":{"content_type":"content-builder","plain_text":"<p class=\"test\">Test</p>","squares_json":"{\"containers\":[{\"id\":\"sq-container-293021\",\"settings\":{\"elements\":[{\"settings\":{\"name\":\"Paragraph\",\"iconClass\":\"fa fa-paragraph\"},\"options\":{\"text\":{\"text\":\"<p class=\\\"test\\\">Test</p>\"}}}]}}]}"}}]}
Please note that I have HTML code inside JSON, which is inside another JSON and this is where it gets a bit messy.
My question - is there a function or library for PHP (for JS will work too) which covers all those corner cases, because I'm sure someone will find a way to break the script.
Thanks!
The short answer, which is woefully inadequate, is for you to use stripslashes. The reason this answer is not adequate is that your JSON string might have been escaped or had addslashes called on it multiple times and you would have to call stripslashes precisely once for each time this had happened.
The proper solution is to find out where the slashes are being added and either a) avoid adding the slashes or b) understand why the slashes are there and respond accordingly. I strongly believe that the process that creates that broken JSON is where the problem lies.
Slashes are typically added in PHP in a few cases:
magic_quotes are turned on. This is an old PHP feature which has been removed. The basic idea is that PHP used to auto-escape quotes in incoming requests to let you just cram incoming strings into a db. Guess what? NOT SAFE.
add_slashes has been called. Why call this? Some folks use it as an incorrect means of escaping data before sticking stuff in a db. Others use it to keep HTML from breaking when echoing variables out (htmlspecialchars should probably be used instead). It can also come in handy in a variety of other meta situations when you are defining code in a string.
When escaping data input. The most common escaping function is mysqli_real_escape_string. It's very important to escape values before inserting them in a db to prevent sql injection and other exploits but you should never escape things twice.
So there's a possibility that your code is double-escaping things or that addslashes is getting called or something like magic_quotes is causing the problem, but I suspect it is another problem: some JS code might be supplying this JSON not as a proper JSON string, but one that has been escaped so to define a string within javascript.
If you take your example JSON string above, and slap some quotes around it:
var myJSON = "<put your string here>";
then SURPRISE your javascript is not broken and the var myJSON contains a string that is actually valid JSON and can be parsed into an a valid JSON object:
var myJSON = "{\"id\":2335,\"editor\":{\"selected_shape\":\"spot-7488\"},\"general\":{\"name\":\"HTML Test\",\"shortcode\":\"html-test\",\"width\":1280,\"height\":776},\"spots\":[{\"id\":\"spot-7488\",\"x\":9.9,\"y\":22.6,\"default_style\":{\"use_icon\":1},\"tooltip_content\":{\"content_type\":\"content-builder\",\"plain_text\":\"<p class=\\\"test\\\">Test</p>\",\"squares_json\":\"{\\\"containers\\\":[{\\\"id\\\":\\\"sq-container-293021\\\",\\\"settings\\\":{\\\"elements\\\":[{\\\"settings\\\":{\\\"name\\\":\\\"Paragraph\\\",\\\"iconClass\\\":\\\"fa fa-paragraph\\\"},\\\"options\\\":{\\\"text\\\":{\\\"text\\\":\\\"<p class=\\\\\\\"test\\\\\\\">Test</p>\\\"}}}]}}]}\"}}]}";
console.log(JSON.parse(myJSON)); // this is an actual object
The key here is to examine the point of entry where this JSON arrives in your system. I suspect some AJAX request has created some object and rather than sending valid JSON Of that object, it is sending instead an escaped string of a JSON object.
EDIT:
Here's a simple example of what happens when you have too many encodings. Try running this JS in your browser and observe the console output:
var myObj = {"key":"here is my value"};
console.log(myObj);
var myJSON = JSON.stringify(myObj);
console.log(myJSON);
var doubleEncoded = JSON.stringify(myJSON);
console.log(doubleEncoded);
I am using jquery CSV library (https://github.com/evanplaice/jquery-csv/) , to parse and convert a CSV file into an array of objects. This is my code
this.parsedData = $.csv.toObjects(data);
if (this.parsedData.length === 0) {
**console.log('In valid'); /**/ This gets printed
} else {
console.log('valid')
}
My CSV file is this:
""__stream_code","project_code","process","due_date","root_table"
"DASH_PLAY_001","DEV","Plate",2013-02-02,"stream"
"DASH_PLAY_001","DEV","DepthAssess",2013-02-03,"stream""
Now, if I remove quotes, it works fine, but with quotes it doesn't.
Most of the time, my application is going to handle CSV with values in quotes.
Is there any way to fix it?
Try with http://papaparse.com/; you can parse it online and it works great.
All you have to do is call through var results = $.parse(csvString);
and it will return the JSON object for you.
Why is it wrapped in quotes?
I've tested it without the outer quotes on the Basic Usage demo and it seems to parse the data just fine. Are you using at least version 0.71?
This:
""__stream_code","project_code","process","due_date","root_table"
"DASH_PLAY_001","DEV","Plate",2013-02-02,"stream"
"DASH_PLAY_001","DEV","DepthAssess",2013-02-03,"stream""
Double-double quotes cancel each out (as per the spec) so this'll error when it tries to parse the first value.
Should be:
"__stream_code","project_code","process","due_date","root_table"
"DASH_PLAY_001","DEV","Plate",2013-02-02,"stream"
"DASH_PLAY_001","DEV","DepthAssess",2013-02-03,"stream"
If jquery-csv encounters an error during parsing it should log an error to the console indicating the row:column where the error occurred. Is there an error in the console. If not what does console.log(data) output?
As for the data being a mix of quoted/unquoted, the parser shouldn't have any issues consuming it. The data (sans outer quotes) looks perfectly valid.
BTW, I'm not trying to shed blame. If there is something else here that isn't in the code sample you provided that exposes a bug in the parser, I'd like to identify and fix it.
Disclaimer: I'm the author of jquery-csv
I am looking to create an HTML version of a JSON, through JavaScript(jQuery), specifically the unofficial Google Dictionary JSON (http://googlesystem.blogspot.com/2009/12/on-googles-unofficial-dictionary-api.html).
The problem I am facing is that the JSON is not readable because it has this in front of it "dict_api.callbacks.id100(" and is trailed by ",200,null)".
How can I remove this and then put it into a JSON object such that I can attach the elements to the HTML. Thanks in advance.
This is a JSONP response.
It calls a function specified by the callback parameter to give you the response.
You should create a global function to handle the response, and pass its name as the callback.
jQuery will do this for you:
$.getJSON(
"http://www.google.com/dictionary/json?q=test&sl=en&tl=en&restrict=pr%2Cde&client=te&callback=?",
function(response) {
alert(response);
}
)
One thing you can do is write a regular expression (or a pair of them) to do something like:
string.replace(/Regular expression that matches start/, "")
string.replace(/Regulat expression that matches the finish/, "")
Be careful not to use greedy regular expressions if you go this route, I have seen entertaining-but-not-very-helpful results with greed exressions in cases like this.
Otherwise, I would definitely go with the other response by SLaks related to using JQuery, as it should also give you additonal abilities to work with the data later, should your need change after the fact.
I'm trying to develop a web application using jQuery, AJAX and JSON.
I have this code:
console.log(response.s);
if (response.s == true) {
alert('good');
} else {
alert('bad');
}
This response (via console.log() on Firebug) seems to be:
{"s":true}
Which seems to be a JSON object right?
Well, the line console.log(response.s); on the first code I added here returns undefined. What's the problem?
What is typeof (response)? if it's a string then you have to parse it, first. (You'd be accessing the s field of a string, which doesn't exist, so JavaScript gives you undefined instead of throwing an Exception or whatever.)
If the content-type of the response isn't application/json then the javascript is probably assuming that it is just a string.
Supplying the correct content header should therefore sort your problem.
Alternatively you could probably use eval() to convert the string into a json object.
try to use:
var obj = jQuery.parseJSON(response);
console.log(obj.s);
Hope it helps.