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.
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"]")
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
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
Is it possible to fill jQuery variable by PHP???
I mean something like this:
<?php
$string_php = "50%";
?>
And with "$string" variable I want to fill jQuery:
var jquery_string = "$string_php";
$('.bar1').animate({'height':'jquery_string'},500);
The code above is only idea how I would like to be working
Yes but with php tags <?php ?> (so that php knows its code):
var jquery_string = "<?php echo $string_php;?>";
$('.bar1').animate({'height':jquery_string}, 500); // no quotes for variables
It is possible because PHP (server-side) runs before jQuery (client-side). The page first goes to server and server returns the response (php code is parsed there) to the browser.
Sure
var jquery_string = "<?php echo $string_php;?>";
Since PHP is processed first on the server and the result is then sent to the user's browser, this is easy, and often done.
The above code would result in:
var jquery_string = "50%";
You would, however want to modify your second line, removing the quotes from the variable so it was:
$('.bar1').animate({'height':jquery_string},500);
since keeping the quotes around jquery_string would make force it to be interpreted as a string whereas you want a variable.
The end result would be the equivalent of:
$('.bar1').animate({'height':'50%'},500);
For simple variables, just do as the users said.
F.ex. var jquery_string = "<?php echo $string_php;?>"; (taken from #Blaster's solution).
In other words:
The most simple solution is to output a php variable that we intend to use as string literal via echo anywhere we define the variable.
But: a correct approach would be that everytime we use a serverside variable as a Javascript string, it should be encoded, because the above solutions would fail when double quotes are present. Here json_encode may come handy.
var jquery_string = <?php echo json_encode($var); ?>;
Code example
We want Javascript alert the string "Hey", dude!
$string = "\"Hey\", dude!";
echo "alert(\"" . $string . "\");";
results in:
alert(""Hey", dude!"); <--- will give Javascript error
Instead:
echo "alert(" . json_encode($string) . ");";
results in:
alert("\"Hey\", dude!"); <---- correct JS code
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.