4

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?

1
  • Maybe try the response from Brandon "here" only because I think you're trying to use the php variable on a linked .js file which won't work. Commented Aug 13, 2015 at 10:51

4 Answers 4

2

Just replace :

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

By :

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

And it should work.

Sign up to request clarification or add additional context in comments.

Comments

0

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>
    

Comments

0

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'));

}

Comments

-1

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

1 Comment

I don't think shoving javascript into a view file in order to coerce it into working is the best approach.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.