Whats the best way to do this?
I have this $_SESSION["sessionOpentok"] I need to set to this java script var var session_id
Security isn't an issue, its okay for the end user to be able to see this session id.
I have heard of AJAX calls, json encode, delimiters, php echo, php print.
None seems to work. echo and print do not work due to quote being in the session variable.
JSON encode encodes this the number to a null.
Any ideas. Thanks
In theory, just var session_id = <?php echo json_encode($_SESSION['sessionOpentok']); ?>; should do it.
However, you mayhave an encoding problem if you're getting null. Try:
var session_id = <?php echo json_encode(utf8_encode($_SESSION['sessionOpentok'])); ?>;
Escape the string before echoing it:
var session_id = '<?php echo addslashes($_SESSION["sessionOpentok"]) ?>';
This might not work depending on how you plan to use the session_id variable as the strings won't match.
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'm trying to pass a PHP variable to Javascript like this..
var url = <?php echo $urlArray[0]; ?>;
The contents of $urlArray[0] is a string from a json decoded array
"baby"
When I run the code I get the error..
Uncaught ReferenceError: baby is not defined
var url = "<?php echo $urlArray[0]; ?>";
you forgot the quotes.
If you need to export more complicated data structure, you may need json_encode. This might be helpful if exporting arrays and/or objects.
json_encode is your friend - use to wrap anything you're trying to pass to javascript.
http://php.net/manual/en/function.json-encode.php
var url = <?php echo json_encode($urlArray[0]); ?>;
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
I have several situations where I need to pass multi-dimensional PHP arrays into Javascript/jQuery. The PHP function json_encode() seems to do this rather well. I've seen some examples that use $.parseJSON, but I'm not sure if this is for IE6 compatibility or some other issue. Can anyone elaborate if this is the correct format to use in JavaScript. Assume this is javascript/jQuery as part of a PHP view.
var sections = <?php echo json_encode($sections); ?>;
Or, perhaps this would be better?
var sections = <?php if (!empty($sections)) { echo json_encode($sections); } else { echo "new Array()"; } ?>;
Or, do I need $.parseJSON? It seems to throw an error.
var sections = $.parseJSON(<?php echo json_encode($sections); ?>);
Does anyone know of any IE6 issues I should be aware of? If I should use parseJSON(), is it used with single or double quotes?
Thanks in advance,
Jeff Walters
I don't know anything about IE, but as long as you aren't dealing with JSON strings in JavaScript you will not need any parseJSON function. Just putting them out into the script text should be fine.
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]); ?>