How to set variable value from javascript to JSP? - javascript

I need to draw a table dynamically depending on the data store in a database. When the first web page (validator.jsp) is loaded it goes to a dataBase and returns an ArrayList called cert. (cert hast Description, value, etc).
<% java.util.ArrayList<Certificate> cert = OperacionesVidaDollars.getCertificates();%>
After that when the page finishes loading, a javascript function is called (function drawCertificates). This function will draw as many tables as certificates the ArrayList has.
<script type="text/javascript">
window.onload = drawCertificates;
function drawCertificates(){
alert("page finish loading, staring to draw certificates");
var i;
for(i=0;i<<%=cert.size()%>;i++){
createTable(i);
}
}
</script>
As you can see in the function create table, the variable text is suppost to change depending on i
text = document.createTextNode("<%=cert.get(i).getDescription()%>");
In order to update that variable i, I first call the JSP setVariable, to update the counter and then I try to use it in getDescription like:
text = document.createTextNode("<%=cert.get(request.getAttribute("count")).getDescription()%>");
I have this setVariable.jsp
<%
int num = Integer.valueOf(request.getParameter("number"));
request.setAttribute("count", num);
request.getRequestDispatcher("VidaDollarsCC.jsp").forward(request, response);
Cookie cookie = new Cookie("countCookie",String.valueOf(num));
cookie.setMaxAge(60*60*24);
response.addCookie(cookie);
%>
In other JSP (validator.jsp)I have this javascript function who it supposed to change the variable value.
function setVariable(number){
alert("setting the number " + number);
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
}
xmlhttp.open("POST", "setVariable.jsp", true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send("number="+number);
}
In the same jsp (validator.jsp) I have this function to createTable(uniqID) where I need that the number is updated depending on the uniqID because I have an ArrayList which has some information that I want to be shown.
function createTable(uniqID){
setVariable(uniqID);
text = document.createTextNode("<%=cert.get(request.getAttribute("count")).getDescription()%>");
}
But is not working. Does someone knows why? How can I solve it? if you have other ideas that I can implement, that also would be great.

I am assuming that your AJAX call is successfully sending number to setVariable.jsp.
1) You have to realize that AJAX call is a different request and is different then the request you have in your validator.jsp page.
2) You cant write JSP expression from Javascript and have it being resolved to HTML since your JSP needs to be reprocessed by server side.
To answer to your question on how to solve this, we need to know what you are trying to do in the first place.
Update:
1) Looks like the uniqID and count are same number. Why not just use uniqID in your javascript.
2) Why not pass certificate description into the createTable too. Like so:
<% java.util.ArrayList<Certificate> cert = OperacionesVidaDollars.getCertificates();
StringBuilder jsCerts = new StringBuilder("[");
boolean first = true;
for (Certificate cr : certs){
if (!first) jsCerts.append(",");
first = false;
jsCerts.append("\"").append( cr.getDescription() ).append("\"");
}
jsCerts.append("]");
%>
<script type="text/javascript">
window.onload = drawCertificates;
function drawCertificates(){
alert("page finish loading, staring to draw certificates");
var certArray = <%=jsCerts.toString()%>;
var i;
for(i=0;i<certArray.length;i++){
createTable(i, certArray[i]);
}
}
</script>
function createTable(uniqID, desc){
setVariable(uniqID);
text = desc;
}
The point here is that you need to write all the necessary data into the HTML to be able to use it in JavaScript, you cant access request attributes from JavaScript.

Related

Display results from api after user input

