简体   繁体   中英

Store PhP variable in JavaScript variable

I'm really new into web dev and I'm working on a project which uses the TALL stack:

  • Laravel Mix ;
  • Livewire ;
  • AlpineJS and;
  • TailwindCSS .

I want to get a PhP variable and store it in a JavaScript variable, so I can do jQuery/JavaScript stuff with it.

The PhP variable is <?php Auth::user()->kyc_status?> and I would like to store it in a JavaScript variable called kycStatus . The idea could be represented by something like let kycStatus = <?php Auth::user()->kyc_status?>

Thanks in advance.

<script>
    let kycStatus = {{ Auth::user()->kyc_status }}
</script>

You can do it like following

<script>    
    var kycStatus = {!! json_encode(Auth::user()->kyc_status) !!};
</script>

Or use this Laravel package https://github.com/laracasts/PHP-Vars-To-Js-Transformer to pass some server-side string/array/collection/whatever to your JavaScript.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM