How to get values from dynamically created(ajax) textboxes in jsp? - html

here is my code
index.html:
<html>
<head>
<script language="javascript">
var xmlHttp;
var f=1;
var t = "text";
function showState()
{
if (typeof XMLHttpRequest != "undefined"){
xmlHttp= new XMLHttpRequest();
}
else if (window.ActiveXObject){
xmlHttp= new ActiveXObject("Microsoft.XMLHTTP");
}
if (xmlHttp==null){
alert ("Browser does not support XMLHTTP Request");
return
}
var url="additem.jsp";
xmlHttp.onreadystatechange = stateChange;
xmlHttp.open("GET", url, true);
xmlHttp.send(null);
}
function stateChange(){
if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete"){
document.getElementById(t).innerHTML=xmlHttp.responseText;
t = "text"+f.toString();
f=f+1;
}
}
</script></head>
<body>
<center>
<form action=AddProd1.jsp method=post>
Enter Catagory <td><BLOCKQUOTE></BLOCKQUOTE><BLOCKQUOTE><center><input type=text name=catagory></BLOCKQUOTE></td>
</center>
<br><br>
<div id='text'></div><br>
<input type=submit value=Submit>
</form>
<input type=submit value=new onclick="showState();">
</body></html>
additem.jsp:
<jsp:useBean id="ob" class="te.tes" scope="session" />
<%!
String value = "";
String t = "" ;
String v="";
%>
<%
v=ob.Increase();
value = "product" + v;
t = "text" + v;
%>
<html>
<input type=text name=product value="<%=value%>">
<div id='<%=t%>'></div><br>
</html>
AddProd1.jsp:
<% int i;
String [] value = request.getParameterValues("product")
for(i=0;i<value.length;i++)
out.println(value[i]);
%>
I am getting exception in "value.length" in AddProd1.jsp no matter what i try....I even tried to get one value by only putting request.getParameter("product")...But i get null value in return ....what am i doing wrong??? Thanx in advace..

Related

jsp page being overwritten by JSON data being sent from Servlet

I am trying to send JSON data to my JSP page from a servlet.
AS soon as I run the JSP, the whole of JSP gets overwritten by the JSON content. why is this happening? This is part of my JSP page.
<%# page import="java.util.ArrayList" %>
<head>
<script>
function populateTypeOfWork(workType) {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
var work = JSON.parse(this.responseText);
workType.options.length = 0;
for (i = 0; i < work.length; i++) {
createOption(workType, workDesc[i], workDesc[i]);
}
}
xhttp.open("GET", "ServletRequest", true);
xhttp.send();
}
}
function createOption(dropdown, text, value) {
var x = document.createElement('option');
x.value = value;
x.text = text;
dropdown.options.add(x);
}
</script>
</head>
<body>
<label>Work Category **</label>
<select id="workCategory"
onchange="populateTypeOfWork(document.getElementById('workTypeDesc1'))"
size=1
style="width:95%;" required>
<option value="" selected>Select A Work Category</option>
<% ArrayList workCategory = (ArrayList)
request.getAttribute("workCategory");
for (int i = 0; i < workCategory.size(); i++) {
%>
<option value="<%=workCategory.get(i)%>"><%=workCategory.get(i)%>
</option>
<% } %>
</select> <br>
<label>Type Of Work **</label>
<select id="workTypeDesc1" size=1 style="width:95%;" required>
<option value="" selected>Type of Work</option>
</select>
</body>
</html>
Servlet
String json = new Gson().toJson(arraylistvar);
res.setContentType("application/json");
PrintWriter pw = res.getWriter();
pw.flush();
pw.close();
req.setAttribute("viewURL","/page1.jsp");
Why does stackoverflow keep asking me to add more details? because its mostly code..?? why should I fill this post unnecessaily?
There are two problems I can see with the current code: (1) you are referencing a non-existent variable workDesc; it appears you should reference the variable named work instead, and (b) the code that sends the AJAX request is inside the onreadystatechange() event handler, when it should actually execute right after the event handler is set. Here is the revised code snippet:
xhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
var work = JSON.parse(this.responseText);
workType.options.length = 0;
for (i = 0; i < work.length; i++) {
createOption(workType, work[i], work[i]);
}
}
}
xhttp.open("GET", "ServletRequest", true);
xhttp.send();
This might be due to how the request is being made from your web page. You should be using an AJAX call; make sure you are not submitting an ordinary form or changing the URL of the page within your JavaScript.

