Timo
Timo

Reputation: 138

Pass Data from Controller to JavaScript

I want to pass data from my Controller to a JavaScript that handles a Google Bar Chart.

composer

$tmp = 6;
return view('pages.template', ['tmp' => $tmp]);

from my template.blade.php I call the Google Chart

<div id="chart_div"></div>

.js file:

var tmp = 6;
var tmp2 = parseInt('{!! $tmp !!}');

var data = google.visualization.arrayToDataTable([
    ['comment1', 'comment2'],
    ["- 6 days", tmp],
    ["- 5 days", tmp2],
    ["- 4 days", 31],
    ["- 3 days", 12],
    ["- 2 days", 10],
    ["- 1 day", 3],
    ["today", 4]

the 2nd bar from Google-Bar-Chart is blank .... enter image description here

But there should be displayed my variable.

How do I solve this issue?

Upvotes: 4

Views: 8054

Answers (4)

Nemo
Nemo

Reputation: 513

This worked for me

<script type="text/javascript">

var tmp = {!! json_encode($tmp->toArray()) !!};
console.log(tmp);

</script>

In Your controller, you could do the following

public function index()

{

$tmp = Tmp::get();

return view('tmp.index', compact('tmp'));

}

Upvotes: 0

Zakaria Acharki
Zakaria Acharki

Reputation: 67505

Just replace :

var tmp2 = parseInt('{!! $tmp !!}');

By :

var tmp2 = parseInt(<?php echo $tmp; ?>);

And it should work.

Upvotes: 2

Eddy
Eddy

Reputation: 3723

The variable $tmp seems not be parsed successfully in .js file. why not you put the code in .js file into template.blade.php?

Upvotes: -1

jedrzej.kurylo
jedrzej.kurylo

Reputation: 40899

You are trying to use Blade syntax in your JS file. In order for that to work, this file would need to be processed by Blade compiler. It means that instead of including JS file in your website directly, you need to include a URL that will be processed by Laravel and output Javascript code. It is possible, but it's usually a bad option. Instead of fetching a light JS file directly from the server, additional request will need to be processed by Laravel.

What you need to do is:

  1. Put your Javascript in a Blade template
  2. Create a controller action that will

    class JavascriptController extends Controller {
      public function javascript() {
        $tmp = 6;
        return view('javascript', ['tmp' => $tmp]);
      }
    }
    
  3. Add a route to that action in your routes.php

    Route::get('/javascript', 'JavascriptController@javascript');
    
  4. Instead of including the original Javascript file include a URL that will execute this controller action

    <script src="{{route(javascript)}}"></script>
    

Upvotes: 0

Related Questions