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>
4
  • 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. Commented Mar 9, 2015 at 8:01
  • 1
    @Vohuman can you kindly give an example? Commented Mar 9, 2015 at 8:05
  • 1
    Please refer to this question. Commented Mar 9, 2015 at 8:07
  • 1
    change your onclick to: onlick='' instead of onclick="" so it will then be onclick='function("{{$variable}}", "{{$variable}}")' Commented Nov 19, 2016 at 13:36

4 Answers 4

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.

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

Comments

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.

Comments

1

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

{!! $someVar !!}

example:

console.log( {!! $someVar !!} );

Comments

0

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

jsFunction({{"$var1"}}{{","}}{{"$var2"}})

Comments

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.