Activate javascript string onload on code behind C# - javascript

Good day!
I need a help on activating my javascript function via on-load on code behind.
Here is my code:
string script = #"var applyCss = function () {
var css = '#CalendarPanel1-month-day-20170607, #CalendarPanel1-month-day-20170614 {background-color: #D0D3D4;}';
Ext.net.ResourceMgr.registerCssClass('someCssClassId', css);
}; ";
ScriptManager.RegisterClientScriptBlock(this, typeof(Page), "css", script, true);
By the way, my code above works in front-end via button click.
But my desired result is, I want my javascript function to work on page load without needing to click the button. I put my javascript function in code-behind because I will put dynamic dates in the css variables. The code above still has static variables. (CalendarPanel1-month-day-20170607)
Will gladly appreaciate any response / solution. Big thanks!

You could use an immediately invoked function to do the trick. Basically you don't give a name to your javascript function and you invoke it right after it's defined.
For example:
var script = #"(function () {alert('Hello');})(); ";
ScriptManager.RegisterStartupScript(this, typeof(Page), "123", script, true);
You need to wrap the function with its body between parenthesis then another set of parenthesis to invoke the function.
You can also pass parameters to your function (which I'm assuming it's what you want to do):
var myAlertText = "Hello Hello";
var script = #"(function (myText) {alert(myText);})('" + myAlertText + "');" ;
If I were you though I would defined the function in client code and just invoke it from code behind with the right parameters.

An alternative and fancier way to call javascript code from code behind would be using X.Call(). Check out this example:
<%# Page Language="C#" %>
<!DOCTYPE html>
<script runat="server">
protected void Page_Load(object sender, EventArgs e)
{
if (!X.IsAjaxRequest)
{
string script = #"var myJSSideVar = 'my var value';
var applyCss = function (paramOne, paramTwo) {
var css = '#CalendarPanel1-month-day-20170607, #CalendarPanel1-month-day-20170614 {background-color: #D0D3D4;}';
Ext.net.ResourceMgr.registerCssClass('someCssClassId', css);
Ext.Msg.alert('applyCss called.', 'I\'ve been run with parameters: (' + paramOne + ', ' + paramTwo + ').');
};";
var hi = "hello";
X.AddScript(script);
X.Call("applyCss", new object[] { hi, new JRawValue("myJSSideVar") });
}
}
</script>
<html>
<head runat="server">
<title></title>
</head>
<body>
<form runat="server" id="form1">
<div>
<ext:ResourceManager runat="server" />
</div>
</form>
</body>
</html>
Notice the second parameter sent to the script call is sent "raw", i.e., it calls: applyCss("hello", myJSSideVar)
If you need to pass but one single parameter you don't need to pass an array, e.g. X.Call("applyCss", hi);

Related

Cannot access javascript function in ADF InlineFrame

