Cannot print results of cgi script in webpage <div> using javascript - javascript

I am trying to print the result of cgi script inside a <div> in html page using the code
HTML
<b>Already Loaded Data</b>
<div id="result"></div>
JS
<script type="text/javascript" >
var fdate='document.ccform.cdt.value';
var tdate='document.ccform.cdt.value';
$( "#result" ).load( "../cgi-bin/coll.cgi?ctype=''&cdet=''&fdt=$fdate&tdt=$tdate" );
</script>
Note:- The HTML form name is ccform and the date field name is cdt.Coll.cgi takes four values which are ctype, cdet, fdt and tdt.
fdt and tdt are dates.
I presume the syntax of date field needs to be corrected.

There is a lot wrong here. You cannot interpolate variables into strings with $ this way, and you cannot access values from variables using 'document.ccform.cdt.value'. You also don't need to supply empty values ('') for your empty query string variables.
You seem to be lacking an understanding of what strings are and how they work; nothing anywhere in JavaScript would suggest that 'fdt=$fdate' would be a correct way of building a query string, or that you can access a variable using 'document.ccform' instead of document.ccform. You should read a tutorial on JavaScript rather than trying to feel your way around these fundamental syntax issues.
Your code should look something like this:
var fdate = document.ccform.cdt.value;
var tdate = document.ccform.cdt.value;
$("#result").load( "../cgi-bin/coll.cgi?ctype=&cdet=&fdt=" + fdate + "&tdt=" + tdate );

Related

apple .replace() Html element generate by handlebar js

I am wondering if how am i able to change the element data by .replace() if i use handlebar js to generate html elements.
For instance i have this role of p tag which display a row of data by handlebar js:
<p id="pre-region">{{region}}</p>
and the result of it is
1,44
and i 'd like to change it to
1+44
If you haven't had any experience of handlebar js then consider the tag be
<p id="pre-region">1,44</p>
how should i change from 1,44 to 1 +44?
UPDATE 1
Here should be an extersion for my question. I am passing the HTML element inside pre-region into an href in order to update my website by Ajax.
After i have converted all the comma in to "+" the API retrieve special character "&B2" which equal to the symbol "+" and the API goes error.
MYDOMAIN/path/getRegion?token&profileId=111&dataType=all&region=1%2B4
This is how may API looks like at the moment
MYDOMAIN/path/getRegion?token&profileId=111&dataType=all&region=1+4
should be the solution
I haven't had any experience of handlebars.js but from my point of view, you can just put the code just before the </body>:
<script>
var node = document.getElementById('pre-region');
node.innerHTML = node.innerHTML.replace(',', '+');
</script>
I'll check out the handlebars js in case it does not work.
Update:
As you mentioned in the comment, if you need to use it in the HTTP request/URL, you may handle the string using decodeURIComponent(yourstring):
decodeURIComponent('1%2B44'); // you get '1+44'
Read more about decodeURIComponent() method from this. In URL, it should be encoded as region=1%2B44 in your case; while it should be decoded if you want to use it in your JavaScript code or display in the web page.
Update 1
You should encode your string when it's used as a part of parameter of HTTP request. Therefore, it looks good if the URL is:
MYDOMAIN/path/getRegion?token&profileId=111&dataType=all&region=1%2B4
What you need to do is decode the string on your server side. I assume that you are in control of the server side. If you are using Node.js, you can just use decodeURIComponent() method to decode the parameter. If you're using Python or PHP as your server language, it should be something like decodeURIComponent() in that language.
Update 2
The solution above only replace the first occasion of comma to +. To solve that, simply use:
<script>
var node = document.getElementById('pre-region');
node.innerHTML = node.innerHTML.replace(/,/g, '+');
// Regular Expression is used here, 'g' for global search.
</script>
PHP has a replaceAll() method, so we can add that method to String.prototype like below if you want:
<script>
String.prototype.replaceAll = function(search, replacement) {
var target = this;
return target.split(search).join(replacement);
}
// Another method to replace all occasions using `split` and `join`.
</script>
Alright, so this is my first answer ever on stack overflow so I'm alien to this whole thing but here we go:
You could try this code in another js file that runs after handlebars:
var pre = $('#pre-region'); // defines a variabe for the element (same as
// document.getElementById('pre-region'))
var retrievedRegion = pre.innerHTML;
var splitten = retrievedRegion.split(',');
var concatenated = parseInt(split[0]) + parseInt(split[1])
retrievedRegion.innerHTML = "'" + concatenated) + "'";
or using replace():
retrievedRegion.replace(',','+')