Can You Find Any Error in This Connectivity With Ajax code? I can not get any output from this

Here in this code I am fetching records from mysql with the use of ajax technology. But I have some error in this. Kindly say me what is my fault.
demo.html file:
<html>
<head>
<title>Demo Program</title>
</head>
<body>
<script type="text/javascript">
function myfunction(){
var myvar;
try{
myvar = new XMLHttpRequest();
}
catch(e){
try{
myvar = new ActiveXObject("Msxml2.XMLHTTP");
}
catch(e){
try{
myvar = new ActiveXObject("Microsoft.XMLHTTP");
}
catch(e){
alert("Your Browser Does Not Support");
return false;
}
}
}
myvar.onreadystatechange = function(){
if(myvar.readyState == 4){
var blankdiv = document.getElementById("blankdiv");
blankdiv.innerHTML = myvar.responseText;
}
}
var age = document.getElementById('age').value;
var wpm = document.getElementById('wpm').value;
var sex = document.getElementById('sex').value;
myvar.open("GET","demo.php",true);
myvar.send(null);
}
</script>
<form name="myform" method="post">
Max Age: <input type="text" name="age"></input><br><br>
Max WPM: <input type="text" name="wpm"></input><br><br>
Sex:
<select name="sex">
<option value="M">M</option>
<option value="F">F</option>
</select>
<input type="submit" onsubmit="myfunction()" value="Click Here"></input>
</form>
<div id="blankdiv">Resul Will Be Here</div>
</body>
</html>
demo.php file:
<?php
$host = "localhost";
$db = "demodb";
$user = "root";
$pass = "";
mysql_connect($host,$user,$pass);
mysql_select_db($db);
$age = $_POST['age'];
$sex = $_POST['sex'];
$wpm = $_POST['wpm'];
$query = "SELECT * FROM demodb WHERE sex = '$sex'";
$query_result = mysql_query($query);
?>
<table>
<tr>
<th>Name</th>
<th>Age</th>
<th>Sex</th>
<th>WPM</th>
</tr>
<?php
while($row = mysql_fetch_array($query_result)){
echo "
<tr>
<td>$row['name']</td>
<td>$row['age']</td>
<td>$row['sex']</td>
<td>$row['wpm']</td>
</tr>
";
}
?>
</table>
I can not find any output from this...please help me. I have tried alot to solve this still not finding what is the error in this.

HTML Drag and Drop and Struts