I have a jsff page containing af:InlineFrame.
The source of this InlineFrame is HTML file say Frame.html
This html file has a javascript function called inlineframeFunction()
I have a button added in the jsff page.
My usecase is to invoke the function inlineframeFunction on click of the button which i am not able achieve.
var doc = inlineFrame.contentDocument?
inlineFrame.contentDocument: inlineFrame.contentWindow.document;
doc.frameFunction();
Frame.html
<script type="javascript">
function inlineframeFunction(){
alert('Inline Frame Function ');
}
</script>
JSFF Page
<af:panelGroupLayout id="pgl1" layout="vertical">
<af:resource type="javascript">
function inlineFrameRegionPageFunction() {
alert('Region Page Function');
var inlineFrame = document.getElementById('r1:0:if2');
var doc = inlineFrame.contentDocument? inlineFrame.contentDocument: inlineFrame.contentWindow.document;
doc.frameFunction();
}
</af:resource>
</af:panelGroupLayout>
<af:panelGroupLayout id="pgl2" layout="vertical">
<af:panelBox text="Inline Frame Region" id="pb2"
inlineStyle="background-color:Lime; border-color:Lime;">
<f:facet name="toolbar"/>
<af:inlineFrame id="if2" source="/Frame.html" shortDesc="InlineFrame"
inlineStyle="background-color:Gray;"/>
<af:commandButton text="Inline Region Button" id="rb2"
actionListener="#{pageFlowScope.RegionBean.onClickInlineFrameRgnButton}"/>
</af:panelBox>
</af:panelGroupLayout>
I used the following and it worked!
function inlineFrameRegionPageFunction() {
var frameComp =$('[id*="InlineFrame"]', document)[0].id;
document.getElementById(frameComp).contentWindow.frameFunction();
}
</af:resource>
To execute a javascript from a managed bean in adf you can use the following function (https://cedricleruth.com/how-to-execute-client-javascript-in-an-adf-java-bean-action/) :
/*** In YOURJSF.jsf button, or other component that need to execute a javascript on action, add : ****/
<af:commandButton text="ClickMe" id="cb1" actionListener="#{YOURSCOPE.YOURJAVABEAN.clickToExecuteJavascriptAction}"/>
/*** In YOURJAVABEAN.java class add : ***/
public void clickToExecuteJavascriptAction(ActionEvent actionEvent) {
this.executeClientJavascript("console.log('You just clicked : " + actionEvent.getSource() + " ')");
//Note: if you use a java string value in this function you should escape it to avoid breaking the javascript.
//Like this : stringValue.replaceAll("[^\\p{L}\\p{Z}]", " ")
}
//You should put this function in a util java class if you want to use it in multiple bean
public static void executeClientJavascript(String script) {
FacesContext facesContext = FacesContext.getCurrentInstance();
ExtendedRenderKitService service = Service.getRenderKitService(facesContext, ExtendedRenderKitService.class);
service.addScript(facesContext, script);
}
Then in your case, refer to this question to call your iframe js function using javascript inside your action listener (Calling javascript function in iframe)
document.getElementById("if2").contentWindow.inlineframeFunction();

Accessing java variable from javascript in spring mvc

i am relatively new to spring mvc.what i am trying to do is pass a variable as model attribute and try and access it on page load with javascript on my JSP page.
my java code is as follows
model.addAttribute("leagueCode",leagueCode);
model.addAttribute("league","new");
return "redirect:/Dashboard";
and on jsp side i am trying to access it by following
<script type="text/javascript"> function myFunction() { var leagueCode=${leagueCode}; alert(leagueCode); } </script> </head> <body onload="myFunction()">
but i am getting the value as blank. is this the right way i am following or is there any other way this has to be done? please help
In the JSP page you can set the values as javascript variables by adding a script tag in the <head> with the assignment inside as a json object for example:
<script>
var myServerSideVars = {
"aServerSideVarName" : "<here you set the value with el/jslt/scriptlet>",
"anotherServerSideVarName" : "<here you set the value with el/jslt/scriptlet>"
};
</script>
EDIT I
Example using EL (Expression Language) but the same could be done with scriptlets if you are using that (<% %>):
Lets say in your Servlet you put a Car instance in the request before forwarding to the JSP page.
The car:
public class Car{
protected String brand;
protected String year;
//getters and setters for the two properties.
}
In the Servlet you put it into the request:
Car car = new Car();
car.setBrand("BMW");
car.setYear("2017");
request.setAttribute("carInRequest", car);
In the JSP you set it to a Json Object accessible from javascript. Before closing the body tag I put a simple example of how the var can be accessed from javascript. I haven't run it so it may have some typo or error to correct:
<%#taglib prefix = "c" uri = "http://java.sun.com/jsp/jstl/core" %>
<html>
<head><title>System.out.println</title>
<script>
var aCar= {
"brand" : "${requestScope.carInRequest.brand}",
"year" : "${requestScope.carInRequest.year}"
};
</script>
</head>
<body>
<h2>Brand: <span id="brandPlaceHolder"></span></h2>
<h2>Year: <span id="yearPlaceHolder"></span></h2>
</body>
<script>
var brandSpan = document.findElementById("brandPlaceHolder");
brandSpan.html = aCar.brand;
var yearSpan = document.findElementById("yearPlaceHolder");
brandSpan.html = aCar.year;
</script>
</html>

Getting session value in javascript

I am using an external javascript file for my asp.net project. Now i want to get the session value in that javascript. How can i get the session value in that javascript file?
Thanks in advance..
<script>
var someSession = '<%= Session["SessionName"].ToString() %>';
alert(someSession)
</script>
This code you can write in Aspx. If you want this in some js.file, you have two ways:
Make aspx file which writes complete JS code, and set source of this file as Script src
Make handler, to process JS file as aspx.
You can access your session variable like '<%= Session["VariableName"]%>'
the text in single quotes will give session value.
1)
<script>
var session ='<%= Session["VariableName"]%>'
</script>
2) you can take a hidden field and assign value at server;
hiddenfield.value= session["xyz"].tostring();
//and in script you access the hiddenfield like
alert(document.getElementbyId("hiddenfield").value);
For me this code worked in JavaScript like a charm!
<%= session.getAttribute("variableName")%>
hope it helps...
I tried following with ASP.NET MVC 5, its works for me
var sessionData = "#Session["SessionName"]";
protected void Page_Load(object sender, EventArgs e)
{
Session["MyTest"] = "abcd";
String csname = "OnSubmitScript";
Type cstype = this.GetType();
// Get a ClientScriptManager reference from the Page class.
ClientScriptManager cs = Page.ClientScript;
// Check to see if the OnSubmit statement is already registered.
if (!cs.IsOnSubmitStatementRegistered(cstype, csname))
{
string cstext = " document.getElementById(\"TextBox1\").value = getMyvalSession() ; ";
cs.RegisterOnSubmitStatement(cstype, csname, cstext);
}
if (TextBox1.Text.Equals("")) { }
else {
Session["MyTest"] = TextBox1.Text;
}
}
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<script language=javascript type="text/javascript">
function getMyvalSession() {
var txt = "efgh";
var ff = '<%=Session["MyTest"] %>' + txt;
return ff ;
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:TextBox ID="TextBox1" runat="server" AutoPostBack=true ></asp:TextBox>
<input type="submit" value="Submit" />
</div>
</form>
</body>
</html>
If you are using VB as code behind, you have to use bracket "()" instead of square bracket "[]".
Example for VB:
<script type="text/javascript">
var accesslevel = '<%= Session("accesslevel").ToString().ToLower() %>';
</script>
var sessionVal = '#Session["EnergyUnit"]';
alert(sessionVal);

Saving javascript variable in server side variable (vbscript)

I know you cant save javascript variables into server side variables (vbscript) directly, but is there a way around this like saving java script variables into html hidden inputs then using javascript to post. Is this possible? If not what else can i do? Below is my code so far get the value of a drop down list - javascript
function selectedDatabase() {
select_temp = form1.elements["selection"];
select_index = select_temp.selectedIndex;
select_text = select_temp.options[select_index].text;
}
Below is the HTML code
<center><select id="selection" onchange="selectedDatabase()">
<option>Movies</option>
<option>Movies 2</option>
<option>New Movies</option>
<option>New Movies 2</option>
</select></center>
</td></tr>
What you're looking for is called ajax. You can do it manually, or better use a JavaScript library such as MooTools, jQuery, or Prototype.
Check out Google University's Ajax tutorial. I would avoid w3schools' tutorials.
Just to cover all the bases, why can't you just have the user submit the form?
Also, you could do this with cookies, though you won't get the cookie values on the server until the next GET or POST from the user.
It is Possible to store javascript variable values into server side variable. All you have to do is to implement "System.Web.UI.ICallbackEventHandler" class.
Below is the code demonstrating how to do it.
In aspx Page:
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>Client Calback Example</title>
<script type="text/ecmascript">
function LookUpStock()
{
var lb=document.getElementById("tbxPassword");
var product=lb.value;
CallServer(product,"");
}
function ReceiveServerData(rValue){
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<input type="password" id="tbxPassword" />
<input type="Button" onclick="LookUpStock">Submit</button>
</div>
</form>
</body>
**
In Code Behind (CS) Page
**
public partial class _Default : System.Web.UI.Page,System.Web.UI.ICallbackEventHandler
{
protected String returnValue;
protected void Page_Load(object sender, EventArgs e)
{
String cbReference = Page.ClientScript.GetCallbackEventReference
(this,"arg", "ReceiveServerData", "context");
String callbackScript;
callbackScript = "function CallServer(arg, context)" +
"{ " + cbReference + ";}";
Page.ClientScript.RegisterClientScriptBlock(this.GetType(),
"CallServer", callbackScript, true);
}
public void RaiseCallbackEvent(String eventArgument)
{
if(eventArgument == null)
{
returnValue = "-1";
}
else
{
returnValue = eventArgument;
}
}
public String GetCallbackResult()
{
return returnValue;
}
}
Now you can get the JavaScript variable "product" value into Server side variable "returnValue".

Pass variable to external JS file?

Is it possible to pass a variable to a linked .js file? I tried this:
<sf:JsFileLink ID="JQueryLoader" runat="server" ScriptType="Custom" FileName="~/Files/Scripts/rotatorLoader.js?timeout=1000" />
But firebug is telling me that timeout is not defined. Here is the code for that .js file:
$(document).ready(function() {
$("#rotator > ul").tabs({ fx: { opacity: "toggle"} }).tabs("rotate", timeout, true);
});
I am using <sf:JsFileLink ... /> tag is because the website I am working in utilizes sitefinity and this tag allows me to load external .js files.
UPDATE:
I was able to 'trick' the include by creating an aspx page that emulates a javascript page:
<%# Page Language="C#" %>
<%
Response.ContentType = "text/javascript";
Response.Clear();
string timeout;
try
{
timeout = Session["timeout"].ToString();
}
catch
{
timeout = "4000";
}
%>
$(document).ready(function() {
$("#rotator > ul").tabs({ fx: { opacity: "toggle"} }).tabs("rotate", <%=timeout %>, true);
});
And on the user control page:
[DefaultProperty("BannerTimeout")]
public partial class Custom_UserControls_TabbedRotator : System.Web.UI.UserControl
{
[Category("Configuration")]
[Description("Sets the rotation timeout, in seconds.")]
[DisplayName("Banner Timeout")]
public int BannerTimeout { get; set; }
protected void Page_Load(object sender, EventArgs e)
{
Session.Add("timeout", (BannerTimeout*1000));
}
}
This achieved what I was looking for, and maybe this method can help someone else out.
try this:
<script>
var myvariable = "foo";
</script>
<script src="/link/to/js.js"></script>
No, you can't pass parameters like that and have the script read them in.
Technically you could grab them from the <script> tag, but that would be a real mess.
Could you just output a script block before you include the file?
<script type="text/javascript"> var timeout = 1000; </script>
<script type="text/javascript">
var imagesPath = "emblematiq/img/";
</script>
<script type="text/javascript" src="emblematiq/niceforms.js"></script>
This will work fine on server
No, but you can pass a the value directly to a function in that file or set a variable value that will be used in the external file.

Categories

Resources