Convert mail merge variable to sting with quotes in Javascript

I'm working in a proprietary system that has the ability to add HTML and Javascript to create custom pages. The system has the ability to insert user profile fields into the HTML/Javascript a mail merge like tag. In a project I'm working on I'm using a value from one of the users fields (User_Region) to append to a URL and create a personalized link to another system for each user.
I have been able to append the URL successfully when the value is numeric (12345) but not when it is text or alphanumeric. For example neither "Florida" nor "123456a" work.
Here's the code that I am using:
<script>
(function() {
var originalURL = "https://www.mywebsite.com/index.php";
var userRegion = {User_Region};
document.write("NewURL = " + originalURL + "?id=" + userRegion);
})();
</script>
In the code {User_Region} is the mail merge tag that I use to insert the variable from the user profile field. If the region variable is numeric like 123456 it works perfectly and it will output a URl like this:
https://www.mywebsite.com/index.php?id=123456
However if the region variable is text or alphanumeric like Florida or 123456a then the script does not work. Document.write does not output anything. It seems like the function either stops or breaks. I'm guessing this has to do with a data type issue, but I can't seem to figure it out.
If I hard code the variable as a string like this the function works perfectly.
<script>
(function() {
var originalURL = "https://www.mywebsite.com/index.php";
var userRegion = 'Florida';
document.write("NewURL = " + originalURL + "?id=" + userRegion);
})();
</script>
The above code will output a correct URL like this:
https://www.mywebsite.com/index.php?id=Florida
I have tried numerous ways to add the single-quote marks to the {User_Region} variable without success.
Does anyone have a suggestion for how I can make this work?
Thanks in advance for your assistance!
Have you tried encapsulating it in quotes as such:
var userRegion = '{User_Region}';
Because I guess your framework just replaces the {User_Region} with something else, please inform me if I got it wrong. I didn't quite get what this tag is. You see, in JS, curly braces are used to define Objects.

Freemarker: Calling macro from JavaScript function

I have a freemarker macro like this.
<#assign xmlNode = parseXML("<field name='dropDown' type='select' valueName='COUNTRY'/>")>;
<#import "utilFields.ftl" as util />
<div>
<#util.createDropdown field=xmlNode/>
</div>
How would I call the same macro from Javascript?
Tried:
<#assign xmlNode = parseXML("<field name='dropDown' type='select' valueName='COUNTRY'/>")>;
<script type="text/javascript">
var dropdown = "${util.createDropdown(xmlNode)}";
alert(dropdown);
</script>
Error
FreeMarker template error:
A macro cannot be called in an expression.
I assume you want to insert the HTML generated by #util.createDropdown into the JavaScript string literal. (You can't literally call FreeMarker form JavaScript, since the two run at different times.) The naive approach is just:
<#-- Not safe! -->
var dropdown = "<#util.createDropdown field=xmlNode/>";
The problem is that util.createDropdown writes HTML to the output, and HTML not in general valid as is inside a JavaScript string literal, because you can have " in it and so on. You can do a trick like this though:
<#macro jsStr>
<#local captured><#nested></#local>
"${captured?js_string}"<#t>
</#macro>
...
var dropdown = <#jsStr><#util.createDropdown field=xmlNode/></#>;
The jsStr macro converts the content printed inside it (and it need not be a single macro call inside it, it can be anything) to a valid JavaScript string literal.

getting error while passing value from javascript to scriplet in jsp

