Passing data from PHP to JS faulty

Hi guys,
following code should assign php data to JavaScript. In principal, i will get data, as required, but output also contents **<?php echo** at beginnig and ;?> at the end. How to avoid this vexation?

<?php
$data = Kopf::findOne(['id' => Yii::$app->user->identity->id])->data;
$ersetzenMitName = User::findOne(['id' => Yii::$app->user->identity->id])->username;
$ersetzenMitMail = User::findOne(['id' => Yii::$app->user->identity->id])->email;
$ersetzenMitTelefon = User::findOne(['id' => Yii::$app->user->identity->id])->telefon;
$replaceMaklerName = str_replace('****', $ersetzenMitName, $data);
$replaceMaklerName = str_replace('++++', $ersetzenMitTelefon, $replaceMaklerName);
$replaceMaklerName = str_replace('::::', $ersetzenMitMail, $replaceMaklerName);
$finalOutput = preg_replace("#[\r\n]#", '', $replaceMaklerName);
$script = <<< JS
    $('#bez').change(function(){
        var finalData = '<?php echo $finalOutput; ?>'; 
        var textId=$(this).val();
        $.get('kopf/baustein',{textId:textId},function(data){
            var result = data.replace(data, finalData);
            $('#IDText').val(result);      
        });
    });
JS;
$this->registerJS($script);
?>

Although, I still don’t know this attitude, I gonna solving it using substring() of JavaScript, for instance like this:

$script = <<< JS
    $('#bez').change(function(){
        var finalData = '<?php echo $finalOutput; ?>'; 
        var textId=$(this).val();
        $.get('kopf/baustein',{textId:textId},function(data){
            var result = data.replace(data, finalData);
            result=result.substring(11);
            result=result.substr(0, result.length-5);
            $('#IDText').val(result);      
        });
    });
JS;
$this->registerJS($script);
?>

You are using Heredoc here and it behaves like string wrapped in double quotes (as opposed to Nowdoc) so you can just use PHP variable as is.

$script = <<<JS
// ...
var finalData = "$finalOutput"; 
// ...
JS
1 Like

Oh, thx a lot for this hint. Didn’t know that so far and will use it instead of substr().
This thread can be closed as succesfully solved!