How inside of laravel methods use javascript vars in javascript code? - javascript

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.

Related

Django | JS variable inside dynamic URL

I'm trying to pass a javascript variable inside a dynamic url using Django. I have the following path
path('task-update/<str:pk>/', updateTask, name='task-update'),
I'm able to retrieve the "Task" fields I created (id, title, description, ...) depending on what task I select inside the HTML (this is done using AJAX and the Django-REST Framework). However, I'm having some trouble on rendering javascript values inside dynamic urls
var url = `{% url 'task-update' pk=${activeItem.id} %}`
The ${activeItem.id} is where I'm having some trouble, I tried assigning it to a variable and passing that into the URL but it doesn't work.
A workaround I've been using is
var url = `http://127.0.0.1:8000/task-update/${activeItem.id}/`
however I'd like to use django's template tags
After searching for quite a bit this was the best neat-looking solution I found (also the only one): django-js-urls.
Just pip install django-js-urls and add 'js_urls' to your INSTALLED APPS.
Afterwards add simply add JS_URLS to your settings.py file and put the names of the paths you'd like to use. In my case I only added task-update, it looks something like this
JS_URLS = (
'task-update',
)
Then, all you need to do is add the following in the URLs root module
from js_urls.views import JsUrlsView
urlpatterns = [
# other urls
url(r'^js-urls/$', JsUrlsView.as_view(), name='js_urls'),
]
And include the following js in the template
<script src="{% url 'js_urls' %}" type="text/javascript"></script>
URLs can be used using the window.reverse function
var url = window.reverse('task-update', { pk: activeItem.id });
I found a trick that might work under most circumstances:
var url = "{% url 'task-update' pk=12345 %}".replace(/12345/, ${activeItem.id});
It's clean, and it doesn't break DRY principle.

How to pass javascript variable to flask url_for which inside innerhtml?

I try to pass JavaScript to url_for which is inside innerhtml using the below code:
var data = 'abc';
mydiv.innerHTML =
"<button onclick=window.location.href='{{ url_for('flask_function', filepath="+data+") }}'></button>
But the result when I print out the data in Python is like this:
+data+
So how can I pass my data to Flask using this code?
Would like to put this in comment.
You missed an " at the end.
Also otherwise this will not work because this is rendered in Jinja template python while generating code that has to be sent of the frontend. So it does not recognize js variables.
You will have to use a python variable with jinja template instead
{% set data = 'abc' %}
Or send the data in template and use
{{data}}
you can use like this worked for me
var actualUrl = "/flask_function/" + id + ""
post.innerHTML =''

How to get array from controller on javascript blade in Laravel

I'm working on a laravel project and am trying to pass an array from a controller to javascript. The following code is from my controller.
$dicomfilearray = $dicom->pluck('filename')->toArray();
return view('xray.view')->withDicomfilearray($dicomfilearray);
And below is the Javascript in that's in the blade file I'm trying to pass it to.
var dicomarray = '{{ json_encode($dicomfilearray) }}';
console.log(dicomarray);
And the following is a log result from the Javascript.
["storage/uploads/storeid1/27/10/dicom/c4p4Oco3rU.dcm","storage/uploads/storeid1/27/10/dicom/RNil0NPPzQ.dcm"]
I would like to get a list from this array. Any advice or guidance on this would be greatly appreciated, Thanks.
You can make ajax call in frotend, and backend do like this
$dicomfilearray = json_encode($dicom->pluck('filename'))->toArray());
return view('xray.view')->withDicomfilearray($dicomfilearray);
when you working in javascript and need data in javascript then why you need view part. Actually, I just read your comment.
If in Ajax
so I suggest send array with json_encode and populate that data into view with javascript.
simply right below in controller
response()->json(['status'=>200,'data'=>$dicomfilearray])
Update
So ,you not sending ajax request so, simply. do like below.
controller:-
$data = json_encode($dicomfilearray);
return view('your-view',compact('data'));
javascript
var dicomarray = '{{ $data }}';
You can do something like this and this even works if you want to pass the variable to external javascript file. All you have to do is to call the init function with passed parameters.
<script>
$(function () {
init({{ json_encode($dicomfilearray) }} });
function init(dicomfilearray){
//use your variable here
}
</script>

get current user in Javascript/jQuery Laravel 5.1

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

Use Separate js File And use Url Helpers in it with ASP.NEt MVC 3 and Razor View Engine

I ask a similar question here and Darin Dimitrov answer that we can't use Url helper like $.ajax({ url: '#Url.Action("Index")', . . . in separate js file so what is your suggestion to use Url helper in view page and pass it to javascript, I don't want to use hard code url, I need to find it with Url helper.?
Use a hidden field to store your url, then use javascript to read the hidden field, then use that in your code. That way you can keep the JS file separate to the view. Something like this:
//In Your View
#Html.Hidden("MyURL", Url.Action("Index"))
//In Your JS
var myUrl = $("#MyURL").val();
$.ajax({ url: myUrl , . . .
The easiest way is just to create a global variable called something and just reference to it in your external JS
var baseURL = '#Url.Action("Index")';
Inside your external JS
$.ajax({ url: baseURL + "Action"
You can use RazorJS for that purpose. It allows writing Razor-Style C# or VB.NET inside your JavaScript files. There is a short description available here.
There is no need to have hidden field, even this works too in the external .js file.
var myUrl = /ControllerName/ActionName;
$.ajax({ url: myUrl , . .
Take a look at Generating External JavaScript Files Using Partial Razor Views. In this blog post, I describe how you can make use of regular Razor views and a custom action filter to render external JavaScript files that can have Razor code in them.
I used a similar approach to raklos, but was looking to get the root directory path in all places, so I went with the code below.
#Html.Hidden("AppUrl", Url.Content("~"))

Categories