I've been trying to implement the new "Drag and Drop" file and upload feature, using the code from SitePoint.com. I am using Struts Framework as well. FormFile made my uploads easier, I could just hit on "choose" and click away. But, I just can't seem to get it to work the DnD with Struts. The ActionForm validates and reports that the file size is 0! Here's the code from SitePoint.com (js):
(function() {
// getElementById
function $id(id) {
return document.getElementById(id);
}
// output information
function Output(msg) {
var m = $id("messages");
m.innerHTML = msg + m.innerHTML;
}
// file drag hover
function FileDragHover(e) {
e.stopPropagation();
e.preventDefault();
e.target.className = (e.type == "dragover" ? "hover" : "");
}
// file selection
function FileSelectHandler(e) {
// cancel event and hover styling
FileDragHover(e);
// fetch FileList object
var files = e.target.files || e.dataTransfer.files;
// process all File objects
for (var i = 0, f; f = files[i]; i++) {
ParseFile(f);
UploadFile(f);
}
}
// output file information
function ParseFile(file) {
Output(
"<p>File information: <strong>" + file.name +
"</strong> type: <strong>" + file.type +
"</strong> size: <strong>" + file.size +
"</strong> bytes</p>"
);
// display an image
if (file.type.indexOf("image") == 0) {
var reader = new FileReader();
reader.onload = function(e) {
Output(
"<p><strong>" + file.name + ":</strong><br />" +
'<img src="' + e.target.result + '" /></p>'
);
}
reader.readAsDataURL(file);
}
// display text
if (file.type.indexOf("text") == 0) {
var reader = new FileReader();
reader.onload = function(e) {
Output(
"<p><strong>" + file.name + ":</strong></p><pre>" +
e.target.result.replace(/</g, "<").replace(/>/g, ">") +
"</pre>"
);
}
reader.readAsText(file);
}
else{
var reader=new FileReader();
reader.readAsDataURL(file);
}
}
// upload JPEG files
function UploadFile(file) {
var xhr = new XMLHttpRequest();
if (xhr.upload) {
// create progress bar
var o = $id("progress");
var progress = o.appendChild(document.createElement("p"));
progress.appendChild(document.createTextNode("upload " + file.name));
// progress bar
xhr.upload.addEventListener("progress", function(e) {
var pc = parseInt(100 - (e.loaded / e.total * 100));
progress.style.backgroundPosition = pc + "% 0";
}, false);
// file received/failed
xhr.onreadystatechange = function(e) {
if (xhr.readyState == 4) {
progress.className = (xhr.status == 200 ? "success" : "failure");
}
};
// start upload
xhr.open("POST", $id("upload").action, true);
xhr.setRequestHeader("X_FILENAME", file.name);
xhr.send(file);
}
}
// initialize
function Init() {
var fileselect = $id("fileselect"),
filedrag = $id("filedrag"),
submitbutton = $id("submitbutton");
// file select
fileselect.addEventListener("change", FileSelectHandler, false);
// is XHR2 available?
var xhr = new XMLHttpRequest();
if (xhr.upload) {
// file drop
filedrag.addEventListener("dragover", FileDragHover, false);
filedrag.addEventListener("dragleave", FileDragHover, false);
filedrag.addEventListener("drop", FileSelectHandler, false);
filedrag.style.display = "block";
}
}
// call initialization file
if (window.File && window.FileList && window.FileReader) {
Init();
}
})();
The jsp (just messing around):
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Upload File</title>
<link href="css/styles.css" rel="stylesheet" type="text/css" media="all"/>
</head>
<body>
<form id="upload" action="../Repositore/upload_file.do" method="POST" enctype="multipart/form-data">
<fieldset>
<legend>File Upload Form</legend>
<input type="hidden" id="MAX_FILE_SIZE" name="MAX_FILE_SIZE" value="20000000" />
<div>
<label for="fileselect">File to upload:</label>
<input type="file" id="fileselect" name="file" multiple="multiple" />
<div id="filedrag">or drop files here</div>
</div>
<div>
<table border='0' cellpadding='2'>
<tr><td><label for="ftags">Tags:</label></td><td> <input type='text' id="ftags" name='tags'/></td><td>(Separate by commas)</td></tr>
<tr><td><label for="desc">Description:</label></td><td> <textarea name="description" id="desc" rows="5" cols="30"></textarea></td></tr>
<tr><td><input type="checkbox" name="comment">Yes</input></td></tr>
</div>
<div id="submitbutton">
<button type="submit">Upload file</button>
</div>
</fieldset>
</form>
<div id="progress"></div>
<div id="messages">
<p>Status:</p>
</div>
<script src="js/filedrag.js" type="text/javascript"></script>
What could be wrong? Help?

Using POST method to send information to a URL with refresh

