0

As it is yii2, i cannot refer external file. my index file in view folder code is :

<script type="text/javascript">
  g2 = new Dygraph(
    document.getElementById("graphdiv2"),
    "temperatures.csv", // path to CSV file
    {}          // options
  );
</script>

i need to call my temperatures.csv in the same view folder, i don't know how to give the path, any help?

  • Does this answer your question? [Relative Paths in Javascript in an external file](https://stackoverflow.com/questions/2188218/relative-paths-in-javascript-in-an-external-file) – Solvalou Dec 04 '19 at 06:17
  • No, its a model view and controller method and so we need to define differently, its not common for yii2 we need something different to refer the path. – pavi THRAN Dec 04 '19 at 06:54
  • @paviTHRAN you can try giving ` "" ` in javascript – indra shastri Dec 04 '19 at 06:55
  • @indrashastri Its also not working. – pavi THRAN Dec 04 '19 at 07:06
  • pavi THARAN please check if you want the file path in url or directory path, if url then create a url of the file and give url in comment else try `dirname(dirname(__DIR__))'.'/path/tempratures.csv'` – indra shastri Dec 04 '19 at 07:54

1 Answers1

0

The folder with view templates is not directly accessible in yii2 so there is no way to refer the csv file there from javascript.

The most simple way to deal with it is to put the csv file in the web folder.

For example you can put your csv file to web/data folder. To get the url for the file you can use url helper.

\yii\helpers\Url::to('@web/data/temperatures.csv');

It's better to use the url manager to get the url because it will take care of handling the base url for you, that might be different in different environments. For example final url will probably be /data/temperatures.csv in production but it can be /web/data/temperatures.csv in development.

Another option is to make action that will send the file.

In that case you can leave the temperatures.csv where it is. You need to make a new action in your controller, for example getTemperatures.

public function actionGetTemperatures()
{
    $file = \Yii::getAlias('@app/views/controller/temperatures.csv');
    return \Yii::$app->response->sendFile($file);
}

Then you will use the url of this action in javascript.

\yii\helpers\Url::to(['controller/get-temperatures']);

The advantage of this solution is, that it allows you to control whether the user is allowed to access the file.

Michal Hynčica
  • 5,038
  • 1
  • 12
  • 24