Can I use data from blade inside javascript code

- 1 answer

Ad

Can I pass blade variable to javascript code:

var deadline = 'Octobar 20 2015 22:00:00 UTC+0200';
initializeClock('clockdiv', deadline);  
    };

How can I pass deadlinevariable with {{$article->auction_end}} ? Is that possible or do I need to make an ajax call ?

Ad

Answer

Ad

What I usually like to do because I think it's cleaner than directly setting php variables as javascript variables is to generate a meta tag for it instead.

<meta name="deadline" content="{{ $article->auction_end }}" >

Then you can grab it later with jquery.

var deadline = $('meta[name=deadline]').attr('content');

This way is especially helpful if you want to break out the js into its own file rather than have a bunch of javascript in your views.

However, yes it is possible to set your javascript variable with PHP, assuming your javascript is inside your .blade.php file...

var deadline = '{{ $article->auction_end }}';
Ad
source: stackoverflow.com
Ad