4

I am using Laravel Blade format for my HTML and I am passing multiple PHP variables to JavaScript functions. The issue is that the variables being passed to JavaScript function could have special characters.

I want the JavaScript function to be as follows:

jsFunction("argument1","argument2","argument3")

What I get:

jsFunction('argument1','argument2','argument3')

My Blade format code is:

<a href="#" onclick="displayBannerInvoice('{{$bannerProperty->property_id}}','{{ $bannerProperty->id }}','{{$bannerProperty->end_date}}','{{$bannerProperty->no_of_days}}','{{$bannerProperty->total}}','{{$bannerProperty->vat_percentage}}')"></a>
Mickael B.
  • 4,755
  • 4
  • 24
  • 48
Muhammad Raza
  • 424
  • 5
  • 22
  • 1
    Instead of using `onclick` and string concatenation which is very fragile and error-prone in this case, consider `json_encode` ing the data and storing the result in JavaScript variables. Then your `click` event handler set by `addEventListenter` or ... can easily read the data. – Ram Mar 09 '15 at 08:01
  • 1
    @Vohuman can you kindly give an example? – Muhammad Raza Mar 09 '15 at 08:05
  • 1
    Please refer to [this question](http://stackoverflow.com/questions/23740548/how-to-pass-variables-and-data-from-php-to-javascript). – Ram Mar 09 '15 at 08:07
  • 1
    change your onclick to: onlick='' instead of onclick="" so it will then be onclick='function("{{$variable}}", "{{$variable}}")' – Uche Dim Nov 19 '16 at 13:36

4 Answers4

6

The best shot is to not reinvent the wheel and try searching :)

There is a package already on github https://github.com/laracasts/PHP-Vars-To-Js-Transformer

It does exactly what you want. Its for Laravel 5 as well as Laravel 4.

Kyslik
  • 8,217
  • 5
  • 54
  • 87
1

You could use the following syntax to display a php variable in laravel blade:

{!! $someVar !!}

example:

console.log( {!! $someVar !!} );
Mickael B.
  • 4,755
  • 4
  • 24
  • 48
Mister Verleg
  • 4,053
  • 5
  • 43
  • 68
1

Here is an example of how I am doing it. I have a form with an update button which calls a JavaScript function.

{!! Form::button('Update', array('class' => 'btn btn-success', 'onClick' => 'updateTeamName(' . $team_id . ')')) !!}

I am passing the $team_id variable (passed to the view by the controller method) to the JavaScript function.

Hope this helps.

KalC
  • 1,530
  • 3
  • 22
  • 33
0

I've tried many syntax and finally this solved the problem. This is your answer:

jsFunction({{"$var1"}}{{","}}{{"$var2"}})
mahmood
  • 124
  • 1
  • 10