Grails 2.0: Use Service in javascript function in GSP - javascript

I am just wondering how I can call a method of a service from within a function within a GSP. I tried the following but it does not seem to work:
<%# page import="com.company.MyService" %>
<%
def myService =grailsApplication.classLoader.loadClass('com.company.MyService').newInstance()
%>
<html>
<head>
[...]
<script language="javascript">
function myFunction() {
if (${myservice.isSomethingAvailable()}) {
[...]
}
}
</script>
I am pretty new to javascript and Grails. Not sure how to achieve that or if it's even possible. Any help appreciated.
Thanks a lot
Jonas

loadClass().newInstance() creates new instance of object, not spring bean (i mean it's not tied to grails infrastructure), i'm sure it's not what you want
You can pass service from your controller, like render(model: [myService: myService]) (you have to declare it at controller lever)
It's much more correct way is to pass result of this call, not service itself. I mean: render(model: [isSomethingAvailable: myService.isSomethingAvailable]) and test it as if ($(isSomethingAvailable)) {
Notice that gsp is processed in server-side, not client-size. So it doesn't matter where you use your variable - on javascript code, or html code. And also, you can use gsp if tag: <g:if test="${isSomethingAvailable}"> instead of preparing javascript to check value on client-side (because you already know the result)

Related

How to pass a scriptlet variable into onclick() function call to javascript

I need to read a variable and then have to pass that as an argument to a function after onclick().
I am using JSP, so I am reading the variable using scriptlets
<% int lateRegDays = 6;%>
I am passing the variable as
onclick="displayDatePicker('startTestAdminNo','mdy',<%=lateRegdays %>,120,0,3);"
But, I am unable to pass the valueof 6. The string "<%=lateRegDays%>" is being passed to the function. However, when I tried to print the value using alert, it worked. The changes I did is,
onclick='<%="alert("+lateRegDays+")"%>'
In the similar fashion, I need to know, how to pass all my arguments to function with this scriptlet variable. The entire code snippet is:
<td><input name="startTestAdminNo"></td>
<td>
<chtml:img srcKey="order.calendar.search" onclick="displayDatePicker('startTestAdminNo','mdy',<%=lateRegdays %>,120,0,3);"
altKey="order.calendar.alt_search" bundle="prompt" />
</td>
I need help with this as I am stuckand I don't know how to pass multiple arguments along with a scriptlet variable
Scriplets will generate the HTML content when the Browser loads the JSP page, so if you want to use it inside your javascript, you need to capture that lateRegDays variable during the page loading time as below:
<script>
var lateRegDays; <!-- global variable -->
function init() {
lateRegDays = '<%= lateRegDays %>';
}
function displayDatePicker(...) {
// Get the lateRegDays var
}
</script>
<body onload="init()">
<!-- your code -->
</body>
P.S.: Scriplets are legacy code (invented in early 2000 by Sun), which is not a best practice to use them, so avoid them by using the latest front-end technology stack for the presentation layer.

using controller variable in javascript in phoenix

Is it possible to use a variable which is passed from controller to view in render parameters to be used in javascript and how to do it?
The variable passed from controllers can be used in javascript as following:
<script type="text/javascript">
alert("<%= #var %>")
</script>
Another way you can use PhoenixGon it generates script tag with variables and additional methods for simplicity. It generate all stuff for you. You only need to use it from window.Gon or wundow.YouApplicationNamespace. And you don't need other rendering and data attributing in html.
In controller:
def index(conn, _params) do
conn = put_gon(conn, :variable, :value)
render conn, "index.html"
end
In js module or browser console:
window.Gon.getAsset('variable')
# => 'value'
It also keeps Mix.env for using in js.

Call Javascript Function before Razor calls my HTML Helper

I've been working on a HTML helper which will hide or show menu items depending on what type of user you are.
For this reason, In one of my controllers I am setting a session variables with values such as "ADMIN"
context.Session["perfil"] = "ADMIN"
The problem I am facing is that the Helper function is being called before the Javascript function which calls the controller that sets the session variables
This is how I call my HtmlHelper (through Razor)
#using XSiteManagerWeb.Helpers
#Html.Raw(Html.MiMenu("../Home/Configuracion", "ConfiguraciĆ³n"))
From my _Layout.cshtml
But before doing that I'm calling the function
<script type="text/javascript">ObtenerDatosSesion();</script>
Which calls a Controler method through Ajax
...
$.ajax({
url: "../Home/ObtenerDatosSesion",
....
Question: Why is the HtmlHelper being called before ObtenerDatosSesion(); even though I've put it before on the _Layout.cshtml ?
I've also tried calling in on window load doing this:
<body class="Fondoblue" onload="ObtenerDatosSesion();">
among other methods.
I noticed the Helper is being called before everytime after many debuggings. What I can't figure out is why that happens.
I wonder if it has anything to do with the Web.config line one has to put to use html helpers
<add namespace="XSiteManagerWeb.Helpers"/>
So to make it clear, I just want to make my "ObtenerDatosSesion(); method gets called before my html helper!
The razor helpers are executed server side, therefore they will be executed before any JS is rendered/executed on the page.
I would recommend moving whatever logic is in your ../Home/ObtenerDatosSesion endpoint to the same endpoint as ../Home/Configuracion. If it's going to be called more than once, you can put it in its own method.

Get model values in separate Javascript file

I'm using ASP.NET MVC 2 and stuck with the situation when needed to store all javascripts in separate javascript files.
But in some pages Javascript's contains information from server-side, so I need a way to do something like this.
I want to make separate JS files and include them in Site.Master. But still I want to make workable code blocks like this
loadNews("<%= Model.A%>", "<%= Model.B%>");
Is there any way to do some trick?
I'm a newbie on MVC and also facing that situation. I'm dealing with it by calling the javascript functions via a script block on the view.
Something like this:
--On MyFile.js
function loadNews(a, b) {
//Do fun stuff
}
--On Index.cshtml
<script type="text/javascript">
loadNews("<%= Model.A%>", "<%= Model.B%>");
</script>
Another option could be declare the variables on the view's script block and referencing those variables on the javascript, since their scope would be global. Would be an ugly thing and a bit harder to mantain, but also could do the job. Like this:
--On MyFile.js
function loadNews() {
doSomethingWithA(a);
doSomethingElseWithB(b);
}
--On Index.cshtml
<script type="text/javascript">
var a = "<%= Model.A%>";
var b = "<%= Model.B%>";
</script>
We had the same issue previous and found a nice solution using jQuery.
Firstly, we extend jQuery with our own namespace (we placed the following in a separate JS file and included it on the masterpage):
$.extend({
myProject: {
dataitem: {},
dataitems: function (a) {
$.extend($.myProject.dataitem, a);
}
}
});
Now, whenever we have a value that we want to pass to our JS file from the ASP view, we simply add the following to the view:
<script type="text/javascript">
$.myProject.dataitems({
foo: Model.Bar,
bar: Model.Foo
});
</script>
Now, for your separate JS file (which would be included below the aforementioned <script></script> block) accessing the value is simple:
$('#foo').click(function () {
alert($.myProject.dataitem.foo);
});
Can you put the data in hidden fields, then access them with Javascript?
<%= Html.HiddenFor(x => x.A) %>
loadNews($('#A').val());
EDIT: Sorry, MVC2

passing a parameter using JSP include directive

I need to pass a parameter to a page using JSP include directive find my code below:
<script>
var gTIID
function showPlayerList(pTIID)
{
gTIID=pTIID;
$("#IdtournamentMessageMain").hide();
$("#userListFrame").show();
}
</script>
<%# include file="players_list.jsp" %>
How can I pass gTIID to players_list.jsp in the players_list.jsp page gTTID is named tiID (/player_list.htm?tiID=gTIID) ?
Thanks in advance!
since you are using the <include> directive, gTIID should already be available.
Alternately, you could set them in one of the scopes (request, session, application) and then fetch from the same scope in your other JSP.
Or, you could also use <jsp:include> and <jsp:param> to achieve this.
You'll be able to acces gTIID in players_list.jsp. There's no need to pass it as a parameter, as it's a global-scope defined variable. However, take into account that the variable is only defined and initialized in the including page, not players.jsp. If that page is referenced somewhere else, it may be undeclared.
I solved the issue using an hidden input box(id="tidhide") in the "players_list.jsp page initialized to -1 and I set it in the showplayer function, find my snippet code below:
Parent page:
function showPlayerList(pTIID)
{
gTIID=pTIID;
$("#IdtournamentMessageMain").hide();
$("#tidhide").val(pTIID);
oTable.fnDraw();
$("#userListFrame").show();
}
bye!

Categories

Resources