I am trying to simply use the POST method without having the page refresh
<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
<P>Light Control:
<FORM METHOD="POST" ACTION="http://192.168.100.106:8080/api/device/Light2"; enctype="application/json">
<P>Light On: <input type=hidden name=command value="on">
<UL></UL>
<P><INPUT TYPE=SUBMIT> </FORM>
Got it work just the way I needed... The AJAX JS is below the HTML (Thanks Simone)
HTML Code:
<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
<head>
<script src="js/ajaxsbmt.js" type="text/javascript"></script>
</head>
<title>HALnix</title>
<H1>HALnix - Test</H1>
<P>Light Control:
<table>
<tr>
<td>
<FORM name="Light14on" METHOD="POST" ACTION="http://192.168.100.106:8080/api/device/Light14"; enctype="application/json" onsubmit="xmlhttpPost('http://192.168.100.106:8080/api/device/Light14', '$
Master Bedroom Lamp<input type=hidden name=command value="on">
</td>
<td><INPUT TYPE=SUBMIT value="On"> </FORM>
</td>
<td>
<FORM name="Light14off" METHOD="POST" ACTION="http://192.168.100.106:8080/api/device/Light14"; enctype="application/json" onsubmit="xmlhttpPost('http://192.168.100.106:8080/api/device/Light14', $
<input type=hidden name=command value="off">
<INPUT TYPE=SUBMIT value="Off"> </FORM>
</td>
</tr>
</table>
AJAX JS Code (ajaxsbmt.js)
//##################################################################################
//## FORM SUBMIT WITH AJAX ##
//## #Author: Simone Rodriguez aka Pukos <http://www.SimoneRodriguez.com> ##
//## #Version: 1.2 ##
//## #Released: 28/08/2007 ##
//## #License: GNU/GPL v. 2 <http://www.gnu.org/copyleft/gpl.html> ##
//##################################################################################
function xmlhttpPost(strURL,formname,responsediv,responsemsg) {
var xmlHttpReq = false;
var self = this;
// Xhr per Mozilla/Safari/Ie7
if (window.XMLHttpRequest) {
self.xmlHttpReq = new XMLHttpRequest();
}
// per tutte le altre versioni di IE
else if (window.ActiveXObject) {
self.xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
}
self.xmlHttpReq.open('POST', strURL, true);
self.xmlHttpReq.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
self.xmlHttpReq.onreadystatechange = function() {
if (self.xmlHttpReq.readyState == 4) {
// Quando pronta, visualizzo la risposta del form
updatepage(self.xmlHttpReq.responseText,responsediv);
}
else{
// In attesa della risposta del form visualizzo il msg di attesa
updatepage(responsemsg,responsediv);
}
}
self.xmlHttpReq.send(getquerystring(formname));
}
function getquerystring(formname) {
var form = document.forms[formname];
var qstr = "";
function GetElemValue(name, value) {
qstr += (qstr.length > 0 ? "&" : "")
+ escape(name).replace(/\+/g, "%2B") + "="
+ escape(value ? value : "").replace(/\+/g, "%2B");
//+ escape(value ? value : "").replace(/\n/g, "%0D");
}
var elemArray = form.elements;
for (var i = 0; i < elemArray.length; i++) {
var element = elemArray[i];
var elemType = element.type.toUpperCase();
var elemName = element.name;
if (elemName) {
if (elemType == "TEXT"
|| elemType == "TEXTAREA"
|| elemType == "PASSWORD"
|| elemType == "BUTTON"
|| elemType == "RESET"
|| elemType == "SUBMIT"
|| elemType == "FILE"
|| elemType == "IMAGE"
|| elemType == "HIDDEN")
GetElemValue(elemName, element.value);
else if (elemType == "CHECKBOX" && element.checked)
GetElemValue(elemName,
element.value ? element.value : "On");
else if (elemType == "RADIO" && element.checked)
GetElemValue(elemName, element.value);
else if (elemType.indexOf("SELECT") != -1)
for (var j = 0; j < element.options.length; j++) {
var option = element.options[j];
if (option.selected)
GetElemValue(elemName,
option.value ? option.value : option.text);
}
}
}
return qstr;
}
function updatepage(str,responsediv){
document.getElementById(responsediv).innerHTML = str;
}

