Interpret variable in Javascript file Laravel - javascript

I need to include a js file in my views.
But in this js file i need to interpret somes PHP variable.
Actually i do this :
#section('javascript')
<script>
alert("{{{test}}}");
</script>
#stop
But i REALLY need to do this :
#section('javascript')
{!! Html::script('js/test.js') !!}
#stop
test.js :
alert("{{{test}}}");
I need to declare a lot o variable. So my JS file will be very huge. And i don't want to show this directly in the source code.
How can i do ?
Thank you !

You can only pass the variable to the javascript like so:
#section('javascript')
<script>
var test = {{{$test}}};
</script>
#stop
then in your javascript file included at the bottom you can use it:
alert(test);
Let me just mention that this is not a great way of handling the passing variables from php to javascript.

When I need to do something like this, I usually create a meta tag on the page which would contain the alert information.
<meta name="someAlertValue" content="{{{ $test }}}" />
Then you can very easily grab that via jQuery.
var alert_text = $('meta[name=someAlertValue]').attr('content');
I find this approach to be much cleaner and maintainable than trying to drop php variables directly into your javascript.

I had the same problem, and wanted to have a stand alone js which will have bunch of variables taken from config() or even from database, multi-language, and will be configurable, or even will work with query parameters.
Maybe it's a hard way, but i've created a route:
Route::get('/js-modules/test.js',function(){ return view('js-modules.test');})->name('my_js);
So in the view resources/views/js-modules/test.blade.php you can put your js code together with your PHP stuff.
Or you can route it to a controller and have even more background work. it looks a bit slow (in the browser) on the first run , but second request it'll be cashed and retrieved as the regular js file
And now you can link it to any of your pages with
<script src="{{route('my_js')}}"></script>

Related

Embed same web widget multiple times with different data attribute values

I want to create a web widget that can be embedded multiple times on the same page but with different data attribute values so I can display different data according to the data attribute value.
For example, I want to embed mywidget.js file multiple times as follows:
<body>
<div>
<script src="script/mywidget.js" data-sport="soccer" id="widget-soccer">
</script>
</div>
<div>
<script src="script/mywidget.js" data-sport="tennis" id="widget-tennis">
</script>
</div>
</body>
My question is, inside the code in mywidget.js, how do I determine the correct script tag reference and read it's data attribute so I can use that value to fetch the corresponding data from a web service. I am using only jquery and javascript.
I want the widget to be embeddable on other users sites as well so all they do is embed using only the script tag and passing in the desired data attribute value without adding anything extra anywhere they need on their website.
This is not really a very good approach, as it is very inflexible. But given that <script> tags, when not deferred, halt parsing of the document while they execute, the current script tag will be the last in the DOM; so you can get the current sport inside your script by using this:
var sport = $('script').last().data('sport');
However, it would be much better to define a function in your external JavaScript file, and then invoke it when you need to instantiate your widget (EDIT: like in Lee Taylor's answer).
Why don't you do something like:
<head>
<script src="script/mywidget.js"></script>
</head>
<body>
<div><script>createMyWidget({sport : "soccer"} );</div>
<div><script>createMyWidget({sport : "tennis"} );</div>
</body>
I don't think you can. I know it's not that nice, but I would try:
<div><script>sport = "soccer";</script><script src="script/mywidget.js" id="widget-soccer"></script></div>
<div><script>sport = "tennis";</script><script src="script/mywidget.js" id="widget-tennis"></script></div>
and use sport in mywidget.js
Another approach could be that myscript.js is actually a dynamic "page", let's say with php, then you could use src="script/mywidget.js?sport=swimming", and in the php you would print:
sport = "<?php echo addcslashes($_GET['sport'], '"'); ?>";
But even better would be:
<script src="script/mywidget.js"></script>
<div><script>showWidget("soccer");</script></div>
<div><script>showWidget("basketball");</script></div>
I think you can use jQuery to find all script tags with src="script/mywidget.js" or something
$('script[src="script/mywidget.js"]')
And then you'll have an array of scripts tags that you can loop through and access the data property using jQuery's .data() method.

Rendering mustache template stored in file

I'm trying in a Rails app to render some json data through a mustache template.
My starting point was this railscast: http://railscasts.com/episodes/295-sharing-mustache-templates
In the cast Rayn does something like
$('#target').append Mustache.to_html($('#project_template').html(), json-data)
Having in the html a div with id="project_template" that contains the template
<script type="text/html" id="project_template">
...
</script>
However, I'd like to be able to store the mustache template into a file (let's say in app/views/projects/project.mustache) and load it directly in my js.
Something like
$('#target').append Mustache.xxxxx(MUSTACHE_FILE, json-data)
I have looked around but I cannot find anything that works or any suggestion. Is this possible to achieve?
Thanks.
You can't access server-side file in javascript directly, but you can use an alternative way to store template on the server side.
You can store the template in app/views/projects/project.mustache for example.
In your project.mustache, you can write:
<script type="text/html" id="project_template">
...
</script>
In your view, you can use:
<%= render :file => 'projects/project.mustache' %>
And use javascript as same as before.
$('#target').append(Mustache.to_html($('#project_template').html(), json-data));
I think it isn't perfect, but it should work :)

"onComplete attribute must be javascript function name" what am i typing wrong?

I'm trying to run a piece of JavaScript code on completion of a song in the <cfmediaplayer> tag but whenever i put "playNext()" into the onComplete attribute it provides me with an error telling me it must be a proper name, but that is the proper name? Anybody know where i might be going wrong?
<script type="text/javascript">
function playNext(){
<cfoutput>
var #ToScript(URL.current, "trackNo")#;
</cfoutput>
trackNo++;
$("#" + trackNo).click();
}
</script>
<div style="margin: 0 auto; width: 500px;">
<cfoutput query="getmusic" maxrows="1">
<cfmediaplayer name="musicPlayer" source="/artists/music/#music_location#" autoplay="yes" height="500" width="500" title="#artist_name# - #music_name#" onComplete="playNext"></cfmediaplayer>
</cfoutput>
</div>
This is my code, however i just noticed (using the Web Developer toolbar) that it is saying playNext is undefined, yet clearly i DO have it defined there as displayed. I'm wondering what I may have done wrong, as far as i'm aware my JavaScript looks OK but i'm a novice when it comes to JS so i've probably made a simple mistake.
use onComplete="playNext" not "playNext()"
Try calling "playNext()" in the onComplete attribute as playNext with no quotations or brackets. If that does not work use playNext(). Let me know if that helps.
I could be wrong but I think it has to do with a CFIDE mapping.
The CFIDE/Scripts folder is needed for a lot of the client side controls ColdFusion creates.
Some CFForm elements like the date picker, multiple file upload, cfajaxproxy, cfmediaplayer, etc require these scripts to be mapped or copied to the site.
Here is a SO question that may help.
Workaround for CFIDE Not Web Accessible for AJAX and Flash Built-Ins
Here is a general google search on the subject.
Try a simple script to mute the player you get any 'Coldfusion is undefined' errors. something like
<script language ="javascript">
ColdFusion.Mediaplayer.setMute('musicPlayer', true);
</script>

Playframework: Elegant way to pass values to javascript

Does anyone have an elegant solution to pass server values to javascript (that is not inline) in playframework? just like ${x} or &{'x'} inside html
Currently I can think of
<script type="text/javascript">
var x= ${x};
</script>
<script src="/public/javascripts/jsThatUsesX.js" type="text/javascript" ></script>
I'm thinking there is a better solution from play
It's not pretty, but that's the way I always end up doing it.
If the values that you're passing to JavaScript describe something in the DOM, you might consider using HTML 5 data attributes to place that information in the HTML. Then you can retrieve it with getAttribute. e.g. If your page is a blog post and you need to store the post ID you could use
<div class="post" data-post-id="77">
...
</div>
That way the data is separated out from the logic and you don't need to inline any JavaScript. You could also use a hidden form field.
What's wrong with that? I found myself doing things like
<script>
var trades = [${_trades.collect {models.Trade t -> t.price}.join(", ")}];
// ...
</script>
I like it the groovy way ;)

