I normally find my answers through searches, but this ones got me stumped and I can't find any related articles :/
I am simply running an AJAX call to my PHP script and alerting the returned value (JSON encoded object).
The problem is, the script freezes as soon as it hits my 'echo' statement. I have tested without the echo, and even with values such as "Hello" (both which were successful). I also tested an output with an example JSON string that I found online. This failed.
I am now believing that any string structured as JSON will cause this error (I have tested both JSON scripts on jsonlint.com).
All help is greatly appreciated!!!
Javascript Code:
function scan()
{
var script = "../resources/ajax/fincenmanager/load_reports.php";
var params = "";
var return_function = "load_wire";
document.getElementById("loading_screen").className = "show";
ajax(script, params, return_function);
}
function load_wire(text)
{
document.getElementById("loading_screen").className = "hidden";
alert(text);
}
PHP Code:
<?php
require_once("../../config.php");
require_once("../../library/FincenManager/fincenmanagerclass.php");
header("Content-Type: application/json");
$manager = new FincenManager("../../inputs/FincenManager/");
$json = json_encode($manager);
// Script Breaks After This Line.. 100% Sure :/
echo $json;
?>
You need to ecape a lot more then just the " character (as you discovered).
In this case, the problem is that the " ends the string and JSON is not expecting a character after the " but a ,, ] or an } there.
The answer of this question will help you further with the escaping of the characters: click
And for testing JSON: JSONlint
Well,
I am looking into reasoning but I believe this should be sufficient to help anyone who runs into this problem:
The double quotes in my JSON string (the double quotes created by json_encode when encoding the object) were causing the 'echo' statement to fail. To resolve this I replaced all unescaped double quotes with escaped double quotes using the following:
str_replace( " \" " , " \\\" " , json_encode($object) )
I believe this to be the result of json_encode not escaping the double quotes on its own, and only happens when trying to 'echo' from an external script called from an ajax request.
Thanks Everyone :D
Related
I have a string created by recipeBlob = JSON.stringify(recipeData). It is a long string but here is a sample of it:
"properties":{"Energy":{"val":90.6,"unit":"cal","rdi":"2000"},"Protein":{"val":0.4,"unit":"g","rdi":"50.00000000"},"Fat":{"val":0.6,"unit":"g","rdi":"65.000000000"},"Carbohydrates":{"val":23.3,"unit":"g","rdi":"300.0000000"},"Dietary Fiber":{"val":4.1,"unit":"g","rdi":"25"},"Sugars":{"val":18.8,"unit":"g","rdi":null}
which I send via $.post like this:
$.post('scripts/save_blob.php', {
blob : recipeBlob
});
The $string = $_POST['blob'] that arrives at my PHP script is showing up like this:
{\"properties\":{\"Energy\":{\"val\":90.6,\"unit\":\"cal\",\"rdi\":\"2000\"},\"Protein\":{\"val\":0.4,\"unit\":\"g\",\"rdi\":\"50.00000000\"},\"Fat\":{\"val\":0.6,\"unit\":\"g\",\"rdi\":\"65.000000000\"},\"Carbohydrates\":{\"val\":23.3,\"unit\":\"g\",\"rdi\":\"300.0000000\"}
When I run json_decode($string) it is returning error #4 which is json syntax error.
I don't know at which part of the process the characters are being escaped, which I need to avoid.
#Juhana provided the most direct answer to the question, PHP magic quotes were turned on on the server, thus automatically escaping quotes.
#dfsq provided the solution I actually used, which is to just send the javascript object without stringifying it. it arrives to the PHP script as an array.
I have a data i want to json_decode, the data was json_stringify before being sent to PHP and the data looks like this:
{\"data\":{\"buildingID\":{\"2\":{\"path\":[[11,11],[10,11],[10,10],[9,10],[8,10],[8,9],[8,8],[8,7],[8,6]]}}}}
In my script i have:
echo $_GET['as']; //this is what you see above^
$obj = json_decode($_GET['as']);
echo $obj; //no output
var_dump($obj); //this shows NULL
There are also no errors/notices/warnings in my error logs either.
I'm wondering if the slashes is causing some kind of problem ?
The slashes are indeed the problem.
My guess is that magic quotes are the culprit. I suggest you disable magic quotes.
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.
I wrote a php script that pulls some data from a database and displays it in XML format. For some reason it halts output when it gets to an apostrophe in the data. This is a SELECT statement, and a simple one at that, so I don't understand why there are any issues with apostrophes or quotation marks. I've tried using addslashes() and mysql_real_escape_string(), even though my understanding is that those are for sanitizing data being inserted into the database, and it did not help. I'm stumped. Below is the code and thanks in advance for any advice!
<? if($result = $mysqli->query("SELECT * FROM ".$tbl)){
while($row = $result->fetch_object()){ ?>
<slide>
<id><?= $row->id ?></id>
<title><?= $row->title ?></title>
<chatter><?= $row->description ?></chatter>
<image><?= $row->path ?></image>
<link><?= $row->href ?></link>
<active><?= $row->active ?></active>
</slide>
<? }
}else{
echo $mysqli->error;
}
EDIT:
It turns out I have misunderstood the problem. They are not apostrophes but instead are right single quotes. If I change them to actual apostrophes the script works but I still don't understand why it doesn't simply output them though.
Try with str_replace("'", "\'", $field_to_be_replaced);
You can replace the ' char with a blank space if you prefer, just for testing.
Are you sure it halts on the output of the data, and not when the data is processed? Apostrophe's have special meaning in XML, so if they are included in your XML data you have to replace them with an entity reference. There are 5 predefined entity references in XML, for less than, greater than, ampersand, apostrophe, and one for quotation mark. Alternatively, you can mark the text as CDATA so that the XML parser doesn't try to parse it.
Try making your program output the XML data to a text file instead of to wherever it is going now. Does it still halt on the apostrophe? If not, then it's definitely because of a problem parsing the data. If your program still halts on the apostrophe even when outputting the data only to a text file, there may be a problem somewhere else in the program where that data is processed. Check all the references to the variable containing the data, and see if you can find the exact line the program breaks on.
the apostrophe (') is an invalid character for XML!
You must call $safe_string = str_replace("'","'",$string) in all your fields before
outputting the .XML file.
Check here to learn about these characters and build a more complete str_replace
EDIT:
What im using:
// save ubercart products in XML
function replace_characters_for_xml($str) {
return str_replace(
array("&",">","<","'",'"'),
array("&",">","<","'","""),$str
);
}
...
$row->title = replace_character_for_xml($row->title);
$row->href = replace_character_for_xml($row->href);
...
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.