Pass PHP variable to javascript including quotes and javascript
Get the solution ↓↓↓This question has been asked a few times, and the answer seems to be to usejson_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
andx-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 asjsVariable
:
<script>
function test() {
return {
jsVariable: ,
anotherVariable: true,
}
}
</script>
Update
If I usejsVariable: <?php echo json_encode($php_variable); ?>,
I get SyntaxError: Unexpected token '&' on that line.
If I usejsVariable: '<?php echo json_encode($php_variable); ?>',
(added single quotes) then the variable is parsed as a string and not as HTML.
Answer
Solution:
Usejson_encode()
:
<script>
function test() {
return {
jsVariable: <?php echo json_encode($php_variable); ?>,
anotherVariable: true,
}
}
</script>
Answer
Solution:
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.
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: videoxxx
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.