How to access javascript value in a4j - javascript

I need to set a Bean value with one javascript return value.
Something like:
<script type="text/javascript">
function getUserId(){
return 4;
}
</script>
<h:inputText name="lala" value="getUserId()"/>
Thanks

I solved it.
I was using a:jsFunction tag as it follows:
<script type="text/javascript">
function getUserId(){
var user = MyCompany.get_User();
return user;
}
</script>
<a:jsFunction action="#{user.performLogin()}" name="doSiteLogin" >
<a:actionparam name="uid" value="getUserId()"/>
</a:jsFunction>
If you use the property noEscape="true" on the a:actionparam ... it call your javascript code.

Related

How to pass values to an external Javascript script from ASP.NET

I have a set of KPI data I need to pass over to a Javascript file from my ASP.NET project. I thought I could do so using a ViewBag... Here is what is in the controller:
public ActionResult KPI()
{
if (Session["OrganizationID"] == null)
{
return RedirectToAction("Unauthorized", "Home");
}
else
{
int orgId;
int.TryParse(Session["OrganizationID"].ToString(), out orgId);
var user = db.Users.Find(User.Identity.GetUserId());
var organization = user.Organizations.Where(o => o.OrganizationID == orgId).FirstOrDefault();
var reports = db.Reports.ToList();
try
{
var org_reports = (from r in reports
where r.OrganizationID == organization.OrganizationID
select r).ToList();
var kpi = new KPI(org_reports);
var jsonKPI = JsonConvert.SerializeObject(kpi);
ViewBag.orgData = jsonKPI;
}
catch (ArgumentNullException e)
{
return RedirectToAction("Unauthorized", "Home");
}
}
return View();
}
From the View I've tried using hidden values, and also just passing them in as parameters when calling the script:
<input type="hidden" id="orgData" value=#ViewBag.orgData>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript" src="~/Scripts/KPIs.js">
orgData = #ViewBag.orgData;
</script>
I then want to read this value in my JS script and parse it into JSON from the string:
function myFunction(){
var test1 = JSON.parse(document.getElementById('orgData'); // Doesn't work
var test2 = JSON.parse(orgData); // Doesn't work
}
It doesn't appear that any of these methods are working. What is my mistake here?
You should use Html.Raw, to avoid ASP.NET to escape your value:
orgData = #Html.Raw(ViewBag.orgData);
Also, if this is a Json, it is also a valid JS object, so you don't need to parse, it already is a JS Object.
It looks like you forgot the quotes.
<input type="hidden" id="orgData" value=#ViewBag.orgData>
should be
<input type="hidden" id="orgData" value="#ViewBag.orgData">
Also the code inside your script tag will never get executed because the script tag has a src attribute on it. Code inside script tags with src attributes never gets executed.
<script type="text/javascript" src="~/Scripts/KPIs.js">
orgData = #ViewBag.orgData;
</script>
should be changed to
<script type="text/javascript" src="~/Scripts/KPIs.js" />
<script>
orgData = #ViewBag.orgData;
</script>
I solved it! Pass the KPI model through the view and then it's as easy as:
var orgData = #Html.Raw(Json.Encode(Model));
Thanks to all to offered help.

External vs Internal JS - MBean value

I'm having trouble getting values from MBean when my javascript is in an external file.
Example:
<script src='scripts/externaljs.js' type='text/javascript' />
<script>
getString();
<script>
//externaljs.js
function getString(){
var string = "#{testMBean.getName()}";
alert(string);
}
It always returns "#{testMBean.getName()}" instead of the string value.
But if I declare it inside my .xhtml file it returns the proper value.
<script>
var string = "#{testMBean.getName()}";
alert(string);
</script>
Am I doing anything wrong here?
This is because your MBean value is only substituted in your view. If you want your external JavaScript file to see those values you can store them in an array / object, or pass them as arguments.
<script>
var mBeanValues = {
string: "#{testMBean.getName()}"
}
</script>
<script src="external.js></script>
<script>
getString()
</script>
=====
// external.js
function getString() {
alert(mBeanValues.string)
}
OR
<script src="external.js"></script>
<script>
getString("#{testMBean.getName()}")
</script>
=====
// external.js
function getString(string) {
alert(string)
}

How do I assign the result of a function into a global variable?

I can't figure out how to assign this function's result into a global variable. I know this is a really basic thing, but can anyone help?
var pixel_code = null
function captureValue(){
pixel_code = document.getElementById("baseText").value;
return pixel_code;
}
pixel_code = captureValue();
Thanks for sharing the jsfiddle of what you were attempting. I see the concern. The captureValue() function is run asynchronously, so the console.log() shortly after defining it doesn't yet have a value. I've stripped and prodded the jsfiddle and come up with this working sample:
<html>
<head>
</head>
<body>
<h1>Welcome to the AdRoll SandBox</h1>
<textarea id="baseText" style="width:400px;height:200px"></textarea><br />
<input type="button" value="test" id="text_box_button" onclick="captureValue()"/>
<input type="button" value="get" id="text_box_button2" onclick="getValue()"/>
<script>
var pixel_code = null;
function captureValue(){
pixel_code = document.getElementById("baseText").value;
return false;
}
function getValue() {
alert(pixel_code);
return false;
}
</script>
</body>
</html>
I added a second button. Type in the textbox, push "test" (to set the value), then push "get" to get the value of the global variable.
Here's the same sample that uses jQuery and a closure to avoid the global variable:
<html>
<head>
</head>
<body>
<h1>Welcome to the AdRoll SandBox</h1>
<textarea id="baseText" style="width:400px;height:200px"></textarea><br />
<input type="button" value="test" id="text_box_button" />
<input type="button" value="get" id="text_box_button2" />
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script>
$(document).ready(function () {
var pixel_code = null;
$("#text_box_button").click(function (){
pixel_code = document.getElementById("baseText").value;
return false;
});
$("#text_box_button2").click(function () {
alert(pixel_code);
return false;
});
});
</script>
</body>
</html>
If the page reloads, your variable will be reset to it's initial state.
You're reusing pixel_code in and out of the function, which is not a great pattern, but the code you show should work as expected. What error are you seeing? What code surrounds this code that you're not showing? Could all this perhaps be nested inside another function? (Thanks #JosephSilver for the nod.)
Please try this,
var pixel_code='';
function captureValue(){
return document.getElementById("baseText").value;
}
function getValueBack()
{
pixel_code = captureValue();
//alert(pixel_code); /* <----- uncomment to test -----<< */
}

getElementById in 3 ways

I have an application that needs to retrieve a value out of a hidden input form field. However, this application has a base page which calls another page that is in an iFrame and then it also can call itself inside another iFrame:
default.asp -> screen.asp (in iFrame)
screen.asp -> a new instance of screen.asp (in iFrame)
document.getElementById('focusValue').value
window.frames[0].document.getElementById('focusValue').value
parent.frames[arrVal].document.getElementById('focusValue').value
When I reference the hidden input form field from default -> screen I can use the standard document.getElementById('focusValue').value;. Then when I'm in the 1st level iFrame I have to use window.frames[0].document.getElementById('focusValue').value;. Then when I'm in the 2+ levels in an iFrame I have to use the parent.frames[arrVal].document.getElementById('focusValue').value;.
A common structure that I'm starting to see is this:
if(document.getElementById('focusValue') == undefined){
window.frames[0].document.getElementById('focusValue').value = focusValue;
console.log('1');
}else if((parent.frames.length -1) == arrVal){
console.log('2');
if (arrVal > 0) {
parent.frames[arrVal].document.getElementById('focusValue').value = focusValue;
}
}else{
document.getElementById('focusValue').value = focusValue;
console.log('3');
}
Now I can certainly do this but outside of writing a novel worth of comments I'm concerned with other programmers(or me 1 month from now) looking at this code and wondering what I was doing.
My question is there a way to achieve what I'm looking to do in a standard form? I'm really hoping that there is a better way to achieve this.
I would suggest you have each page do the work of finding the value you want by calling a method. Basically exposing a lookup interface. Then you only need to call a method on the target page from the parent page. Proper naming will help developers understand what is going on and using methods will simplify the logic.
Or if you only need to get the value from the parent page, then you could register a hook with each page in an iframe using a common interface. Each page can just call that hook to get the value. This prevents your complex logic of determining what level the page is. Something like
iframe1.GetValueHook = this.GetValue;
iframe2.GetValueHook = this.GetValue;
Then each page can just call
var x = this.GetValueHook();
If you have nested pages, you could make this recursive. If you need communication between all pages then use the same approach but with a registration process. Each page registers itself (and it's children) with it's parent. But if you need to do this then you should reevaluate your architecture.
Example:
register.js
var __FRAMENAME = "Frame1";
var __FIELDID = "fieldId";
var __frames = [];
function RegisterFrame(frame) {
__frames.push(frame);
for (var i = 0; i < frame.children.length; i++) {
__frames.push(frame.children[i]);
}
RegisterWithParent();
}
function RegisterWithParent() {
var reg = {
name: __FRAMENAME,
getvalue: GetFieldValue,
children: __frames
};
if(parent != undefined && parent != this) {
parent.RegisterFrame(reg);
}
}
function SetupFrame(name, fieldId) {
__FRAMENAME = name;
__FIELDID = fieldId;
RegisterWithParent();
}
function GetFieldValue() {
return document.getElementById(__FIELDID).value;
}
function GetValueFrom(name) {
for (var i = 0; i < __frames.length; i++) {
if (__frames[i].name == name) {
return __frames[i].getvalue();
}
}
}
index.html
<html>
<head>
<script language="javascript" type="text/javascript" src="register.js"></script>
</head>
<body>
PAGE
<input type="hidden" id="hid123" value="123" />
<iframe id="frame1" src="frame1.html"></iframe>
<iframe id="frame2" src="frame2.html"></iframe>
<script type="text/javascript">
SetupFrame("Index", "hid123");
setTimeout(function () { //Only here for demonstration. Make sure the pages are registred
alert(GetValueFrom("frame3"));
}, 2000);
</script>
</body></html>
frame1.html
<html>
<head>
<script language="javascript" type="text/javascript" src="register.js"></script>
</head>
<body>
<input type="hidden" id="hid" value="eterert" />
<script type="text/javascript">
SetupFrame("frame1", "hid");
</script>
</body></html>
frame2.html
<html>
<head>
<script language="javascript" type="text/javascript" src="register.js"></script>
</head>
<body>
<input type="hidden" id="hid456" value="sdfsdf" />
<iframe id="frame2" src="frame3.html"></iframe>
<script type="text/javascript">
SetupFrame("frame2", "hid456");
</script>
</body></html>
frame3.html
<html>
<head>
<script language="javascript" type="text/javascript" src="register.js"></script>
</head>
<body>
<input type="hidden" id="hid999" value="bnmbnmbnm" />
<script type="text/javascript">
SetupFrame("frame3", "hid999");
</script>
</body></html>
This would be better if you can change it up to use a dictionary/hash tbale instead of loops.
Your best bet will be to set varables named correctly so it's self documenting. Something like this...
var screenFrame = window.frames[0];
var screenFrame2 = parent.frames[arrVal];
var value = screenFrame2.document.getElementById('focusValue').value
This will make it easier to read.
If you really must search frames for a given element, then you should just make your own function to do that and use that function everywhere. Put a lot of comments in the function explaining why/what you're doing and give the function a meaningful name so it will be more obvious to future programmers looking at your code what you are doing or where they can look to find what you are doing.
function setValueByIdFrames(name) {
if(document.getElementById(name) == undefined){
window.frames[0].document.getElementById(name).value = name;
console.log('1');
} else if((parent.frames.length -1) == arrVal){
console.log('2');
if (arrVal > 0) {
parent.frames[arrVal].document.getElementById(name).value = name;
}
} else {
document.getElementById(name).value = name;
console.log('3');
}
}

JSF. How to set a value of JavaScript function to a field of Bean?

Good morning! How to set a value of JavaScript function to a field of Enterprice Java Bean?
I have the js function:
<script type="text/javascript">
function getTimezone() {
var d = new Date()
var gmtMinutes = -d.getTimezoneOffset();
return gmtMinutes;
}
</script>
I'm trying to use:
<a4j:jsFunction name="timezone" assignTo="MyBean.gmtMinutes">
<a4j:actionparam name="timezone" value="getUserId()"/>
</a4j:jsFunction>
But I did not get. I think that I incorrectly used the tag a4j:jsFunction. Give me advice please how to use the tag correctly!
You can register a jsFunction which sends parameter's value to server:
<a4j:jsFunction name="updateTimeZone">
<a4j:param name="timezone" assignTo="#{MyBean.gmtMinutes}"/>
</a4j:jsFunction>
And then invoke that jsFunction from JavaScript:
<script type="text/javascript">
function sendTimezoneToServer() {
var d = new Date()
var gmtMinutes = -d.getTimezoneOffset();
updateTimeZone(gmtMinutes);
}
</script>
There is also an example of the same on RichFaces Showcase:
http://richfaces-showcase.appspot.com/richfaces/component-sample.jsf?demo=jsFunction&skin=blueSky

Categories