Is it possible to get Javascript array in JSP page - java

I am developing a web application in which I which I have a JavaScript array and I want this array in my JSP page and iterate it save the data in database.
var value = response;
for (var key in value) {
if (value.hasOwnProperty(key)) {
alert(key + " -> " + value[key]);
var sample = new Array();
sample=value[key];
console.log(sample);
// document.getElementById('');
}
}
});
I want this data on my JSP page is it possible. If it is possible, then how?

You can have javascript in jsp but that will always execute on client side. So if you want to save some stuff on trigger of some event inside browser you can do that by making ajax call or form submission. Ajax is preferred way because its faster and better experience for user
But if you have intention of execution of javascript on server side thats not possible

Java script client side script whereas jsp is server side script so you can't simply do this.
What you can do is submit the calculated variable from javascript to server by form-submission, or using URL parameter or using AJAX calls and then you can make it available on server to store in database.
Client Side:
<script type="text/javascript">
var n = document.getElementById("data");
var f=new Array( "apple", "orange", "mango" );
n.value = f;
</script>
<form action="Your_JSP.jsp" method="POST">
<input type="hidden" id="data" name="data" value="" />
<input type="submit" />
</form>
Server Side:
<%
String val = request.getParameter("data");
String aa[]=val.split(",");
for(String x : aa )
out.println(x);
//now hereyou can use aa array tostore in database or do whatever you want
%>

Try this if you have two different jsp:
first.jsp
<script>
var response = [];
...
var put = function(form) {
form.resp.value = response.join(','); //using comma as separator
};
</script>
<form onsubmit='put(this)' method='next.jsp' method='post'>
<input type='hidden' name='resp' />
<button>Submit</button>
</form>
next.jsp
<%
String[] resp = request.getParameter("resp").split(",");
%>
Response is: ${param.resp} <!-- debugging -->

yes , its possible to do that. you can show array in HTML tag
<!DOCTYPE html>
<html>
<head>
<script>
var value=response;
for (var key in value) {
if (value.hasOwnProperty(key)) {
alert(key + " -> " + value[key]);
var sample = new Array();
sample=value[key];
console.log(sample);
// do here as
document.getElementById("array").innerHTML = sample;
// here array is <p> tag in html and sample is array which will be shown in jsp page.
}
}
</script>
</head>
<body>
<form action="get.jsp" method="POST">
<p id="array" name="array" type="hidden"></p>
<input type="submit" />
</body>
</html>
in get.jsp you will able to get value from array as:
<%
String []array = request.getParameter("array").split(",");
//this String array you can use to store data in DB
%>

Related

How to send dropdown value to servlet NOT the option text

I have dropdown with options and the values. I can get the option value by the dropdown name in servlet but how can i get the dropdown "value" in servlet. In screenshot, temporarily i concatenated the with options but i want to store value in variable in servlet.
Please help:
HTML:
<input type="text" name="taxiDropdown" id= "taxiDropdown" placeholder="Search taxi...">
</div>
<div class="scrolling menu">
<%
List eList = (ArrayList) session.getAttribute("taxiInfo");
%>
<%
for (int i = 0; i < eList.size(); i++) {
%>
<div class="item" data-value="<%=((TaxiInfo) eList.get(i)).getID()%>">
<div class="ui green empty circular label"></div>
<%=((TaxiInfo) eList.get(i)).getTaxiPlate() +" "+ ((TaxiInfo) eList.get(i)).getID() %>
</div>
<%
}
%>
</div>
</div>
Servlet:
String val = request.getParameter("taxiDropdown");
(in "val", I want to store the value of the dropdown not the option text)
In JSP you should have something like that:
<form method="post">
<select name="taxiDropdown" id="taxiDropdown">
<%
List<TaxiInfo> eList = (List<TaxiInfo>) request.getAttribute("taxiInfo");
for (TaxiInfo taxiInfo : eList) {
%>
<option name="<%=taxiInfo.getTaxiPlate()%>" value="<%=taxiInfo.getID()%>"><%=taxiInfo.getTaxiPlate()%></option>
<%
}
%>
</select>
<input type="submit" />
</form>
Then in controller/servlet you will receive the id of TaxiInfo:
String val = request.getParameter("taxiDropdown");
System.out.println(val);
Or in your case you should set a hidden input with javascript with desired value.
added this code in html:
Move value of the dropdown selection to hidden textbox
<script type='text/javascript'>
$(function() {
$('#driverdp').change(function() { <-- this is my dropdown -->
var x = $(this).val();
$('#driverid').val(x); <-- this is my textbox -->
});
});
</script>
Servlet:
get the value of hidden text in servlet
String text= request.getParameter("driverId");
hope it will help someone

