Vince Gonzales
Vince Gonzales

Reputation: 985

Laravel - How to pass a php variable to a javascript function from a blade file

I have an html element inside my blade file:

<input id="check_all" onclick="toggleCheckOrders('$orderFormObject', ' $count')" name="check_all" type="checkbox" value="1">

The onclick handler is assigned a javascript function toggleCheckOrders which accepts two parameters which are objects that were passed from the controller to the blade template. When I do this, it just treats them as strings inside the javascript function, it there a way to pass them while retaining their respective data types?

Upvotes: 0

Views: 4872

Answers (4)

Harrison O
Harrison O

Reputation: 1210

In HTML do as seen below:

<input id="check_all" onclick="jsFunction(`{{json_encode($orderFormObject)}}`, `{{ json_encode($count)}}`)" name="check_all" type="checkbox" value="1">

In javascript, do the following:

<script>
  function jsFunction(orderFormObject, count) {
      const orderFormObjectNew = JSON.parse(orderFormObject);

      console.log(orderFormObjectNew);
      console.log(count);
  }
</script>

I hope this will be helpful.

Upvotes: 0

N69S
N69S

Reputation: 17204

you can simply do

<input id="check_all" onclick="toggleCheckOrders({{json_encode($orderFormObject)}}, {{ json_encode($count)}})" name="check_all" type="checkbox" value="1">

carefull that associative array will be casted as object in JavaScript

Upvotes: 0

apokryfos
apokryfos

Reputation: 40653

Here's a little helper I wrote for myself:

I added this in my AppServiceProvider.php:

 Blade::directive('jsvar', function ($expression) {
     return "<?php echo json_encode($expression); ?>";
 });

This will allow you to do:

<input id="check_all" onclick="toggleCheckOrders(@jsvar($orderFormObject), @jsvar($count))" name="check_all" type="checkbox" value="1">

If you find yourself passing PHP variables to JavaScript often I highly recommend this approach.

Upvotes: 0

Marcin Nabiałek
Marcin Nabiałek

Reputation: 111829

You should use:

<input id="check_all" onclick="toggleCheckOrders('{{ $orderFormObject }}', ' {{ $count }}')" name="check_all" type="checkbox" value="1">

In Blade you use {{ ... }} to echo variable value

Upvotes: 0

Related Questions