How do I use Javascript in my Coldfusion page?

I have a coldfusion page and I am very newbie in coldfusion. What I need to do is to insert the alert in between to see what is the time. In php I could close the php tags and enter the javascript tag and alert out the value. How would I do that in coldfusion? I have this
<cfset right_now=Now()>
<cfscript>
alert(#right_now#);
</cfscript>
But its not working.
thanks
<cfscript> is a Coldfusion tag for using the Coldfusion scripting language (aka CFScript). If you want to use Javascript, open a <script> tag like you would normally in HTML. You'll probably want to make sure it's inside a <cfoutput> tag if you want to use Coldfusion values within your javascript.
<cfset right_now = Now()>
<cfoutput>
<script type="text/javascript">
alert('#right_now#'); // don't forget you need to put quotes around strings in JS
</script>
</cfoutput>
You don't need to even use cfscript for this specific need. You could, for instance, do this:
<script type="text/javascript">
var currtime = new Date();
alert(currtime);
</script>
... Also a point to remember, you can't directly output HTML from within a <cfscript> tag. You can however get around this by calling a function from within a <cfscript> tag that can output the data for you.
Always remember the coldfusion begins and ends before anything else is executed: html, javaScript, sql, etc., so the javascript is getting an already formed code, which is CF instead of being hard coded.

Categories

Resources