Input tag won't work with JQuery Ajax properly

I made a code where when the client types something in the input, it will send the data to a jsp file to evaluate, and if the data equals "James", it will say "Hello James". The problem is that the input tag won't display your input, and only takes 1 input
jQuery w/ input
<fieldset>
<form style="padding:15px;">
<label for=name>Enter Name:</label>
<input type="text" name="name" id="name">
</form>
</fieldset>
<div id="result"></div>
<script>
$(document).ready(function() {
$("input").keypress(function(event) {
event.preventDefault();
var name = $("#name").val();
var send = {
name: name
};
$.ajax({
type: "POST",
url: "process2.jsp",
data: send,
success: function(data) {
$("#result").html(data);
}
})
});
});
</script>
-----------------------
JSP FILE:
<%
String name = request.getParameter("name");
if(name.equals("James")){
out.println("Hello James");
} else {
out.println("Hello User");
}
%>
The problem with your code ist that you are assigning the name variable incorrectly. Instead of writing.
var name = $("#name").val();
You should write
var name = event.target.value;
Otherwise you are assigning the same value over and over again with every key press, making it impossible to type more than a single character.

text field name should be unique

I am working on a project where the client's requirement is to add a dynamic text box. I made the dynamic text box but I'm not getting the unique name of the text box.
Here is my code:
<script type="text/javascript">
function addfieldset() {
var namefieldset = document.getElementById("name").cloneNode(true);
document.getElementById("names").appendChild(namefieldset);
}
function deletefieldset(e) {
var namefieldset = e.parentNode;
namefieldset.parentNode.removeChild(namefieldset);
}
</script>
<body>
<%! public static int i = 1;%>
<% if (i > 0) { %>
<div id="names"><div id="name"><% out.print(i);%>Name: <input name="namefield<%= i%>" type="text"/>delete</div></div>
<input id="addnamebtn" type="button" value="Add Name" onclick="addfieldset()"/>
<% i++;
}%>
</body>
You are mixing two different codes. The key is to realize, where and when each code is executed - JSP on the server when the page is requested and rendered (i.e. before the response is sent to the browser) and Javascript in the browser, after the browser receives the already generated response.
I.e. you have to change the name of the new text field in the addfieldset() function (which means you have to have a counter, how many text fields there already is).
The java code in scriptlet is executed on the server side. Hence, cloning it again through Javascript will not execute the scriptlet again.
An another approach of what you are trying to achieve will be to store the count variable in javascript.
var count = 1;
function addfieldset() {
count++;
var namefieldset = document.getElementById("name").cloneNode(true);
var textField = namefieldset.getElementsByTagName('input')[0];
textField.setAttribute("name", "namefield" + count);
textField.value = "";
document.getElementById("names").appendChild(namefieldset);
}
function deletefieldset(e) {
var namefieldset = e.parentNode;
namefieldset.parentNode.removeChild(namefieldset);
}
<body>
<div id="names">
<div id="name">
<span>Name:</span>
<input name="namefield1" type="text" />
delete
</div>
</div>
<input id="addnamebtn" type="button" value="Add Name" onclick="addfieldset()" />
</body>
try this JavaScript and HTML
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<script type="text/javascript">
var i = 0;
function generateRow() {
i++;
var d = document.getElementById("div");
d.name = "food";
d.innerHTML += "<p>name"+i+" :<input type='text' name='name" + i + "' /> <a href='#' onclick='deletefieldset(this)'>delete</a></p>";
}
function deletefieldset(e) {
var namefieldset = e.parentNode;
namefieldset.parentNode.removeChild(namefieldset);
}
function onLoad() {
generateRow();
}
window.onload = onLoad;
</script>
<body>
<div id="div"></div>
<p>
<input type="button" id="addnamebtn" value="Add Name" onclick="generateRow()" />
</p>
</body>
</html>

