This question has been asked a few times, and the answer seems to be to use json_encode but this is not working as my string contains a few more things than quotes.
This is the PHP string:
<img src="test.jpg" :class="{ 'add-class': comment == 1, 'another-class': comment == 2 }" x-on:click="submit()">
The :class and x-on: are AlpineJS attributes in case you were wondering (check it out, it's really cool!).
This PHP string is dynamically generated and I would like to pass it to a javascript variable, shown here as jsVariable:
<script>
function test() {
return {
jsVariable: ,
anotherVariable: true,
}
}
</script>
Update
If I use jsVariable: <?php echo json_encode($php_variable); ?>, I get SyntaxError: Unexpected token '&' on that line.
If I use jsVariable: '<?php echo json_encode($php_variable); ?>', (added single quotes) then the variable is parsed as a string and not as HTML.
Use json_encode():
<script>
function test() {
return {
jsVariable: <?php echo json_encode($php_variable); ?>,
anotherVariable: true,
}
}
</script>
If you just use ASCII coding, you may give base64 encoding a try.
PHP encode the string into base64, and Javascript to decode, like this:
<script>
function test(){
var str = '<?php echo base64_encode($str);?>';
return {
jsVariable: atob(str),
anotherVariable: true
}
}
alert(test().jsVariable)
</script>
Hope this helps.
Related
I was wandering if it is possible to send a php object/array from a database into a javascript function through html?
Here is what I am trying to accomplish:
<?php
$test = array('Apple', 'Banana', 'Lemon');
?>
Send object
<script type="text/javascript">
function myfuntion(test)
{
console.log("What is first fruit: "+test[0]);
}
</script>
I get this error in my console:
Uncaught SyntaxError: Unexpected end of input
myfuntion([
What am I missing? Hoping for help and thanks in advance :-)
It is because string generated by json_encode contains double quotes and conflict with onclick="..."
Try to wrap it with htmlspecialchars
Send object
To avoid quotes collision just store your json as an object somewhere:
<?php
$test = array('Apple', 'Banana', 'Lemon');
?>
Send object
<script type="text/javascript">
var data = <?php echo json_encode($test) ?>;
function myfuntion()
{
console.log("What is first fruit: "+data[0]);
}
</script>
Or using an argument:
<?php
$test = array('Apple', 'Banana', 'Lemon');
?>
<script type="text/javascript">
var data = <?php echo json_encode($test) ?>;
</script>
Send object
<script type="text/javascript">
function myfuntion(jsonObj)
{
console.log("What is first fruit: "+jsonObj[0]);
}
</script>
Instead of pass in function direct use $test array json in js like this.
<?php
$test = array('Apple', 'Banana', 'Lemon');
?>
Send object
<script type="text/javascript">
function myfuntion()
{
var test = <?php echo json_encode($test); ?>;
for(var i=0; i<test.length; i++){
console.log("What is first fruit: "+test[i]);
}
}
</script>
If you pass in a tag then it passes a string instead of json.
Hope this is helpful to you.
You are missing parentheses for PHP code inside myfuntion.
Send object
You are doing correct only thing missing is, you need to surround passed argument in parentheses as below.
<a href="javascript:;"
onclick="myfuntion('<?php echo json_encode($test) ?>');">Send object</a>
Because your code will echo json encoded values/string in argument (and string must be inside single of double quotes) and function arguments must needs to be surrounded in parentheses. But if it is number then it will work but when you are dealing with objects and array you must need to enclose them in ''.
And in your js code just parse that argument to JSON using JSON.parse method.
When I load a php page, i put within a javascript function, a name. The problem comes when this string has special chars like '.
Here I paste the code of a click event:
showSocialShare(event, '<?php echo $object->slug; ?>', '<?php echo htmlspecialchars($object->title); ?>', '<?php echo $object->image; ?>')
I thought that the function htmlspecialchars code somehow the string but the result is:
showSocialShare(event, '4049269', 'collection-'Noun'', '/img/Original.jpg')
As can be seen, at the second parameter, the name contains characters like ' and arises an error.
How can I avoid this?
Never output text from PHP directly into a Javascript context. As you're finding out, it's VERY easy to generate JS syntax errors.
Always use json_encode: e.g. given this
<?php $foo = 'bar'; ?>
<script>
var badly_broken = <?php echo $foo ?>;
var working_fine = <?php echo json_encode($foo); ?>;
</script>
You'll end up with
<script>
var badly_broken = bar; // oops - undefined variable "bar"
var working_fine = "bar";
</script>
And note that if you're outputting JS into an HTML attribute, you not only have to generate valid Javascript, you have to output valid HTML AS WELL:
<?php $foo = array('bar' => 'baz'); ?>
<a onclick="brokenCall(<?echo json_encode($foo) ?>)">
<a onclick="workinCall(<? echo htmlspecialchars(json_encode($foo)) ?>)">
produces:
<a onclick="brokenCall({"bar":"baz"})">
^--start attribute
^--end attribute - ruhroh
<a onclick="workingCall({"bar":"baz"}")>
I am trying to load some select options by using a few JS functions. I want to have one option selected by default if it is equal to a PHP variable defined before.
I receive an error:
Unexpected token
and I am sure I am doing something wrong with the syntax:
This is a section of my JS functions:
for(var i = 0; i < categories.length; i++){
select.options[i] = new Option(categories[i].val,categories[i].id);
if (select.options[i].text== <?php echo '$categoriesSelect'; ?>)
{
select.options[i].selected=true;
}
}
The variable $categoriesSelect is defined before the JS. Thank you!
You need to quote your strings.
Change (from your comment):
if (select.options[i]== <?php echo "json_encode($categoriesSelect)"; ?>)
to:
if (select.options[i].text == "<?php echo $categoriesSelect; ?>")
This will validate against the text for the option. Change .text to .value to validate against value for the option.
...also removed json_encode() since the variable only contains a string.
You need to remove quotes around php function:
From
if (select.options[i].text== <?php echo '$categoriesSelect'; ?>)
To
if (select.options[i].text== '<?php echo $categoriesSelect; ?>')
I have got the most biggest problem, I have see.
piece of code (just and example, the main example use database querys):
<?php $var1="999"?>
<script>
bigvar= <?php echo json_encode($var1); ?>;
var lolo = {
big: 2
}
lolo.big=bigvar;
alert(lolo.big);
</script>
Problem:
It does not recognize the PHP variable (it doesn't change to 999 value), and passing php value to javascript variable, doesn't work.How can help me ?.It is a big issue.
you should add quotes while assigning value from php variable to javascript, like as follows
<script>
bigvar= "<?php echo json_encode($var1); ?>"
var lolo = {
big: 2
}
lolo.big=bigvar;
alert(lolo.big);
</script>
and its </script>, not </scripts>
<script>
var bigvar= "<?php echo($var1); ?>"
var lolo = {
"big": "2"
}
lolo.big=bigvar;
alert(lolo.big);
</scripts>
The above example works fine for me..Try it
You have to add quotes around your php, so your JS know that this value is a string.
bigvar = "<?php echo json_encode($var1); ?>";
I had an onclick event as below.
<div onclick="display_function('<?php echo $user_id;?>','<?php echo $student_id;?>','<?php echo $student_name;?>')"></div>
function display_function(user_id,student_id,student_name)
{
alert(user_id+'-'+student_id+'-'+student_name); //<-- testing only. I have my own code here
}
the function works fine with the name like Mary, Chris and etc.
However, if the student name contains a ', e.g. Cheng'li, the function won't work.
I need help to fix this. How can I make the function works by 'escaping' the quote mark in name?
Thanks.
You need to add a call to htmlentities around the data you wish to echo.
Not doing so exposes your code to XSS attacks.
use PHP function addslashes
<?php
$str = "Is your name O'reilly?";
// Outputs: Is your name O\'reilly?
echo addslashes($str);
?>
IN your case
<?php echo addslashes($student_name);?>
REFERENCE
http://www.php.net/addslashes
Note: If your code contain html tag than use htmlentities (Entoarox Answer)
you can either use escape()
<div onclick="display_function(escape('<?php echo $user_id;?>'),escape('<?php echo $student_id;?>'),escape('<?php echo $student_name;?>'))"></div>
function display_function(user_id,student_id,student_name)
{
alert(user_id+'-'+student_id+'-'+student_name); //<-- testing only. I have my own code here
}
That is because you are passing the values in function in single quotes. When name will have a single quote, this will cause error.
try double quotes like
<div onclick="display_function(\"<?php echo $user_id;?>\",\"<?php echo $student_id;?>\",\"<?php echo $student_name;?>\")"></div>
Just add \ before ' to tell your script that it is a string. I hope it helps
<?php
$user_id = 1;
$student_id = 1;
$student_name = "Cheng\'li";
?>
<div onclick="display_function('<?php echo $user_id;?>','<?php echo $student_id;?>','<?php echo $student_name;?>')">Click</div>
<script>
function display_function(user_id,student_id,student_name)
{
alert(user_id+'-'+student_id+'-'+student_name); //<-- testing only. I have my own code here
}
</script>
If you cannot put \ directly in String, you need to use [addslashes][1]
<script>
function display_function(user_id,student_id,student_name)
{
alert(user_id+'-'+student_id+'-'+addslashes(student_name)); //<-- testing only. I have my own code here
}
</script>