I am able to get the value of '${currentNode.identifier}' in JSP javascript functions.
When I put the same js function and try to access the '${currentNode.identifier}' inside clientlibs javascript file , it simply outputting the string. not the actual identifier.
**
How to access the current node identfier inside a client libe js file
or inside a listener js function ?
**
I appreciate all the help.
Thanks,
Sri
As rakhi already mentioned in the comment: JavaScripts are delivered "as is" and are not executable servlets like JSPs. So there will be no replacement of scriptlets and ${} attributes. So the easiest way is to have a data attribute on a DIV or any other HTML element which is rendered by a JSP:
<div data-nodeid="${currentNode.identifier}"></div>
Then you could use a jQuery selector to get the value on load:
jQuery(function() {
jQuery('div[data-nodeid]').each(function() {
var nodeId = jQuery(this).data('nodeid');
//do something with the id
});
}
Related
This may be really basic, but help would be appreciated.
I have the following script that can be added to a custom built web application and embeds within it another page in an iframe.
$(function() {
$('#customframe').after('<iframe src="https://www.myurl.com" style="width:100%;height:200px"></iframe>');
});
I need to include a query parameter to the iframe like below
$(function() {
$('#customframe').after('<iframe src="https://www.myurl.com/page.html?id=ThisRecordId" style="width:100%;height:200px"></iframe>');
});
ThisRecordId variable is already available in the DOM.
If I go to the browser console and just type ThisRecordId it displays the value I need for the iFrame.
I am just struggling to get it to work.
Thanks in advance.
Use string interpolation for string literals,
use backticks instead of quotes and enclose variable in ${ThisRecordId} template
More about template literals here.
Example:
let ThisRecordId = 'myidnumber'
$(function() {
$('#customframe').after(`<iframe src="https://www.myurl.com/page.html?id=${ThisRecordId}" style="width:100%;height:200px"></iframe>`);
});
Suppose I go
$( '#' + subform_id ) .load( "subform.php" );
where '#' + subform_id is the ID of a DIV
... is there any way the PHP in subform.php can find out, within its PHP code, the identity of the DIV? (e.g. using its own JS code <script> section)
Or otherwise refer to it by some mechanism without knowing its ID? (e.g. to use JQ's append())
Obviously I could pass the subform_id as a param of the data object (2nd param of load()). But I'm just wondering...
later
followed up on what I thought Victor2748 was suggesting... but in fact it was the ID of a <SCRIPT> block in the injected file which I used to gain access to the existing JS DOM.
Victor2748: if you read this, I'm not sure how you could know the "id of the parent container of your subform.php page" without somehow passing this id as a param in the load() function's data object...
even later
Every comment in this thread says something intelligent! In fact, concerning the question of specifying that this is a PHP file, I'm still trying to get my head around something: obviously it is possible to access the DOM when JS runs in the client. But if your PHP code needs to know the name of the DIV into which it's being loaded I believe you do indeed have to pass this through _POST or _GET. I think there are many reasons why injected PHP code might need this sort of info, e.g. so it can contain code which at some point injects more PHP into the same DIV...
Although... clearly that injection code will inevitably use a JS/JQ script, so maybe that would be the appropriate time to find out what you need about where you are in the DOM.
In JavaScript, you can use this.parentNode to get the parent container, and use this.parentNode.id to get the parent div's id.
Here is an example how your loaded block can get itself as an object/node:
var loadedBlock = document.getElementById("nameOfYourDownloadedParentContainer")
Then you can use loadedBlock.parentNode to get its parent element, then you can get any parameter from it, to identify the element/div.
Update:
First you need to get the node of the current executing <script> tag:
var arrScripts = document.getElementsByTagName('script');
var currentScriptTag = arrScripts[arrScripts.length - 1];
Then, to get the parent of the script tag, use: currentScriptTag.parentNode
(I did not test it yet, please tell me if it helped)
I think so... if you have a script tag in subform.php and the file has the following HTML: Submit form, you should be able to:
var subformId = $('#mydiv').parent().id;
It would work because the script tag executes when the PHP file is included. Put the script tag at the end of subform.php to be sure.
We are building large ASP.NET applications for the intranet use in multiple languages/cultures. We utilize the Globalization with RESX files and use GetResourceText on the server side to get the localized texts.
Lately we are doing more and more client side logic with JQuery.
How do I get the RESX texts to be used in Javascript?
e.g. texts used for validation, dynamic messages etc.
All our Javascripts are in .JS files, we do not want to mix HTML in the ASPX page and Javascript blocks.
Thanks for your help.
Unfortunately, in an external JS file the server side code is not being processed by the server. However I have seen a workaround where you can set your translated values in hidden fields on the page - this way your javascript will be able to read the values in.
For example:
<%-- This goes into your page --%>
<input type="hidden" id="translatedField" name="translatedField" value="<%=Resources.Resources.translatedText %>" />
and use this inside your javascript file:
// This is the js file
$(document).ready(function() {
alert($("#translatedField").attr("value"));
});
You will be able to separate the values and still see it in your external JS file.
There is also another workaround that creates a .aspx file that only outputs Javascript instead of HTML. Check out the link below:
Using server side method in an external JavaScript file
Always separate functionality from human readable strings.
If you're creating jQuery-plugins you should be able to pass an array of localized strings as parameter when you call your different jQuery functions. The array could be defined as inline javascript directly on the page calling the different jQuery plugins or you could load the from external resource in the format /scripts/localization/strings.js?ci=en-US and register a Generic ASP.Net Handler in web.config that would respond to scripts/localization/strings.js
The DatePicker control is a fine example of how to localize text for the jQuery datepick control - this js file is dynamically created from resource files (resx) and when included on a page it will make sure the calendar control will have danish text.
Create a HttpHandler (.ashx file), and return JSON with your text resource strings.
You may also "publish" it to global namespace, i.e.
Response.Write("window.Resources=");
Response.Write((new JavaScriptSerializer()).Serialize(strings));
set up HTML like:
<script src="Resx.ashx?lang=en-US" />
<button class="LogoutButtonResourceId OtherButtonClasses">(generic logout text)</button>
<a href="#"><span class="SomeLinkTextResourceId OtherClasses">
(generic link text)
</span></a>
and apply texts like this:
$(document).ready(function() {
for(var resId in Resources){
$("."+resId).html(Resources[resId]);
}
});
If you don't want to use ASP.NET to generate your main JavaScript, here are two other options:
Use ASP.NET to generate a script file that contains variable-to-string assignments, such as var mystring = 'my value';. Your main script would then reference the localized text with variables names rather than as embedded values. If that's still too "dirty" for you, you could encode the strings as JSON rather than as variable assignments, using an HttpHandler rather than straight .aspx.
Have your JavaScript code issue an Ajax call to retrieve an array or list of localized strings from the server. The server-side part of the call would retrieve the text from your resx files.
Have you considered using $.ajax in combination with ASP.NET WebMethods? It's hard to suggest a more concrete solution to this problem without understanding how your JavaScript/jQuery would consume/process the resources. I assume that they're organized into logical groups (or could be) where you could return several resource strings that belong on a single page.
Assuming that, you could write a very simple C# class -- or use a Dictionary<string, string> -- to return data from your ASP.NET WebMethod. The results would look something like:
[WebMethod]
public Dictionary<string, string> GetPageResources(string currentPage)
{
// ... Organizational stuff goes here.
}
I always separate out my AJAX calls into separate .js files/objects; that would look like:
function GetPageResources (page, callback)
$.ajax({ // Setup the AJAX call to your WebMethod
data: "{ 'currentPage':'" + page + "' }",
url: /Ajax/Resources.asmx/GetPageResources, // Or similar.
success: function (result) { // To be replaced with .done in jQuery 1.8
callback(result.d);
}
});
Then, in the .js executed on the page, you should be able to consume that data like:
// Whatever first executes when you load a page and its JS files
// -- I assume that you aren't using something like $(document).ready(function () {});
GetPageResources(document.location, SetPageResources);
function SetPageResources(resources) {
for (currentResource in resources) {
$("#" + currentResource.Key).html(currentResource.Value);
}
}
I know it's to late but want share my experience in this task)
I use AjaxMin. It can insert resx key values into js file on build event.
It's not common way but it keeps html without unneeded script blocks and can be done during minification process if you have it.
It works like this:
ajaxmin.exe test.js -RES:Strings resource.resx -o test.min.js
Also you need to do the same for ech locale if you have many.
Syntax to write resource keys in js (and also css) is written here:
Js localization
Css localization
How about injecting it as part of a javascript control initialization? what i do is as follows:
I have a self-contained javascript control - call it CRMControl, which has an init method called setupCRMControl, to which i pass a settings object. When i initialize it, i pass an object containing all the resources i need inside javascript as follows:
CRMControl.setupCRMControl({
numOfCRMs: 3,
maxNumOfItems: 10,
// then i pass a resources object with the strings i need inside
Resources: {
Cancel: '#Resources.Cancel',
Done: '#Resources.Done',
Title: '#Resources.Title'
}
});
Then, inside this javascript control:
var crmSettings = {};
this.setupCRMControl(settings) {
crmSettings = settings;
};
and whenever i want to show a resource, i say (for example, show an alert saying 'Done'):
alert(crmSettings.Resources.Done);
You can call it "R" to make it shorter or something, but this is my approach. Maybe this may not work if you have a whole bunch of strings, but for manageable cases, this may work.
Not sure if this is possible or even if I should do it, but I think it's quite interesting.
I have a javascript file which I'm referencing in a flat HTML page. I'd like to pass in a parameter or two via the path to the script. Like this;
<script src="/scripts/myJavascriptFile.js?config1=true" type="text/javascript"></script>
Not really sure if it can work but it would make my solution a little easier for others to take my script and implement (arguable).
Cheers,
Mike
I don't think that passing in variables via the src attribute is possible out of the box without some extra coding on your part (there is an article here if you are interested!). You could do the following though, which should provide the same functionality as you are looking for:
Define your "config" variables in a single script block on your HTML page:
<script type="text/javascript">
var config1 = true;
</script>
Reference your external JS file in a second script block:
<script src="/scripts/myJavascriptFile.js" type="text/javascript"></script>
Add this code to your external JS file to reference the "local" variable in your HTML:
var conf1 = window.config1;
if (conf1) {
// Do stuff
}
This is a variation on Matt's answer. I have a similar case where I need a jQuery file to use a value that is generated in the HTML (by Razor in this case). I write the value to a meta tag, generated as it is from the controller:
<meta name="sessionId" content="#ViewBag.SessionId">
and then read it in the jQuery file:
var sessionId = $("meta[name=sessionId]").attr("content");
It's not quite the same as passing it in by querystring, but useful if that information is considered "meta-information" of the HTML page.
I have a javascript file that I reference in HTML with standard <script src="foo.js?param"></script>. In the file I want to distinguish e.g. loading the file with foo.js from foo.js?auto and foo.js?noauto=true, but not if the file is renamed to bar.js and referenced with the same parameter. How can I accomplish this, preferably not using any framework?
Take a look a scriptaculous' approach:
var js = /scriptaculous\.js(\?.*)?$/;
$$('head script[src]').findAll(function(s) {
return s.src.match(js);
}).each(function(s) {
var path = s.src.replace(js, ''),
includes = s.src.match(/\?.*load=([a-z,]*)/);
(includes ? includes[1] : 'builder,effects,dragdrop,controls,slider,sound').split(',').each(
function(include) { Scriptaculous.require(path+include+'.js') });
});
I think it runs through all script elements and finds the reference to itself, and then parses that URL.
If you want to do it reliably, then you need to provide different JS for each URL. You could generate it with a server side script.
If you want to do it in pure JS, then you can getElementsByTagName('script') and assume that last script is the one that matched (it might not be, e.g. if script elements are being added using DOM after the page has loaded).