Laravel Blade Pass Javascript Variable In Php
Solution 1:
PHP has finished doing its work even before the page hits your browser, so passing a variable from Javascript to PHP without doing another request is simply impossible. Consider
A) Moving your loop to Javascript. Consider using some UI library like Vue.js, Angular or React.
B) Move the contents of myJsVar
to PHP. If it depends on user input or browser rendering, that impossible.
C) Performing the rendering logic through an Ajax-request
$.ajax({
type: 'GET',
url: myUrl,
headers: {'X-Requested-With': 'XMLHttpRequest'},
data: {value: myJsVar},
success: function (response) {
$(someContainer).html(response);
}
});
And in your controller:
publicfunctionprod()
{
$value = Request::get('value');
return view('view-with-a-loop')->with('value', $value);
}
Be careful with the latter method XSS-wise.
Solution 2:
I use a section in blade to add the javascript then pull that into the layout. The example below shows passing of integer/string/collection of models, eg:
// blade template
@extends('layouts.app')@section('javascript')
<script type="text/javascript">
var myInteger = {!! $myInteger !!};
var myString = '{!! $myInteger !!}';
var myObject = {!! json_encode($models) !!};
</script>
@endsection@section('content')
...
@endsection
// Layout (the javascript can go anywhere in the layout, ie the head or body:
<!DOCTYPE html><html><body>
@yield('content')
@yield('javascript')
</body></html>
Post a Comment for "Laravel Blade Pass Javascript Variable In Php"