How I can get the current user in JS/Jquery? In the blade we can do like
{{Auth::user()}} But it wont work in the .js file.
As per looking at the standard and the way most javascript templates engine work, I would prefer to do something like this:
Install laracasts/utilities by using composer require laracasts/utilities
In the controller method, from where you are returning view, I would make it look like this:
public function returnUser(){
$user = Auth::user();
Javascript::put([ 'user.name' => $user->name, 'email' => $user->email ]);
return view('my.user.js');
}
In the blade file, I would simply do,
<script>alert("Hi " + user.name + ". Your email is " + user.email)</script>
And yeah, I would even prefer the way, #Robbin said. And yeah just one more edit to his answer, in laravel 5.1, Auth::user() should not be used. It should be used as auth()->user() //->name or ->email or ->anything.
You have to build an API and get it with AJAX. You cannot use blade in javascript files.
Or, in the <head> of your template, you place.
<script>
var user = {!! json_encode((array)auth()->user()) !!};
</script>
<!-- include your js file here-->
And use the user var in your js file.
EDIT:
As per Mark's comment this is indeed cleaner:
<script>
var user = {!! auth()->user()->toJson() !!};
</script>
<!-- include your js file here-->
simply =>
add any input or any tag to inject auth-user inside it, in my case:
< meta name="auth-check" content="{{ (Auth::check()) ? 'true' : 'false' }}">
in JS file u can get a value from your tag using jquery!
var authcheck = $('meta[name="auth-check"]').attr('content');
I hope my idea is useful, my best wishes
Related
Let's say i have data coming from my controller through Javascript.
So the data is paginated and i want display pagination result inside the javascript. I mean...I want to use the links() method inside javascript.
Controller
$schedules= DB::table('schedules')
->paginate(4);
Javascript,
success:function(schedules)
{
console.log(schedules);
$('#table').append(' <ul class="pager">'+{{ $schedules>links() }}+'</ul>');
})
But unfortunately not working, any help guys?
Push html paginate results from the controller, Enter the javascript code in the blade file, maybe
//controller
$paginate = '';
$paginate .= $datas->links();
//JS code in the blade file
<script type="text/javascript">
let paginate = '<div>';
paginate += {!! json_encode($paginate) !!}
paginate += '</div>'
consolelog(paginate)
</script>
You have an error in your blade syntax {{ }}:
$('#table').append(' <ul class="pager">'+{{ + $schedules>links() }}+'</ul>');
Remove the extra plus + icon before + $schedules>links() like so:
$('#table').append(' <ul class="pager">'+{{ $schedules>links() }}+'</ul>');
I think you can just convert the collection to a JSON.
Try this one:
Controller
$schedules= DB::table('schedules')
->paginate(4)->toArray();
return response()->json($schedules);
Javascript Ajax
success:function(schedules)
{
console.log(schedules);
$('#table').append(' <ul class="pager">'+schedules.links+'</ul>');
})
But in what I see, you're using the schedules also on your blade. In that case you can have a different function called for the ajax in your controller and different route.
Hope it helps!
I have some values on my controller that I want to pass to a javascript function in the view page.
In the controller, I have:
$f3->set('value', $value);
I can access the value on the view with {{#value}}, but how do I use(access) that value inside a javascript function on the view page??
<script type="text/javascript">
var value = XXX; //XXX in the {{#value}}, how do i access it in here???
</script>
It depends on the content stored inside $value.
If it's a basic string with no single/double quote inside, then the following code will work:
<script>
var value='{{ #value }}';
</script>
If it's an integer, the following code will work:
<script>
var value={{ #value }};
</script>
... although your IDE will probably report a syntax error.
If it's a float, the following code will work:
<script>
var value={{ str_replace(',', '.', #value) }};
</script>
... and your IDE will also probably report a syntax error. NB: the str_replace is for non-English locales that have decimal separator set to comma.
For all the rest (strings including quotes or arrays), you should convert your data to JSON, using one of the following techniques:
Technique 1:
Convert data to JSON and dump it to a JS object.
// controller.php (JSON encode)
$f3->set('data',json_encode($data));
<!-- template.html -->
<script>
var data={{ #data | raw }};
</script>
Pros: easy to use.
Cons: your IDE will report a syntax error + extra call to raw.
Technique 2:
Convert data to JSON, dump it to a JS string and parse it.
// controller.php (JSON encode + escape double quotes)
$f3->set('data',str_replace('\\u0022','\\\\u0022',
json_encode($data,JSON_HEX_APOS|JSON_HEX_QUOT)));
<!-- template.html -->
<script>
var data=JSON.parse('{{ #data | raw }}');
</script>
Cons: less easy to use + extra call to raw.
Pros: your IDE will not report any syntax error.
Technique 2bis:
Embed technique 2 in a F3 template filter.
// index.php
$tpl=Template::instance();
$tpl->filter('safejson',function($data){
$raw=\View::instance()->raw($data);
return str_replace('\\u0022','\\\\u0022',
json_encode($raw,JSON_HEX_APOS|JSON_HEX_QUOT));
});
<!-- template.html -->
<script>
var data=JSON.parse('{{ #data | safejson }}');
</script>
Pros: easy to use + your IDE will not report any syntax error.
Cons: extra call to raw.
Technique 3:
Convert data to JSON and embed it inside a DOM data- attribute.
// controller.php (JSON encode)
$f3->set('data',json_encode($data));
<!-- template.html -->
<div id="foo" data-json="{{ #data }}"></div>
<script>
var data=JSON.parse(document.getElementById('foo').dataset.json);
</script>
Pros: easy to use + your IDE will not report any syntax error + no extra call to raw.
I went a bit lazier than that.
I have my data in a dictionary file (F3). I load it in an input field at the bottom of my page and assign value via templating. I use Jquery (plain JS could be used to) to retrieve value.
Ex:
Dict data
'prf_conf'=>' Update your profile'
In my profile.html
`< input type = 'hidden' id ='prf_conf' value='{{#prf_conf}}' >`
//this loads data in whatever language on my page
JS
Confirm button text: (i used jquery-confirm.min.js in this example)
$.confirm({ title: $('#prf_conf').value()
… bit of gymnastic but worked well. No IDE issue…
I have simple javascript code:
var photo = data.photo;
console.log("{{url('" + photo + "')}}");
Here I use laravel url() method. But I can't display value photo inside laravel method. How I can display it?
It's a bad practice to mix Blade syntax with JS. You should do something like this in one of Blade templates:
<script>
let window.url = {{ url('/') }}
</script>
Then in JS files use this variable:
var photo = data.photo;
console.log(window.url + photo);
You'll find another related code example in my Laravel best practices repo.
Is there any way to print js file?
I know I can use register method of AssetBundle class to register a js/css file into page, also there is another option: to store javascript code in a php variable and use the following method:
\yii\web\View::registerJs($js, \yii\web\View::POS_READY);
But what I need is (on server-side) open a js file, get the contents and write down the code into the html.
The meaning of doing so is that the javascript code is needed only in one page, but also I don't want to add extra requests on client-side.
Also, I know, I can use php include method to load the file and store into a variable, but maybe there is a Yii-way.
So, is there any proper way to do so ? Any help will be appreciated.
Try this , I hope this will Help you.
<?php
$this->registerJs('
$(document).ready(function(){
$(\'.ordinary\').hide();
$(\'.special\').hide();
$(\'#company-typeofcompany\').change(function () {
var x = $(this).val();
if (x === "ordinary") {
$(\'.ordinary\').show();
$(\'.special\').hide();
} else {
$(\'.special\').show();
$(\'.ordinary\').hide();
}
});
});', \yii\web\View::POS_READY);
?>
Thank You..
I am using Nodejs and ExpressJS .
I have an HTML page , which has a Javascript file being referred to .
<script type="text/javascript" src="../javascripts/game.js"></script>
I have not embedded all the Javascript into the HTML page itself because its too big .
Now I need my Javascript ( game.js ) to access some of the variables being passed by the controller . I want to do something like this -
var max_players = parseInt("<%= table.total_players %>");
console.log("<%= table.name %>")
I am passing the table variable while rendering the page .
exports.index = function(req,res){
//code
res.render('mytable', {table: table });
};
But this obviously doesnt work because the JS file is being rendered as a static file .
How do I go about if I need to make these variables accessible to the Javascript ?
I read somewhere that this can be achieved by renaming Game.js to Game.ejs . But where do I put the Game.js file ( so that its rendered properly and dynamically ? )
If there are any other ways to achieve this , please also let me know .
Probably the simplest option would be to output the globals you need from table (or table itself) in another <script> before game.js:
<script>
var max_players = <%- JSON.stringify(table.total_players) %>;
console.log(<%- JSON.stringify(table.name) %>);
/* Alternative:
var table = <%- JSON.stringify(table) %>;
var max_players = table.total_players;
console.log(table.name);
*/
</script>
<script type="text/javascript" src="../javascripts/game.js"></script>
Note the use of <%- ... %> vs. <%= ... %>, which will skip HTML-encoding the output as that can cause syntax errors in.
Using JSON.stringify() here takes advantage of the syntax relation between JSON and JavaScript. The values will be written as JSON data server-side, but parsed as JavaScript literals client-side.
If you want to run game.js itself through EJS, you can move it into your ./views directory, add a route for it, and res.render() it.
Note that you'll need to set the Content-Type as the assumed value will be text/html, which could some browsers will refuse to parse.
// ~/views/game-js.ejs
var max_players = <%- JSON.stringify(table.total_players) %>;
console.log(<%- JSON.stringify(table.name) %>);
// ...
app.get('/javascripts/game.js', function (req, res) {
// code
res.setHeader('Content-Type', 'application/javascript');
res.render('game-js', { table: table });
});
Another option would be to have game.js make a request for table. You can see an example of this in a previous edit of this post.