Initialize JavaScript variable with java

Can we initialize JavaScript variables with java in jsp page?
like,
<script type="text/javascript">
var refreshId = setInterval(function() {
var nv=<% out.print(num_voted); %>;
var tv=<%out.print(totalvoted); %>;
var m=<% out.print(month);%>;
var y=<% out.print(year);%>;
alert("refreshed");
$('#alertmessagebox').text("Total members voted "+nv+" out of "+tv+" for "+m+" " +y);
}, 9000);
$.ajaxSetup({ cache: false });
</script>
Code is not working as expected. :(
Is there way to do this? Why it is not possible by this way? shall we need to create header to do this?
Here is an example of setting Javascript variables in a JSP.
<head>
<%
String numVotedStr = request.getParameter("numvoted");
int numVoted = 0;
if (numVotedStr != null) {
numVoted = Integer.parseInt(numVotedStr);
}
%>
<script type="text/javascript">
function setInterval() {
alert("hello " + <%= numVoted %>);
}
</script>
</head>
<body>
<form>
<input type="button" onclick="setInterval()" value="Press Me"/>
</form>
</body>
</html>
To test, use the appropriate version of this URL:
http://localhost:8080/sandbox/example.jsp?numvoted=99
This will popup an alert box with the integral value of "numvoted" on the HTTP request, by producing an HTML page where the value is initialized in Javascript. (The code should have at least a try-catch for the parseInt() call, but this will serve as simple example.)

retrieve value of arraylist in javascript in same page

There is a JSP page in which i have an ArrayList variable. I need these arraylist values(txt1 and txt2) in script tag.I have tried lots of combinations and googling but didnot succeed.
javascript function
function fun1()
{
// how to get arraylist values
}
JSP page:
<body>
<%
ArrayList<String> al= new ArrayList<String>();
al.add("txt1");
al.add("txt2");
out.println("<input type=text id=" + al.get(0) + ">");out.println("<br>");
out.println("<input type=text id= " + al.get(1) + ">");out.println("<br>");
out.println("<input type=button id=btn1 value=click onClick=fun1(); > ");
%>
</body>
Thanks for reply
Inside javascript you can use Scriplets very well
Assume the list 'arrayList' is having [1,2,3,4] in java (JSP)
you can get the array list by this
function fun1()
{
var list = '<%= arrayList %>';
}
if you print the variable list, it will be a string with value '[1,2,3,4]'
You can then split this using Regex or simple string operation
<body>
<%
ArrayList<String> al= new ArrayList<String>();
al.add("txt1");
al.add("txt2");
out.println("<input type=text id=" + al.get(0) + ">");out.println("<br>");
out.println("<input type=text id= " + al.get(1) + ">");out.println("<br>");
out.println("<input type=button id=btn1 value=click onClick=fun1(); > ");
%>
</body>
<script>
// try the script here
</script>
Try something like this.
<script>
var myArray=new Array();
myArray[0] = '<%= al.get(0) %>';
myArray[1] = '<%= al.get(1) %>';
<script>
You could create a script tag which creates an array in js that holds all you values. I'm not familar with jsp but deppending on oyur code it could look like:
out.println("<script type='text/javascript'>");
out.println("var myJsArray = new Array();");
foreach(var arrayMember in al)
{
out.println("myJsArray.push(" + arrayMember + ");");
}
out.println("</script>");
In Js just use the array:
function fun1()
{
var firstArrayMember = myJsArray[0];
// or whatever you want to do
}
You could also use assoziativ arrays if you have a key for a specific array member.
Hope you got the idea
I would have the Java code somewhere else, but if you insist on having it inside your JSP, try having readable HTML and only output Java content using <%=...%> - something like this:
<%
ArrayList<String> list = new ArrayList<String>();
list.add("text1");
list.add("text2");
%>
<body>
<form ...>
<input type="text" id="<%=list.get(0)%>" />
<input type="text" id="<%=list.get(1)%>" />
<input type="button" id="button1" value="Click" onclick="functionOne();" />
</form>
<script type="text/javascript">
function functionOne() {
alert(document.getElementById("<%=list.get(0)%>").value);
}
</script>
</body>

Categories

Resources