$_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"]")
Related
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.
In my php code, I have
<?php
$test = json_encode($array);//$array is a valid multidimensional array
?>
I am passing this variable to a javascript function and I am trying to set this variable to javascript.
<script>
var test = "<?php echo $test;?>";
</script>
(To clarify I am using codeigniter framework and for simplicity I did not use how I am sending the variable to the page)
But when I execute the above code, I am getting
Uncaught SyntaxError: Unexpected identifier
I have checked all my syntax.
Thank you in advance.
Don't put the decoded json array inside double quotes in the javascript. Change to this.
var test = <?php echo $test;?>;
It's not required to wrap the output of json_encode in quotes, otherwise it will be interpreted as a string. At which point you'll need to decode it within JavaScript.
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.
I have a txt file on the server which contains 10 lines of text. The text file is rewritten sometimes, and I get new lines using "\r\n". My problem shows when I want to load the lines in javascript variables. I do it like this, but this work only for numbers or for the last line of the file, because its not using the breakline tag: var x = '<?php echo $file[0]; ?>';
Ive tried to alert(x) but it`s not working.... (working only if I read the last line)
Any idead ?
I'm not sure I completely understand the question, but you should be able to use json_encode() which will escape the data appropriately:
var x = <?php echo json_encode($file[0], JSON_HEX_TAG); ?>;
As others have said, you can trim() the data to remove trailing whitespace/line breaks. You should still use json_encode() in addition to this as otherwise it will still be possible to break out of the javascript string (e.g. by sending a string with a quote in).
You want trim():
var x = '<?php echo trim($file[0]); ?>';
But if you read the file(), you could array_map() it with trim() and then keep doing what you're doing:
$values = array_map("trim", file('input-file.txt'));
You might consider what happens if someone decides to include a single quote in the variable with this approach.
EDIT: Then you can add json_encode() as suggested in other answers:
var x = <?php echo json_encode($file[0]); ?>;
Thanks for all! The I solved the problem with the help of artlung and Richard JP Le Guen:
var x = <?php rtrim($file[0]); ?>