JavaScript (in jsp) receive String from Java - javascript

Good Morning:
I am having several problems trying to receive a String from Java to JSP (Javascript inside).
Java File
String var = "Hello World!";
JavaScript (inside the JSP):
window.onload = function() {
loadData();
};
function loadData() {
document.getElementById('paragraph').innerHTML = "<%=var%>";
alert(matr1); }
}
But I received org.apache.jasper.JasperException: Cannot compile the class.
The rest of JSP and JavaScript is correct, I am trying only to fill the select with the text received in Java, I read other topics but nothing works.
Any help?
Thanks.

The <%= %> or the expression tag is used in jsp as a replacement for out.print() function of java.
You don't need to put double quotes around it to use it in java script, in your case if you have imported the java file into your jsp correctly then i think this should work:
document.getElementById('paragraph').innerHTML = <%=var%>;
Or
try using the variable name directly,
document.getElementById('paragraph').innerHTML = var;

Related

Access RESX file from external javascript file [duplicate]

How would one get resx resource strings into javascript code stored in a .js file?
If your javascript is in a script block in the markup, you can use this syntax:
<%$Resources:Resource, FieldName %>
and it will parse the resource value in as it renders the page... Unfortunately, that will only be parsed if the javascript appears in the body of the page. In an external .js file referenced in a <script> tag, those server tags obviously never get parsed.
I don't want to have to write a ScriptService to return those resources or anything like that, since they don't change after the page is rendered so it's a waste to have something that active.
One possibility could be to write an ashx handler and point the <script> tags to that, but I'm still not sure how I would read in the .js files and parse any server tags like that before streaming the text to the client. Is there a line of code I can run that will do that task similarly to the ASP.NET parser?
Or does anyone have any other suggestions?
Here is my solution for now. I am sure I will need to make it more versatile in the future... but so far this is good.
using System.Collections;
using System.Linq;
using System.Resources;
using System.Web.Mvc;
using System.Web.Script.Serialization;
public class ResourcesController : Controller
{
private static readonly JavaScriptSerializer Serializer = new JavaScriptSerializer();
public ActionResult GetResourcesJavaScript(string resxFileName)
{
var resourceDictionary = new ResXResourceReader(Server.MapPath("~/App_GlobalResources/" + resxFileName + ".resx"))
.Cast<DictionaryEntry>()
.ToDictionary(entry => entry.Key.ToString(), entry => entry.Value.ToString());
var json = Serializer.Serialize(resourceDictionary);
var javaScript = string.Format("window.Resources = window.Resources || {{}}; window.Resources.{0} = {1};", resxFileName, json);
return JavaScript(javaScript);
}
}
// In the RegisterRoutes method in Global.asax:
routes.MapRoute("Resources", "resources/{resxFileName}.js", new { controller = "Resources", action = "GetResourcesJavaScript" });
So I can do
<script src="/resources/Foo.js"></script>
and then my scripts can reference e.g. window.Resources.Foo.Bar and get a string.
There's no native support for this.
I built a JavaScriptResourceHandler a while ago that can serve Serverside resources into the client page via objects where each property on the object represents a localization resource id and its value. You can check this out and download it from this blog post:
http://www.west-wind.com/Weblog/posts/698097.aspx
I've been using this extensively in a number of apps and it works well. The main win on this is that you can localize your resources in one place (Resx or in my case a custom ResourceProvider using a database) rather than having to have multiple localization schemes.
whereas "Common" is the name of the resource file and Msg1 is the fieldname. This also works for culture changes.
Partial Javascript...:
messages:
{
<%=txtRequiredField.UniqueID %>:{
required: "<%=Resources.Common.Msg1 %>",
maxlength: "Only 50 character allowed in required field."
}
}
In a nutshell, make ASP.NET serve javascript rather than HTML for a specific page. Cleanest if done as a custom IHttpHandler, but in a pinch a page will do, just remember to:
1) Clear out all the ASP.NET stuff and make it look like a JS file.
2) Set the content-type to "text/javascript" in the codebehind.
Once you have a script like this setup, you can then create a client-side copy of your resources that other client-side scripts can reference from your app.
If you have your resources in a separate assembly you can use the ResourceSet instead of the filename. Building on #Domenics great answer:
public class ResourcesController : Controller
{
private static readonly JavaScriptSerializer Serializer = new JavaScriptSerializer();
public ActionResult GetResourcesJavaScript()
{
// This avoids the file path dependency.
ResourceSet resourceSet = MyResource.ResourceManager.GetResourceSet(CultureInfo.CurrentUICulture, true, true);
// Create dictionary.
var resourceDictionary = resourceSet
.Cast<DictionaryEntry>()
.ToDictionary(entry => entry.Key.ToString(), entry => entry.Value.ToString());
var json = Serializer.Serialize(resourceDictionary);
var javaScript = string.Format("window.Resources = window.Resources || {{}}; window.Resources.resources = {1};", json);
return JavaScript(javaScript);
}
}
The downside is that this will not enable more than one resource-file per action. In that way #Domenics answer is more generic and reusable.
You may also consider using OutputCache, since the resource won't change a lot between requests.
[OutputCache(Duration = 3600, Location = OutputCacheLocation.ServerAndClient)]
public ActionResult GetResourcesJavaScript()
{
// Logic here...
}
http://www.asp.net/mvc/overview/older-versions-1/controllers-and-routing/improving-performance-with-output-caching-cs
I usually pass the resource string as a parameter to whatever javascript function I'm calling, that way I can continue to use the expression syntax in the HTML.
I the brown field application I'm working on we have an xslt that transforms the resx file into a javascript file as part of the build process. This works well since this is a web application. I'm not sure if the original question is a web application.
use a hidden field to hold the resource string value and then access the field value in javascript
for example :
" />
var todayString= $("input[name=TodayString][type=hidden]").val();
Add the function in the BasePage class:
protected string GetLanguageText(string _key)
{
System.Resources.ResourceManager _resourceTemp = new System.Resources.ResourceManager("Resources.Language", System.Reflection.Assembly.Load("App_GlobalResources"));
return _resourceTemp.GetString(_key);
}
Javascript:
var _resurceValue = "<%=GetLanguageText("UserName")%>";
or direct use:
var _resurceValue = "<%= Resources.Language.UserName %>";
Note:
The Language is my resouce name. Exam: Language.resx and Language.en-US.resx

