I would like to get the current logged in username and display it my frontend.
Currently I have a function called GetCurrentUser() that gets called when a button is clicked.
<button type="submit" onclick="GetCurrentUser()" style="margin-left: 15px;margin-top:10px; margin-bottom: 5px;background-color: black; "value="Submit">Save Selections</button><br>
function GetCurrentUser() {
var usrName ="#HttpContext.Current.User.Identity.Name.ToString()";
//var usrName = '<%HttpContext.Current.User.Identity.Name %>';
//document.getElementById("UserName").innerHTML = usrName;
console.log(usrName);}
I get the follwoingoutput in my console log--> #HttpContext.Current.User.Identity.Name
If you are seeing the literal output of "HttpContext.Current.User.Identity.Name " then your JS function is generated client side after you have lost server context.
Couple options for you:
Call back to your controller via ajax to get the username
Store the username in a read only field on page load (kinda like setting a form value) and retrieve the value via jquery or js on function call
Assign the username on page load to a global js element and just use that element in your function.
Here is an example of 2 and 3. I don't think you should worry about #1 until you fully understand why your issue is happening in the first place:
<div class="btn btn-info" onclick="GetCurrentUser()" style="margin-left: 15px;margin-top:10px; margin-bottom: 5px;background-color: black; " value="Submit">Save Selections</div><br>
<input type="hidden" name="method2" id="method2" value="#System.Security.Principal.WindowsIdentity.GetCurrent().Name">
#section scripts {
<script>
var globalSettingMethod = '#System.Security.Principal.WindowsIdentity.GetCurrent().Name';
function GetCurrentUser() {
alert(globalSettingMethod);
alert($('#method2').val());
}
</script>
}
I could get the user logged in by passing the script at the end of the document.
<%# Master Language="C#" AutoEventWireup="true" CodeBehind="Site.master.cs" Inherits="Example.SiteMaster" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
</head>
<body>
<form runat="server">
</form>
<script>
var loggedUser = "<%: HttpContext.Current.User.Identity.Name %>";
</script>
</body>
</html>
I hope you find it useful.
Related
I'm currently trying to get the live value of a Java object in Javascript to fill up some progress bar.
Here is the code in the JSP file :
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# page import="server_ihm_web.server"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<style>
#myProgress {
width: 100%;
background-color: #ddd;
}
#myBar1 {
width: 1%;
height: 30px;
background-color: #4CAF50;
}
#myBar2 {
width: 1%;
height: 30px;
background-color: #4CAF50;
}
#myBar3 {
width: 1%;
height: 30px;
background-color: #4CAF50;
}
</style>
<body>
<h1>JavaScript Progress Bar</h1>
<div id="myProgress">
<div id="myBar1"></div>
</div>
<br>
<div id="myProgress">
<div id="myBar2"></div>
</div>
<br>
<div id="myProgress">
<div id="myBar3"></div>
</div>
<%
server serv = new server();
serv.startServer();
%>
</body>
<button onclick="move()">Click Me</button>
<script>
function move() {
var elem = document.getElementById("myBar1");
var elem2 = document.getElementById("myBar2");
var elem3 = document.getElementById("myBar3");
var id = setInterval(update, 100);
function update() {
elem.style.width = <%=serv.getBar1()%> + '%';
elem2.style.width = <%=serv.getBar2()%> + '%';
elem3.style.width = <%=serv.getBar3()%> + '%';
}
}
</script>
</html>
serv values are updated every few seconds but nothing changes for the progress bar.
I think it always take the base value of the object so everytime update() is called it will change the progress bar to the same value.
Is there a way to update the values of serv for the javascript ?
I think you are mixing things that live on separate dimensions :)
Javascript executes in the browser and JAVA (JSP) on the server.
If your ideas was to have the jsp scriptlet execute in the user's browser, it is not going to happen.
If you need to update the page with a progress when it is already in the user's browser, you will have to implement some ajax call to get the updates on the background.
The JSP tags <%= ... %> are evaluated in the server, before the page is displayed the first time in a browser. So, the values of that tags are static, and don't change in each execution of the javascript functions.
For that values to change, you need to do a request to the server, and reload the page. To avoid reloading an entire page each time, you need to do an Ajax request to obtain a new value to display with Javascript.
I am working on Struts 2 application. In my application, I need to use Struts 2 autocompleter tag. For that I have used struts2-dojo-plugin-2.3.1.2.jar jar file. I need to fetch the value from autocompleter once the value changes. I tried using onchange event but it was not working. Here is my code:
<%#taglib uri="/struts-dojo-tags" prefix="sx"%>
<html>
<head>
<script type="text/javascript">
function abc() {
var a = dojo.widget.byId("country");
var value1 = a.getSelectedValue();
document.getElementById("myText").value = value1;
}
</script>
<sx:head />
</head>
<body>
<sx:autocompleter name="country"
id="country" onchange="abc();" list="cricketNations" />
</body>
</html>
How do I achieve this. Help me solve this issue.
The struts2-dojo-plugin is deprecated. You need to use struts2-jquery-plugin.
<%# taglib prefix="s" uri="/struts-tags"%>
<%# taglib prefix="sj" uri="/struts-jquery-tags"%>
<html>
<head>
<sj:head jqueryui="true"/>
</head>
<body>
<div id="myText" class="result ui-widget-content ui-corner-all"></div>
<sj:autocompleter name = "country"
id = "country"
onChangeTopics = "autocompleteChange"
list = "%{cricketNations}" />
<script>
$.subscribe('autocompleteChange', function(event, data) {
var ui = event.originalEvent.ui;
var message = ui.item.value;
if (ui.item.key) {
message = '( '+ ui.item.key +' ) '+message;
}
$('#myText').html('<b>'+message+'</b>');
});
</script>
</body>
</html>
You might not be able to use HTML attributes with dojo widgets, you need to use dojo topics to subscribe for an event:
<%#taglib uri="/struts-dojo-tags" prefix="sx"%>
<html>
<head>
<script type="text/javascript">
dojo.event.topic.subscribe("/countryName", function(value, key, text, widget){
alert('inside onchange');
document.getElementById("myText").value = value;
});
</script>
<sx:head />
</head>
<body>
<sx:autocompleter name="country" valueNotifyTopics="/countryName" list="cricketNations" />
</body>
</html>
When value is selected for sx:autocompleter, topics will be published. See autocompleter doc here.
I used jquery getJSON method to get the two strings from java servlet. one string contains the type of data like simple string, XML and HTML and another string contains data. I need to open a popup window with different size based on contents.
Below the code used to get the strings.
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>AJAX calls using Jquery in Servlet</title>
<script src="http://code.jquery.com/jquery-latest.js"> </script>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
<script src="https://code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
<script>
$(document).ready(function() {
$('#submit').click(function(event) {
var applid=$('#applicationid').val();
var applname=$('#appname').val();
$.getJSON('ActionServlet',
{
appid:applid,
appname:applname
},function(data) {
var errortype = data.errortype;
var errorMsg = data.errorMsg;
});
});
});
</script>
</head>
<body>
<form id="form1">
<h1>AJAX Demo using Jquery in JSP and Servlet</h1>
Enter your Name:
<input type="text" id="applicationid"/>
<input type="text" id="appname"/>
<input type="button" id="submit" value="Ajax Submit"/>
<br/>
<div id="hello" title="Hello World!"></div>
</form>
</body>
</html>
You can user fancybox. It gives options for opening the passed html string check here
To open a new window you can use the window.open() function.
To display the XML as raw text, you need to escape the special characters.
Javascript does not have builtin function for it (like htmlentities() in php).
You can try the following code:
function htmlentities(str)
{
return String(str).replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"');
}
For example in page1.html I have:
<input type="radio" id="id1" onclick="change()">Radio Button</input>
In page2.html I have :
Link
Clicking the radio button on page1.html should change the value of the href attribute in page2.html.
Javascript (js_file.js):
function change()
{
if(document.getElementById(id1).checked)
{
document.getElementById(id2).href="page4.html";
}
}
This code will not work since id1 and id2 do not exist on the same page.
Is there any method where 2 or more html pages can simultaneously access a javascript function?
Assuming I have included this :
<script src="js_file.js" type="text/javascript" />
in both the HTML pages within the head tag.
I am trying to avoid server side programming as it is an embedded web server and can only be programmed in C language.
Try this on for size.
Page1.html
<!DOCTYPE html>
<html>
<head>
<script>
window.addEventListener('load', onDocLoaded, false);
function onDocLoaded()
{
var urlRadios = document.getElementsByName('urlSelector');
var i, n = urlRadios.length;
for (i=0; i<n; i++)
urlRadios[i].addEventListener('click', onUrlRadioChange, false);
}
function onUrlRadioChange(evt)
{
localStorage.destUrl = this.getAttribute('dest');
localStorage.destTxt = this.getAttribute('msg');
}
</script>
<style>
</style>
</head>
<body>
<h3>Pick destination of link on page 2</h3>
<input type='radio' msg='No page selected' dest='none' checked name='urlSelector'>none</input>
<input type='radio' msg='Page 3' dest='page3.html' name='urlSelector'>page3.html</input>
<input type='radio' msg='Page 4' dest='page4.html' name='urlSelector'>page4.html</input>
<hr>
<a href='page2.html'>Page 2</a>
</body>
</html>
Page2.html
<!DOCTYPE html>
<html>
<head>
<script>
function byId(e){return document.getElementById(e);}
window.addEventListener('load', onDocLoaded, false);
function onDocLoaded()
{
if (localStorage.destUrl != 'none')
byId('tgtLink').href = localStorage.destUrl;
byId('tgtLink').innerHTML = localStorage.destTxt;
}
</script>
<style>
</style>
</head>
<body>
<h3>Destination was set by page 1</h3>
<a id='tgtLink'>Link</a>
</body>
</html>
The only way that you can do this is by passing data between pages using hidden HTML elements.
Page1
<input type="radio" name="radio1" id="radio1" onclick="change.js">Radio Button</input>
Page2
<input type="hidden" name="radio1" value="XXX">
Of course, you'll have to have Page1 upload the form to the server, and have the server generate Page2 with the hidden elements populated.
Another solution which might work if the structure of the sites allow this: window.opener
Let's say page 1 opens page 2 as a popup (so both windows are kept opened), then you could access everything from page 1 through window.opener.
You can even test this here. Open any link on this site (whithin the domain of stackoverflow, else that would be XSS) in a new window, then open the JavaScript console of that new window and enter: window.opener.document.title = "YAY!"
At least that's an easy way to avoid using local storage etc.
I am getting started with backbone.js but it seems i am not able to get the first hand code correct. I looked up all the resources but cant figure out what is the problem.
I was expecting changed event getting fired every time i change something in the input box and finally when i click the button, it should fire someAction function. There are no JavaScript errors but nothing happens. no change or click event getting fired.
Can someone please tell me what am i missing here?
Aspx Page:
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs"
Inherits="_Default" %>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Untitled Page</title>
<script src="jquery-1.7.1.min.js" type="text/javascript"></script>
<script src="jquery-ui-1.8.18.custom.min.js" type="text/javascript"></script>
<script src="underscore.js" type="text/javascript"></script>
<script src="Backbone.js" type="text/javascript"></script>
<script type="text/javascript">
$(function() {
Person = Backbone.Model.extend({
el: '#form1',
events : {
"click #DoSomething": "someAction"
},
initialize: function(){
//This will bind change event of input controls to below function
_.bindAll(this, "changed");
},
//This function will be fired whenever value in the input is changed
changed: function(evt) {
var target = $(evt.currentTarget),
data = {};
data[target.attr('name')] = target.attr('value');
this.model.set(data);
alert('Model Updated')
},
//take some action on click of a button
someAction: function(){
var fName = this.model.get('FirstName');
var lName = this.model.get('LastName');
alert("First Name" + fName + " Last Name " + lName);
return false;
}
});
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<span>First Name</span>
<input type="text" name="FirstName" id="txtFirstName" value="Mark" />
<span>Last Name</span><input type="text" name="LastName" id="txtLastName" value="Waugh" />
<input type="button" id="DoSomething" value="Login Here" />
</div>
</form>
</body>
</html>
All of your functionality should be in a view not a model.
Change Person = Backbone.Model.extend to PersonView = Backbone.View.extend. Now you actually have to create an instance of the view.
$(function() {
PersonView = Backbone.View.extend({
...
});
window.personview = new PersonView();
});
_.bindAll(this, "changed"); won't bind to the changed event. You need to add 'change input': 'changed' to your events list. The bindAll isn't needed at all.
Also, I believe this.model is undefined. I think you should be using this.set(data) instead of this.model.set(data).
Relevant fiddle (this is not mine but it works)
http://jsfiddle.net/thomas/C9wew/4/