Value from Grails controller breaking javascript in gsp - javascript

I am passing XML string from grails controller to gsp and need to use it in the javascript function for showing treeview using jstree.
My controller code is
render(view: "list",model: [dataXML: callXML.getXmlString()])
The javascript function in gsp code is
function callXML(){
var xmlStr = "${dataXML}";
_uimTree = new UIMTreeProcessor(parseXml(), jQuery("#jstree"));
_uimTree.doProcess();
}
function parseXML(){
if (window.DOMParser) {
return new window.DOMParser().parseFromString(xmlStr, "text/xml");
}else if (typeof window.ActiveXObject != "undefined" && new window.ActiveXObject("Microsoft.XMLDOM")) {
var xmlDoc = new window.ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async = "false";
xmlDoc.loadXML(xmlStr);
return xmlDoc;
}else{
return jQuery(xmlStr);
}
}
Controller:
def showModel = {
CallXML callXML = new CallXML();
callXML.setXmlString();
def productFlowModels = new XmlParser().parseText(callXML.getXmlString());
println callXML.getXmlString();
render(view: "list",model: [dataXML: callXML.getXmlString() as String])
}
As soon as the ${dataXML} comes in function it breaks the code. I tried without quotes, still same problem.
What is that I am doing wrong?
Thanks in advance.

If you have xml string, you should be able to access it from your controller like this:
Controller:
def list(Integer max) {
def xmlString = """<langs type="current">
<language>Java</language>
<language>Groovy</language>
<language>JavaScript</language>
</langs>"""
def xml = new XmlParser().parseText( xmlString )
render (view:'list',model: [dataXML:xml ])
}
GSP:
<!DOCTYPE html>
<html>
<head>
<script>
function my(){
var str = "${dataXML.encodeAsHTML()}"
alert (str)
}
</script>
</head>
<body>
<p>
${dataXML.encodeAsHTML()}
</p>
<script>
my()
</script>
</body>
</html>

in your model, use
render(view: "list",model: [dataXML: JsonOutput.toJson(callXML.getXmlString())])
You need to properly encode strings as javascript strings if you are going to output them in a javascript context.

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.

Issue in sharing data between JavaScript and JSP files using window.open() function

In below example I am sharing data between JavaScript and JSP files. I can successfully send data from File1.js to File2.jsp, But I am not getting value back from File2.jsp to File1.js. It was working fine with IE5 when I used ShowModalDialogue function, but it is not working with window.open() function.
I tried using localStorage, but it is not working out. I am always getting returnValue, data1 and data2 as undefined or empty. Is there any solution to get value from the file2.jsp? Thank you in advance.
file1.js
function framedialog() {
data1 = new Array();
data2 = new Array();
var pm = new Object();
pm.data1 = data1;
pm.data2 = data2;
var url = "http://locahost:8080/File2.jsp";
var returnValue = window.open(url, pm, '', '');
if (returnValue == '1') {
for (i in data1) {
alert(data1[i]);
alert(data2[i]);
}
}
}
File2.jsp
<html>
<head>
<script>
var count=5;
var tabco=new Array(count);
function ActionOK(){
tabco=['aa','bb','cc'];
for(j in tabco){
data1[j]=tabco[j];
}
tabcoTitle=['1','2','3'];
for(k in tabcoTitle){
data2[k]=tabcoTitle[k];
}
top.opener.returnValue="1";
}
</script>``
</head>
<body class="">
<input type="button" name="ok" value="ok" onClick="ActionOk()">
</body>
</html>
enter code here

JavaScript function not defined in c# code

