registerJS worng position of script


(Torsten) #1

Hi,
I want to register a JavaScript, where I have to dynamical add parameters. I am using the following code:

Clipboard05

In the console I get the following error:
SyntaxError: expected expression, got ‘<’

Looking at the source code of the web page I found, the the script was added in between another script:

Clipboard04

Can anybody help me with this issue?

Cheers,
Torsten


(Johnson) #2

Hi Torsten,

It looks like the first argument if $id looks like string so when you call the js function argument just use quotes.

$java = '<script type="text/javascript">
drawmap("' . $id . '", ' . $lat . ', '.$lon . ');
</script>';

As well when you ask some queries please do share the full error message and snippet.!! So that the community members can help you faster with good understanding.


(Torsten) #3

Thank you very much. I added the quotes, but this did not fix the problem.
Here is a liitle bit more of my view.php
<?php

use yii\helpers\Html;
use yii\widgets\DetailView;
use kartik\tabs\TabsX;
use kartik\icons\FontAwesomeAsset;

/* @var $this yii\web\View */
/* @var $model frontend\models\EpiMain */

FontAwesomeAsset::register($this);

$this->title = $model->id;
$this->params['breadcrumbs'][] = ['label' => 'Epichloe Database', 'url' => ['index']];
$this->params['breadcrumbs'][] = $this->title;


$id = $model->id;
$lat = $model->latitude_dec;
$lat = strval($lat);
$lon = $model->longitude_dec;
$lon = strval($lon);
$java = '<script type="text/javascript">
		drawmap("' .$id. '", ' .$lat. ', ' .$lon. ');
        </script>;';
$this->registerJs($java);   


\yii\web\YiiAsset::register($this);

The error messege in the console is just what I have written in my first post:

It points to the index file, where the script is still in the wrong place:

<script src="http://www.openstreetmap.org/openlayers/OpenStreetMap.js"></script>
<script src="/js/tom.js"></script>
<script src="/js/cdata_script.js"></script>
<script>jQuery(function ($) {
<script type="text/javascript">
		drawmap("JKI-0013", 51.889151, 10.58899);
        </script>;
jQuery&&jQuery.pjax&&(jQuery.pjax.defaults.maxCacheLength=0);

jQuery("#w6-container").tabsX(tabsX_00000000);

});</script></body>
</html>

(Torsten) #4

I found the problem.
registerJs is adding the <script> and </script> automatically.
The code has to be just this:
$java = ‘drawmap("’ .$jki_id. '", ’ .$lat. ', ’ .$lon. ‘);’;
$this->registerJs($java);

Cheers,
Torsten