I'm learning JS and I need some help figuring out why my info isn't getting populated in the html. I'm just trying to get the basic functionality to work, so that I can continue to expand on it.
User is supposed to input a 3 digit route value, which will then return all the route information from an api call. I was able to get the route info to display earlier when I got the api call set up, but I'm struggling to figure why it's not displaying now that I tried adding in a feature to allow the user to input the route. See attached pen
HTML
<div class='container'>
<h1 id='header'>Route Info</h1>
<input id="input" type="text" placeholder="Enter 3 digit route ex 005" >
<input type="button" value="Get Route" onclick="getRoute()">
<br>
<p id = 'p'><span id="routeInfo"></span></p>
</div>
Javascript
$(document).ready(function() {
var route = $('#input');
getRoute.click(function() {
var scriptTag = document.createElement('SCRIPT');
scriptTag.src = "https://wsdot.wa.gov/Traffic/api/Bridges/ClearanceREST.svc/GetClearancesAsJson?AccessCode=59a077ad-7ee3-49f8-9966-95a788d7052f&callback=myCallback&Route=" + route;
document.getElementsByTagName('HEAD')[0].appendChild(scriptTag);
var myCallback = function(data) {
var myarray = Array.prototype.slice.call(data);
document.getElementById("routeInfo").innerHTML = JSON.stringify(myarray);
}
});
});
It looks like you are jumping through a lot of hoops you don't need to. As long as you are using Jquery, you should look into getting the api data with an ajax request. It's much easier and more intuitive. Also you have a few problems such as trying to get the input value with var route = $('#input'); which return the actual input element. You are also processing the returned data in a way that won't work.
Here's a basic example to get you going on (IMO) a better track:
function getRoute() {
var route = $('#input').val();
var url = "https://wsdot.wa.gov/Traffic/api/Bridges/ClearanceREST.svc/GetClearancesAsJson?AccessCode=59a077ad-7ee3-49f8-9966-95a788d7052f&Route=" + route;
$.ajax({url: url, success: function(data){
var retValue = "";
var i = 0
for(i; i< data.length; i++) {
retValue += data[i].BridgeName + "<br>"
}
document.getElementById("routeInfo").innerHTML = retValue;
}});
}
If you intend functionality in the getRoute.click callback to run, you need to rewrite that as a method function getRoute(), or get the button element via jQuery and assign that to the variable getRoute. As it stands, you have the click method wired via the markup to a function named getRoute which does not exist. In the JS you are trying to register a click event to a jQuery object named getRoute which does not exist.
getRoute needs to be a global function for it to be called from html :
getRoute = (function() {
Also, myCallback needs to be a global function for it to be called from your loaded script (just remove the var):
myCallback = function(data) {

Show image after button click

I have a controller method that returns image in byte array, from MongoDB, and I want to show it in my view:
<HttpPost()>
Function ShowImage(id As String) As FileContentResult
Dim Handler = New MongoDBHandler()
Dim newString = id.Replace(vbLf, "").Trim().Replace("""", String.Empty)
Dim byteArray = Handler.ReadImage(newString)
Return File(byteArray, "image/png")
End Function
I have the javascript function:
function postCardNumber(elm) {
var CardNumber = $(elm).closest("tr").find(".card-number").html();
var $img = $('<img>');
$img.attr("src", "/MyController/MyMethod/CardNumber");
$("#myModal").append($img);
}
The Table:
When the "Show" button click, on the table, the "No." cell (and is data) is sent to the JS function, and pass to the controller, then i try to create new image element with, and add it to my popup modal for show.
The problem is i cant get the controller response, and spent hours in google search for it, any solutions please?
try following and check if it work. Please verify that the controller name you are specifying in following URL is correct.
I am not sure that your controller name is "MyController". check it and change if it is wrong.
If following code doesn't work, send me the url it generated in comment
function postCardNumber(elm) {
var CardNumber = $(elm).closest("tr").find(".card-number").html();
var $img = $('<img>');
$img.attr("src", "#(Url.Action("ShowImage","CreditCard"))/" + CardNumber);
$("#myModal").append($img);
}

JavaScript Query Json String from (api.census.gov)

I have an API which should return some text JSon String.
http://api.census.gov/data/2010/sf1?get=P0010001&for=county:013&in=state:08
I wan to use JavaScript to query this API and display in the HTML element. The code looks like this:
//html
<input type="submit" value="Get City" onclick=" getpop()">
//JS:
function getpop() {
var nereq2 = new XMLHttpRequest();
nereq2.open("GET", "http://api.census.gov/data/2010/sf1?get=P0010001&for=county:013&in=state:08", true);
nereq2.onreadystatechange = function () {
if (nereq2.readyState == 4) {
var temp3 = nereq.response; **//problem start at here, which always return empty*******
document.getElementById("fs").innerHTML = temp3;
};
};
nereq2.send();
}
When I click the link it returns the JSon properly, however when I use the code to query, it returns empty. I don't know whether it related to the browser setup or there are some other issues?
You have a typo. nereq.response should be nereq2.response.
Working JSFiddle - (using https here because JSFiddle requires that)

Oracle APEX & JavaScript - Passing name of textfield in function NOT value

I have a function that will need the Name of a textfield, like P12_ACCOUNT_ID But when I call a function on that page with: callMyFunction('P12_ACCOUNT_ID'); it will pass the value of this textfield on to the function.
Is there a way to create a link to URL which will be javascript, and make P12_ACCOUNT_ID a varchar?
Just to be clear: I want my function to work with the varchar: 'P12_ACCOUNT_ID' and not with the value of that textfield.
This is the function to be called in which I want my page item to be loaded.
The link to this function now is: javascript:callMyPopup('P12_ACCOUNT_ID') but when it retrieves the content of this textfield and doesn't pass the string on by itself.
<script language="JavaScript" type="text/javascript">
function callMyPopup (paramItem) {
var hiddenField = document.getElementById(paramItem).value;
var url;
url = 'f?p=&APP_ID.:3:&APP_SESSION.::::P3_HIDDEN:' + hiddenField;
w = open(url,"winLov","Scrollbars=1,resizable=1,width=800,height=600");
if (w.opener == null)
w.opener = self;
w.focus();
}
</script>
As provided by Jeffrey Kemp but he didn't post an answer and I do want to close this question:
In Apex you can get the value of an item using $v(paramItem).

global site variable js

I am new to javascript, i am trying to make a small site with two HTML pages (A and B) and a global js file.
So lets say i have selected certain items in page A, the list-preview on Page A gets updated.
But if i want to see the list in detail i have to go to page B.
Page A and B bith use the same .js file, the selected items are saved in a array.
How do i make sure the selected items still stay in the array, and the array doesn't get flushed when i go from page A to page B ?
what i thought of was ...
var selectedProductsName = new Array();
in OwnJS.js
the adding items to the preview list works.
i'm only struggling to keep the array unflushed when i go to page B from page A.
HTML5 introduces a new thing called localStorage. It's basically some kind of storage that is persistent between all pages of your website as well as between user sessions. It can be accessed as a simple key/value store:
var selectedProductsName = localStorage.getItem("selectedProductsName");
And to set:
localStorage.setItem("selectedProductsName", []);
Here's an article about getting started with localStorage, if you want to be able to do more things like checking browser compatibility for localStorage and watching the storage event, among others.
You could use the HTML5 local storage. It lets you tell the browser to save data on the user's machine. (There's also session storage, valid only for the current session.)
Save (in Apply.html)
IN.API.Profile("me")
.fields(["id", "firstName", "lastName", "pictureUrl","headline","industry","location:(name)","positions:(title)","emailAddress"])
.result(function(result) {
profile = result.values[0];
// save all keys to local storage
for (f in profile) localStorage[f] = fields[f];
// more stuff ...
});
to Retrieve (in personal_Info.html)
// retrieve first name from local storage
var firstName = localStorage["firstName"];
if (firstName !== undefined) {
$("#textfield1").attr(value, firstName);
}
Source Page
The Source Page has an HTML Button with a jQuery Click event handler. When the Button is clicked, the values of the Name TextBox and the Technology DropDownList is set as QueryString Parameter and then the page is redirected to the Destination page (Page2.htm).
<input type="button" id="btnQueryString" value="Send" />
<script type="text/javascript">
$(function () {
$("#btnQueryString").bind("click", function () {
var url = "Page2.htm?name=" + encodeURIComponent($("#txtName").val()) + "&technology=" + encodeURIComponent($("#ddlTechnolgy").val());
window.location.href = url;
});
});
</script>
Destination Page
On the Destination page (Page2.htm), inside the jQuery Page Load event handler the URL of the page is first checked to determine whether it has some QueryString Parameters being received, this is done by checking the window.location.search property. If it has some QueryString Parameters then loop is executed and each QueryString Key and Value Pair is inserted in an Array and finally the values are displayed on the page using the HTML span.
<script type="text/javascript">
var queryString = new Array();
$(function () {
if (queryString.length == 0) {
if (window.location.search.split('?').length > 1) {
var params = window.location.search.split('?')[1].split('&');
for (var i = 0; i < params.length; i++) {
var key = params[i].split('=')[0];
var value = decodeURIComponent(params[i].split('=')[1]);
queryString[key] = value;
}
}
}
if (queryString["name"] != null && queryString["technology"] != null) {
var data = "<u>Values from QueryString</u><br /><br />";
data += "<b>Name:</b> " + queryString["name"] + " <b>Technology:</b> " + queryString["technology"];
$("#lblData").html(data);
}
});
</script>

Categories

Resources