I am working with VS, a web form application, and I want to generate in the code-behind (C#) a JavaScript function defined in a JavaScript file in the project,.
I have tried different ways ,such as this line of code:
Page.ClientScript.RegisterStartupScript(this.GetType(), "CallMyFunction", "Function_Name", true);
However, it can't resolve the name of my function since it's "not defined" as it's shown as a JavaScript error. But it works fine with a simple line of JavaScript code put in the Function_Name field (like alert("something")).
Any help with this please?
C#
define your javascript inside the C# code as text
Type type = this.GetType();
String key = "CallMyFunction";
ClientScriptManager cs = Page.ClientScript;
if (!cs.IsClientScriptBlockRegistered(type, key))
{
StringBuilder script = new StringBuilder();
script.AppendLine("<script type=\"text/javascript\">");
script.AppendLine(" function Function_Name() {");
script.AppendLine(" frmMain.Message.value = 'Hello World';");
script.AppendLine(" }");
script.AppendLine("</script>");
cs.RegisterClientScriptBlock(type, key, script.ToString(), false);
}
or read your javascript from a .js file
<script type="text/javascript">
function Function_Name() {
frmMain.Message.value = 'Hello World';
}
</script>
Type type = this.GetType();
String key = "CallMyFunction";
ClientScriptManager cs = Page.ClientScript;
if (!cs.IsClientScriptBlockRegistered(type, key) && File.Exists(path))
{
string script = File.ReadAllText(path);
cs.RegisterClientScriptBlock(type, key, script, false);
}
HTML - Body
<body>
<form id="frmMain" runat="server">
<input type="text" id="Message" />
<input type="button" value="Click!" onclick="Function_Name()" />
</form>
</body>
If you need a one-liner:
Page.ClientScript.RegisterStartupScript(this.GetType(), "CallMyFunction", "function Function_Name() { frmMain.Message.value='Hello World'; }", true);
or
Page.ClientScript.RegisterStartupScript(this.GetType(), "CallMyFunction", "<script type=\"text/javascript\">function Function_Name() { frmMain.Message.value='Hello World'; }</script>", false);
EDIT:
Using includes
String includeKey = "MyInclude";
String includeFile = "/myInclude.js";
String scriptKey = "CallMyFunction";
String script = "Function_Name();"; //Function inside your included js file.
Type type = GetType();
ClientScriptManager cs = Page.ClientScript;
//register the js file containing the function
if (!cs.IsClientScriptIncludeRegistered(includeKey))
{
cs.RegisterClientScriptInclude(includeKey, includeFile);
}
//register the script to call the function
if (!cs.IsClientScriptBlockRegistered(scriptKey))
{
cs.RegisterClientScriptBlock(type, scriptKey, script, true);
}

Node.js -- Robust HTML parsing + access to javascript functions in HTML

I'm new to node, and looking to extract javascript info from the following example page:
contrived.html:
<html>
<head>
<title>
This is a contrived example
</title>
<script type="text/javascript">
var filenames = new Array()
filenames[filenames.length] = "http://domainwhatever.s3.amazonaws.com/780BONNYVILLECOLDLAKECHRYSLER/4431716.jpg";
filenames[filenames.length] = "http://domainwhatever.s3.amazonaws.com/780BONNYVILLECOLDLAKECHRYSLER/4431716_1.jpg";
filenames[filenames.length] = "http://domainwhatever.s3.amazonaws.com/780BONNYVILLECOLDLAKECHRYSLER/4431716_2.jpg";
filenames[filenames.length] = "http://domainwhatever.s3.amazonaws.com/780BONNYVILLECOLDLAKECHRYSLER/4431716_3.jpg";
filenames[filenames.length] = "http://domainwhatever.s3.amazonaws.com/780BONNYVILLECOLDLAKECHRYSLER/4431716_4.jpg";
function pixplosion_Content()
{
var eElement = document.getElementById('idLoading');
if( eElement ) eElement.style.display = 'none';
return "<pixplosion test=\"test\" flashGasket=\"http://www.realelivepeople.com/pixplosion/assets/flashGasket.swf?contentPath=\" ytBridge=\"/images/image.php?pixplosion=ytbridge\"><tab test=\"test\" label=\"Photos (%1)\" icon=\"Image\" autoIterate=\"false\" ><tab test=\"test\" label=\"Vehicle Photos (%1)\" icon=\"\" autoIterate=\"true\" startFocused=\"true\" >
<image>http://s3.domainwhatever_2.com/vehicles/photos/3726/1300025.jpg</image>
<image>http://s3.domainwhatever_2.com/vehicles/photos/3726/1300025/35102537.jpg</image>
<image>http://s3.domainwhatever_2.com/vehicles/photos/3726/1300025/35102538.jpg</image>
<image>http://s3.domainwhatever_2.com/vehicles/photos/3726/1300025/35102539.jpg</image>
<image>http://s3.domainwhatever_2.com/vehicles/photos/3726/1300025/35102540.jpg</image>
<image>http://s3.domainwhatever_2.com/vehicles/photos/3726/1300025/35102541.jpg</image>
<image>http://s3.domainwhatever_2.com/vehicles/photos/3726/1300025/35102542.jpg</image>
<image>http://s3.domainwhatever_2.com/vehicles/photos/3726/1300025/35102543.jpg</image><image>http://s3.domainwhatever_2.com/vehicles/photos/3726/1300025/35102544.jpg</image><image>http://s3.domainwhatever_2.com/vehicles/photos/3726/1300025/35102545.jpg</image><image>http://s3.domainwhatever_2.com/vehicles/photos/3726/1300025/35102546.jpg</image></tab></tab></pixplosion>";
}
</script>
</head>
<body>
</body>
</html>
Jsdom chokes on this HTML using its default parser, so I've used aredridel/html5 parser from github. It seems to work for reading in HTML, through jQuery, but I don't have access to function definitions like I did with jsdom and its default parser.
For example, the following:
console.log(window.filenames);
With the default parser gives me an array.
With the HTML5 parser, it gives me:
undefined
Here is my code:
var jsdom = require("jsdom"),
fs = require('fs'),
HTML5 = require('html5');
fs.readFile('contrived.html', 'utf-8', function(err, data) {
if (err) {
throw err;
}
var document = jsdom.jsdom(data, null, {parser: HTML5});
// HTML data should be in document creation call
var script = document.createElement("script");
// HTML data SHOULD NOT be in window creation call
var window = document.createWindow();
var parser = new HTML5.Parser({document: window.document});
parser.parse(data);
script.src = 'http://code.jquery.com/jquery-1.4.2.js';
script.onload = function(window) {
console.log('this is a test');
console.log(window.filenames);
console.log(window.pixplosion_Content);
}
document.head.appendChild(script);
});
Am I missing something, or is this functionality just not available?
Many thanks.

Running Exe in Firefox why do I get an error

I run this in Firefox, when clicking on link, Firefox says NS_ERROR_FILE_UNRECOGNIZED_PATH wheread I followed the instruction from here How to open .EXE with Javascript/XPCOM as Windows "Run..."?
<html>
<head>
<script>
function RunExe(path) {
try {
var ua = navigator.userAgent.toLowerCase();
if (ua.indexOf("msie") != -1) {
MyObject = new ActiveXObject("WScript.Shell")
MyObject.Run(path);
} else {
netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
var exe = window.Components.classes['#mozilla.org/file/local;1'].createInstance(Components.interfaces.nsILocalFile);
exe.initWithPath(path);
var run = window.Components.classes['#mozilla.org/process/util;1'].createInstance(Components.interfaces.nsIProcess);
run.init(exe);
var parameters = [""];
run.run(false, parameters, parameters.length);
}
} catch (ex) {
alert(ex.toString());
}
}
</script>
</head>
<body>
Open Word
</body>
In javascript literals, a backslash indicates the beginning of an escape sequence. If you actually want to represent a backslash, you can escape it with a double backslash.
ie
'C:\\Windows\\System32\\cmd.exe /c start winword.exe'
http://www.javascriptkit.com/jsref/escapesequence.shtml
EDIT:
From the comments on the correct answer from the post you linked, it looks like the way he got it working was:
only pass the path to runexe:
javascript:RunExe('C:\Windows\System32\cmd.exe')
set the params equal to the command args:
var parameters = ["/c start winword.exe"];
So this would work theoretically:
<html>
<head>
<script>
function RunExe(path) {
try {
var ua = navigator.userAgent.toLowerCase();
if (ua.indexOf("msie") != -1) {
MyObject = new ActiveXObject("WScript.Shell")
MyObject.Run(path);
} else {
netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
var exe = window.Components.classes['#mozilla.org/file/local;1'].createInstance(Components.interfaces.nsILocalFile);
exe.initWithPath(path);
var run = window.Components.classes['#mozilla.org/process/util;1'].createInstance(Components.interfaces.nsIProcess);
run.init(exe);
var parameters = ["/c start winword.exe"];
run.run(false, parameters, parameters.length);
}
} catch (ex) {
alert(ex.toString());
}
}
</script>
</head>
<body>
Open Word
</body>
Although clearly it would be better to pass in the params as an argument than hardcode them as I've done here (or pass them in as part of the path and parse them out)

Categories