I have a requirement where i need to pass a value from Javascript to a Scriplet in a JSP. i am aware that javascript is executed on client side and jsp on the server side.i have searched online and googled a lot but till now i am not able to find a solution that i am looking for. The JSP code is as below. both javascript and scriplet are in same jsp.
<script type="text/javascript">
var strUrl = window.location.href;
var aps = strUrl.toLowerCase().indexOf("values");
var modifiedString = strUrl.substring(aps+8);
var v = strUrl.indexOf(modifiedString);
document.write(v);
</script>
<%
String st="<script>document.writeln(v)</script>";
out.println("-----"+st);
int pareseValue = Integer.parseInt(st);
if(st.equals("0")){
out.println("test");
%>
<h1><div class="xyz">
<fmt:message>header.txt</fmt:message>
</div></h1>
<%
}else{
%>
<div class="pqr">
<fmt:message>header1.txt</fmt:message>
</div>
<%
}
%>
In the above code i am trying to pass a value from Javascript to a scriplet.
But i am getting a NumberFormatException when i try to parse that string and convert to int. looks like the variable st is not of a string type.
String st="<script>document.writeln(v)</script>";
out.println("-----"+st);
int pareseValue = Integer.parseInt(st)
Can you please let me know what is the problem with the above code and how can i resolve the problem that i am facing now.
Thanks
Vikeng
The reason why you can't parse "<script>document.writeln(v)</script>" as an int is because it contains characters other than digits.
Even though it looks like it contains <script> tags - it's still not code that will execute or evaluate to a number. Because it's in quotes it's just a string. So "<script>document.writeln(v)</script>" looks the same to the parser as would "tic/v)neiwtm>oprs<citdun.rtl(<rp>".
This is somewhat of a moot point however, because unfortunately, you can't pass values to scriptlets. It's completely one-directional.
In order to get your page communicating with your java, you'll need to pass your params while requesting some handler.
For example, you could do some asynchronous JavaScript:
var asyncHR = new XMLHttpRequest();
var URL = "https://www.yourserver.com/intparser?st=v";
asyncHR.open("GET", URL, true);
asyncHR.send();
Then your request handler could take that parameter st, parse it or whatever you need to do, modify the model - adding this new value as an attribute, and then from JavaScript, reload the page.

Struts object accessing in JS

I have a bean and want to iterate through the values and store it in an array.
My form bean name is keywords and the element to be accessed is keywordList, so in my JS when I alert("${keywords.keywordList}");
I get [com.test.bean.Keyword#10, com.test.bean.Keyword#f, com.test.bean.Keyword#e], but I want the values and assign them to a var, how can I do this?
javascript and java are two different languages, you can not assume that you pass the keywords.keywordList in java and get the corresponding objects in javascript, you need to iterate the keywordlist in java and create the corresponding javascript objects manually.
update: some pseudocode
out.print("var keywordsInJS = []")
for (String keyword : keywordList) {
out.print("var keyword = '" + keyword + "';");
out.print("keywordsInJS.push(keyword);");
}
// now you can use keywordsInJS in js.
Here is how I solved my problem
<script>
var i = 0;
var collection = new Array();
</script>
And since I was using logic:iterator and displaying the values in the table, I added
<script>
collection[i++] = "${keyword.name}";
</script>
Now when I alert collection, all the words are in the array. Which is exactly what I need.
This is what I have done to solve this issue on JSP page
< %# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<script type="text/javascript">
var keyWordsArray=new Array();
var rowCounter=0;
<c:forEach items="${keywords.keywordList}" var="keyWords">
var fieldObj=new Object();
fieldObj.value='<c:out value="${keyWords}"/>'
keyWordsArray[rowCounter]=fieldObj;
rowCounter++;
</c:forEach>
</script>
</code>
Now you can access keWordArray in Javascript.
In my experience JS and Java doesn't interact well...
I suggest you to use HTML as a middle term for them to interact. Like, for example, displaying the contents of the list in invisible text in html (with iterator and the property indexed you can have different names for each text), then you can get them in JS.
You should also keep the length of the list so when you iterate in JS you know when to stop.
I know this far from a perfect solution and far from something remotely nice to do. But I know no better way to do it :(
Hope there is one, so I can also use it :)

Categories