How to write ruby method in js file - javascript

I'm trying to display in each cell of my calendar in js (fullcalendar) a ruby method “week_balance” where I have some informations but I can't.
I write :
dayRender:function(cell, week_balance){
$(cell).html(‘<span>’ + week_balance + ‘</span>’);
},
It doesn't work, why ?
Thanks.

If you are using Rails framework, then it provides an option where you write ruby code in Js file.
For this, you need to change extension for js file to .js.erb
And then call ruby function is js method as,
dayRender:function(cell, week_balance){
$(cell).html('<span>' + "<%= week_balance %>" + ‘</span>’);
},
make sure week_balance is accessible without any parent. Else make it class method and use it.

Related

How to pass JavaScript variable to Symfony route using Twig path function

I have a small problem with a Javascript variable in a Twig template,
what I want is to pass a variable as a parameter (in a url) to a function. All I have found on StackOverflow is how to pass a string 'blablabla' to the URL like:
url/{param}, {'param' : 'blablabla'}
but I want something like :
$var =...;
url/{param}, {'param': $var}
this photo should make it clear to you , thanks for reading
photo
I advise you to use the FOS JsRouting bundle. It is totally suited to what you want to do.
Here is the official documentation : https://symfony.com/doc/current/bundles/FOSJsRoutingBundle/usage.html
Example in Twig :
Routing.generate('your_route_with_params', { param: varJavascript });
Enjoy

Print js file Yii2

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..

asp.net mvc another controller in the same folder

I have a folder 'Report' which holds ReportController.
Now i want to add AgreementController to the same folder.
from javascript i have a code which runs 'Download' action (downloads file).
When i run from javascript - Report/Download/id='5' everything fine.
When i run from javascript - Report/Agreement/Download/id='5' everything bad.
How can i run 'Download' action from Agreement controller ?
I dont want one folder-one controller structure.
I think only areas can help me there ?
according to routing:
url: "{controller}/{action}/{id}"
your code is:
Report/Agreement/Download/id='5'
so in your case:
Controller= Report
action= Agreement
Id= Download.
that's why you get an error
You need to remove Report from call end use this:
Agreement/Download/id='5'
If you are writing js in same view page and not in external js file, you can use mvc url.action in ajax call file method to call appropriate controller and action method as described below
syantax:
url: '#Url.Action("ActionMethodName","ControllerName",new {Parameters})'
In your case it would be something like this:
to invoke report controller's download method
url: '#Url.Action("Download","Report",new { id = "Value" })'
to invoke agreement controller's download method
url: '#Url.Action("Download","Agreement",new { id = "Value" })'
If you are using external js file then it will be as below
url: serverbaeurl + "/Report/Download?id=" + "Value"
url: serverbaeurl + "/Agreement/Download?id=" + "Value"
(here serverbaseurl will be the domain of website)
(you will have to add other ajax options as needed)

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("~"))

Best way to get server values into JavaScript in .NET MVC?

Using ASP.NET MVC + jQuery:
I need to use some values owned by the server in my client-side JavaScript.
Right now, I've temporarily got a script tag in the actual view like this:
<script>
var savePath = '<%= Url.Action("Save") %>';
</script>
But I want to move it into something cleaner and more maintainable. I'm thinking of something along the lines of creating a JavaScript controller/action and returning a JSON object that would contain all the data I need, then using the view as the src for a script tag.
Any other ideas?
This actually depends. For simple inliners, the line above works just fine. If you need a LOT of server data in the JavaScript, your view approach may work. However you'll get the same result if you just render partial view that outputs the required JavaScript.
There's a problem with this, since you may end up mixing server data with JavaScript. The best approach would be to minimize server data to absolute minimum, and pass it to JavaScript functions instead of mixing with JavaScript code. That is, not
function func() {
var path = '<%= Url.Action("my") %>';
$(".selector").append("<img src='" + path + "' />");
}
but
function AppendImageToSelector(path) {
$(".selector").append("<img src='" + path + "' />");
}
function func() {
var path = '<%= Url.Action("my") %>';
AppendImageToSelector(path);
}
This makes the code cleaner and easier to understand, helps to move JavaScript out to separate .js files, helps to re-use JavaScript when needed, and so on.
If you need a lot of server-related URLs in JavaScript, you may want to create global (in master page) function like
function url(relative) {
return '<%= Url.Content("~") %>' + relative;
}
and use it from JavaScript scripts. This technique is questionable, though; for example it doesn't use MVC routing rules so URLs may not be out of sync; etc.
I know this is not applicable in all cases but when I need to pass an Url to a client script (as in your example) it is often to ajaxify some anchor or button I already have in the DOM:
<%= Html.ActionLink("Save data", "save") %>
and in my script:
$('a').click(function() {
$.get(this.href);
return false;
});
Stephen Walther - ASP.NET MVC Tip #45 – Use Client View Data

Categories