User javascript variable inside php blade Hello,
I want to use a javascript variable inside php in a blade template. Probably explained a little bit wrong, so here is my code:
// Some HTML
<script>
var javascriptNumber = $('#id').val();
$("#response").html("{{ trans('messages.themessage', ['number' => javascriptNumber]) }}")
</script>
So, how to put javascriptNumber in the trans array.
Your Javascript variable is on client side, you cant use it in Blade.
You can't do that, php is executed before the page loads, your javascript when the page is done loading.
You should do a request to your server with the number and read the response.
in your route/controller you can then get the number and return the appropriate data.
@malfait.robin Aarrgh of course! Didn't thought of that!! Thanks. I will need to fix this with an AJAX call!
or you can put these values into a HTML data attribute (data-something="value") and just pick them up from the JS side.
@postitief Sometimes, in the view that is needs to implement this functionality i create a particular section
@section ('footer_scripts')
<script>
var javascriptNumber = $('#id').val();
$("#response").html("{{ trans('messages.themessage', ['number' => javascriptNumber]) }}")
</script>
@stop
And then on the master layout, under the scripts i yield it.
@yield ('footer_scripts')
This allows me to inject data from my views and have it render altogether with the javascript after the page has loaded.
This will work in your case.
Just pay attention, as you're using jQuery, to place the yielded section under the jQuery import.
You're good to go.
Please sign in or create an account to participate in this conversation.