Trying to understand how to call a class in javascript and getting a json string

I am trying to understand these line, which are written in a jsp page:
<%# page import="com.x.VoltDAOImpl" %>
<%!
VoltDAOImpl voltDao = new VoltDAOImpl();
Map<String , List<HashMap<String,String>>> returnList= null;
List<HashMap<String,String>> orderDetailsList1= null;
orderDetailsList1 = returnList.get("order_details");
JSONArray jsonArray = new JSONArray(orderDetailsList1);
%>
I'm a complete newbie to jsp and javascript, but I'm reading online and getting things done. What I understand from the above lines is that, it's importing from VoltDAOImpl class (calling the class which has some database), creating a HashMap orderDetailsList1 that gets "order_details". But, I don't what to use this jsp. I want to simply call this class in a javascript file and get this orderDetailsList1 as a json. I know, that I can convert some json string to json object using JSON.parse, but how do I call this class and get the order_details as a json string in the first place??
I'm so confused. Please help!!!

Populating Dynamic Fields in groovy GSP by using JavaScript

Hey Guys i am trying to populate dynamic fields in groovy GSP by using javascript and Groovy markup
*Here's the Effort 1 ->Works fine using plain html *
<r:script>
function createField()
{
var variable=0;
var d="<input type='text' name='item["+variable+"]' id='item["+variable+"]'/>";
reutrn d;
}
</r:script>
*Here's the Effort 2 ->JavaScript Error while using Groovy tags *
<r:script>
function createField()
{
var variable = 0;
var d = "<g:textField name='item["+variable+"]' id='item["+variable+"]' />";
return d;
}
</r:script>
By Using above function browser ends up with the error :javascript uncaught syntaxerror unexpected token illegal
So i decided to encode the tag using Grails InLine codec encodeAs="JavaScript".
*Here's the Effort 3 ->Error using Groovy tags *
y<r:script>
function createField()
{
var variable=0;
var d="<g:textField name='item["+variable+"]' id='item["+variable+"]' encodeAs="JavaScript"/>";
return d;
}
</r:script>
Problem with the third effort while encoding the tags, quotes besides the variable are also encoded so the output is something like u003b+variable+\u0026#39, this makes the nonidentical form fields which are unable to process further.
Any help will be appreciated.
GSP and javascript are evaluated at different times which is causing this not to work. GSP is executed server side then the result is sent back to the client the JS is executed client side. If you view source of the page from your browser you will see that the createField function has the g:textField already replaced.

