Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

script

<script type="text/javascript" >
var myvar = <?= json_encode($str); ?>;
alert(myvar);
</script>

php

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<?
$str = "ABCD";
echo "ENCODING: " . mb_detect_encoding($str) . "\n";
?>

im not good at english sorry.

$str = "ABCD"

i want to send string from php to javascript

var myvar = <?= json_encode($str); ?>;

i use json_encode but when i alert no massage display in alert-box(box happen but no massage there maybe null value)

alert(myvar);

i dont know what happen please help me PS.alert for test string i want to use that string in javascript code

share|improve this question
2  
Try var myvar = '<?= json_encode($str); ?>'; –  dfsq 22 hours ago
1  
are we to assume your php code is in the same file and above your javascript code? –  Sean 22 hours ago
1  
@dfsq: No, if given a string, json_encode puts quotes around it. –  T.J. Crowder 22 hours ago
1  
Are the first two snippets from the same or separate files? If separate, is the "php" snippet included before the "script" snippet? –  Jonathan Lonowski 22 hours ago
    
No, I was wrong, quotes are not needed as json_encode already take care of it. –  dfsq 22 hours ago

2 Answers 2

up vote 0 down vote accepted

There are some issues with your code try to fix those as below :

  • Put the second <script> tag after PHP blocks.
  • Replace <? ?> blocks with <?php ?> or <?= ?>

Like so :

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<?=
 $str = "ABCD";
 echo "ENCODING: " . mb_detect_encoding($str) . "\n";
?>
<script type="text/javascript" >
 var myvar = <?= json_encode($str); ?>;
 alert(myvar);
</script>
share|improve this answer
    
thank you my php under javascript that make my lose 2hr. for fix it T___T –  Tour Avril 14 hours ago
  • Here are 2 flaws in your code
    • syntex to use php is <?php $str = "ABCD"; ?> not <?$str = "ABCD"?>
    • echo "ENCODING: " . mb_detect_encoding($str) . "\n"; is giving error , so it will not run

PHP code :-

<?php 
   $str = "ABCD";
   $message = json_encode($str);
?>

Javacript code:-

<script type="text/javascript" >
var json = <?= json_decode($message); ?>;
var obj = JSON.parse(json);
alert(obj);
</script>
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.