how to check uniqueness of a username in MySQL database via JSON?

I have this next page, on which a user can create a new account. My question now is how can i make sure the user inserts a username that doesn't already exist in my MySQL database. The page is available on http://webs.hogent.be/kevinbaeyens/gebruiker.html
the code of this page is:
<!doctype html>
<html class="">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Nieuwe gebruiker | Sociale buurt</title>
<link href="boilerplate.css" rel="stylesheet" type="text/css">
<link href="onzebuurt.css" rel="stylesheet" type="text/css">
<script type="text/javascript" src="jquery-1.7.1.min.js"></script>
<script type="text/javascript" language="javascript">
window.onload = function() {
document.getElementById("Username").focus();
};
function formulierValideren() {
if (document.getElementById('Username').value == '' || document.getElementById('Username').value == null)
{
alert ('Gebruikersnaam is verplicht.');
document.getElementById('Username').style.borderColor = "red";
return false;
}
else if (document.getElementById('Wachtwoord').value == '' || document.getElementById('Wachtwoord').value == null)
{
alert ('Wachtwoord is verplicht.');
document.getElementById('Wachtwoord').style.borderColor = "red";
return false;
}
else if (document.getElementById('Wachtwoord2').value == '' || document.getElementById('Wachtwoord2').value == null)
{
alert ('Bevestig wachtwoord.');
document.getElementById('Wachtwoord2').style.borderColor = "red";
return false;
}
else if (document.getElementById('Wachtwoord2').value != document.getElementById('Wachtwoord').value)
{
alert ('Wachtwoorden komen niet overeen.');
document.getElementById('Wachtwoord2').style.borderColor = "red";
return false;
}
else
{
var url = "http://localhost:8080/OnzeBuurt2/resources/gebruikers";
var reminder = {};
reminder.naam = jQuery.trim($("#Username").val());
reminder.wachtwoord = jQuery.trim($("#Wachtwoord").val());
var request = new XMLHttpRequest();
request.open("POST", url);
request.onload = function() {
if (request.status === 201) {
reminder.id = request.getResponseHeader("Location").split("/").pop();
} else {
console.log("Error creating reminder: " + request.status + " " + request.responseText);
}
};
request.setRequestHeader("Content-Type", "application/json");
request.send(JSON.stringify(reminder));
var msg = "Registratie succesvol. Klik op OK om u aan te melden op de site.";
if(confirm(msg)){
setTimeout(function() {window.location.href = "http://localhost:8080/OnzeBuurt2/"})
}
}
//end if
}//end function
</script>
</head>
<body class="body2">
<div class="gridContainer clearfix">
<div class="header2">
<center>
Nieuwe gebruiker
</center>
</div>
<div id="formulier2">
<form method="post" name="form" action="">
<p class="labels"><center>Gebruikersnaam *</center></p><input id="Username" type="text" name="Username" placeholder="Gebruikersnaam" size="50">
<p class="labels"><center>Wachtwoord *</center></p><input id="Wachtwoord" type="password" name="Wachtwoord" placeholder="Wachtwoord" size="50">
<p class="labels"><center>Bevestig wachtwoord *</center></p><input id="Wachtwoord2" type="password" name="Bevestig wachtwoord" placeholder="Bevestig wachtwoord" size="50">
<br />
<center><img id="return" name="jsbutton" src="return.png" alt="Terug" /></center>
<br />
<center><input id="bevestig" type="image" src="Bevestig.png" width="200" height="50" border="0" alt="SUBMIT!" onclick="formulierValideren()"></center>
<br />
</form>
</div>
</div>
</body>
</html>
Some notes you need to know:
1) since it's an assignment for school, I can't use PHP.
2) The primary key in my database table 'Gebruiker' is 'ID', the field of 'username' is the field which has to be unique
thanks in advance!