Transferring javascript from a view to a seperate JS file

I am working on a legacy application and I want to move some JS code onto a separate JS file.
I will have to refractor some of the code to do this. I can put #Url.Content statements into data attributes in the HTML.
But how would I replace this line of code?
var array = #Html.Raw(Json.Encode(ViewBag.JobList));
A separate JS file will not know what #Html.Raw means.
Server side code like that cannot run in a seperate javascript file. My solution for such problems is having a short javascript part in the head that runs on the onload event. There you can set variables that you can use in a seperate javascript file:
in the head:
array = #Html.Raw(Json.Encode(ViewBag.JobList));
in the seperate javascript file:
var array;
Then, in the seperate javascript file you can do with your array whatever is necessary.
The ViewBag.JobList data is only known at HTML page generation time. To include it in an external JavaScript file, you have to have another ASP.NET resource that recalculated ViewBag.JobList and then served as part of a dynamic JavaScript file. This is pretty inefficient.
Instead, do what you're doing with the URLs: pass the data through the DOM. If you're writing into normal DOM instead of a script block, you don't need the raw-output any more (*), normal HTML escaping is fine:
<script
id="do_stuff_script" src="do_stuff.js"
data-array="#Json.Encode(ViewBag.JobList)"
></script>
...
var array = $('#do_stuff_script').data('array');
// jQuery hack - equivalent to JSON.parse($('#do_stuff_script').attr('data-array'));
(Actually, the raw-output might have been a security bug, depending on what JSON encoder you're using and whether it chooses to escape </script to \u003C/script. Writing to HTML, with well-understood HTML-encoding requirements, is a good idea as it avoids problems like this too.)
I think you need to create action with JavaScriptResult
public ActionResult Test()
{
string script = "var textboxvalue=$('#name').val();";
return JavaScript(script);
}
But, before proceeding please go through following links
Beware of ASP.NET MVC JavaScriptResult
Working example for JavaScriptResult in asp.net mvc
I would also follow MelanciaUK's suggestion :
In your javascript file, put your code inside a function :
function MyViewRefactored( array ){
... your code ...
}
In your view, leave a minimal javascript bloc :
<script>
var array = #Html.Raw(Json.Encode(ViewBag.JobList));
MyViewRefactored( array );
</script>

Error while trying to get asp.net(C#) textbox text from ajax static WebMethod

I am using an ajax htmleditor in asp.net web application so i am trying to get the text the user has entered in the editor then i will send that text back to the client javascript function that will show the text in a div. But I am getting this error "Object reference not set to an instance of an object."
Firstly i tried to access the text of textbox linked with htmleditorextender through javascript but it was not working for me so i moved to ajax webmethod but this time also i am facing a problem. Please Help me.
[System.Web.Services.WebMethod]
public static string seteditor()
{
String x="";
try
{
Content c = new Content();
x = c.txteditor.Text;
}
catch (Exception ex) { x=ex.Message; }
return x;
}
Here, txteditor is the ID of asp:textbox which is linked with ajaxcontroltoolkit htmleditorextender.
You cannot get your aspx controls inside a static method.
If you are Calling a static method from jquery means the Page and its Controls don't even exist. You need to look another workaround for your problem.
EDIT:
I always pass my control values to page methods like this:
Assume I have two text controls: txtGroupName and txtGroupLevel
...My JS with Jquery will be :
var grpName = $("#<%=txtGroupName.ClientID%>").val();
var grpLevel = $("#<%= txtGroupLevel.ClientID %>").val();
data: "{'groupName':'" + grpName + "','groupLevel':'" + grpLevel + "'}",
Where groupName and groupRights are my webmethod parameters.
EDIT2:
Include your script like this:
<script type="text/javascript" src="<%= ResolveUrl("~/Scripts/jquery-1.4.1.js") %>"></script>
I suggest you to use the latest jquery version.
Web methods do not interact with the page object or the control hierarchy like this. That's why they're static in the first place. You need to pass the text from the client as a parameter to the web method, not read it from the textbox.
This issue was torturing me from last 18 hours continuouslyFirst I tried javascript than webmethod and than on user1042031's suggestion I tried jquery and than again I tried javascript and look how much easily it can be done with a single line of code.
var a = document.getElementById('<%= txteditor.ClientID %>').value;
read this stackoverflow article Getting Textbox value in Javascript
I apologize to everyone who responded me in this question but i have not found that article in my initial search.

Categories

Resources