skip to Main Content

how can I access javascript variables in blade laravel?

for example

  var counter = 1;


 {{ dd(counter) }}

it gives me this error

Use of undefined constant counter – assumed ‘counter’ (this will throw
an Error in a future version of PHP)

2

Answers


  1. You can’t. You need to use JavaScript to inject the values to the Blade templates. Basically you need to do this in a script tag.

    <p id="counter"></p>
    
    <script>
    var counter = 0;
    
    counter++;
    
    document.querySelector('#counter').innerHTML = counter;
    </script>
    
    Login or Signup to reply.
  2. Its better to add any id where you want to show veriable then select this element using query selector

    <div id="show_variable"></div>
    

    and use jquery

    $(document).ready(function(){
     var countor = 0;
     counter++;
     $('#show_variable').html(counter)
    });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search