Here i'm attempting to load a form using ajax and set to "maindiv" upon clicking a button "Add Item".but returns undefined. A servlet named "AddItem" also exists..
html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<input type="button" onclick="loadAddItemForm()" value="Add Item"/>
<div id="maindiv"> </div>
<script>
function loadAddItemForm() {
var x;
if (window.XMLHttpRequest) {
x = new XMLHttpRequest();
}
x.onreadystatechange = function () {
if (x.readyState == 4 && x.status == 200) {
//
var txt = "ItemCode:" + "<input type='text' id='itemcodetxt'><br>" + "ItemName:" + "<input type='text' id='itemnametxt'><br>" + "Description:" + "<input type='text' id='descriptiontxt'><br>" + "QtyOnHand:" + "<input type='text' id='qtyonhandtxt'><br>" + "Reorderlevel:" + "<input type='text' id='reorderleveltxt'><br>" + "Unit price:" + "<input type='text' id='unitpricetxt'><br><input type='button' value='Add' onclick='addItem()'/>";
}
document.getElementById("maindiv").innerHTML = txt;
};
x.open("GET", "AddItem", true);
x.send();
}
</script>
</body>
You're not passing in the page, try
x.open("GET", "AddItem.html", true);
assuming that's the page you waant to open.
it's returning false because it's looking for AddItem, and as it's returning false the txt is undefined as the if block isn't executed
Related
I have a JSON data retrieved from Spring boot controller as:
[
{
"surgeonId": 13505,
"surgeonNationalID": 308236823,
"surgeonFirstName": "Ali",
"surgeonLastName": "Zah",
"surgeonNationality": "UK",
"surgeonDateOfBirth": "1969-03-10T21:00:00.000+00:00",
"surgeonGender": "Male",
"surgeonAddress": "322 Diplomatic Dist.",
"surgeonConact": "02277469",
"surgeonEmailAddress": "ali#hotmail.com",
"surgeonSpeciality": "GS",
"departmentIdInSurgery": 31
},
{
"surgeonId": 13000,
"surgeonNationalID": 492487233,
"surgeonFirstName": "Sami",
"surgeonLastName": "Abdulkareem",
"surgeonNationality": "Canada",
"surgeonDateOfBirth": "1960-12-11T21:00:00.000+00:00",
"surgeonGender": "Male",
"surgeonAddress": "74 Aiano Dis.",
"surgeonConact": "02323322",
"surgeonEmailAddress": "sami#yahoo.com",
"surgeonSpeciality": "GS",
"departmentIdInSurgery": 31
}
]
And HTML as:
<td>
<div id="SurgeonId">
<select >
<option value="" disabled>Select Department First</option>
</select>
</div>
</td>
And this is the JavaScript code in the HTML page:
<script type ="text/javascript">
function showSurgeons(str) {
var xmlhttp;
if (str == "") {
document.getElementById("txtHint").innerHTML = "";
return;
}
if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var ourData = JSON.parse(xmlhttp.responseText);
var innerHTMLTest = '<select th:field="${waitinglist.waitingListSurgeonId}"> ';
for(i=0; i<ourData.length; i++){
innerHTMLTest +=' <option th:value="'+ ourData[i].surgeonId + '" th:text="' + ourData[i].surgeonLastName + '"> </option>';
console.log('inside loop' + innerHTMLTest);
}
innerHTMLTest += ' </select>';
console.log(innerHTMLTest);
alert(document.getElementById("SurgeonId").innerHTML);
document.getElementById("SurgeonId").innerHTML = innerHTMLTest;
}
}
xmlhttp.open("GET", "/surgeon/" + str, false);
xmlhttp.send();
}
</script>
However, I do not get the expected outcome as you can see in the images below:
The database missing the surgeonId data!
Also, as you can see below, I tried to inspect the code which seems right!
Thank you for the time spent guys :)
JavaScript isn't parsed through the Thymeleaf interpreter. When you have this code in JavaScript:
'<option th:value="'+ ourData[i].surgeonId + '" th:text="' + ourData[i].surgeonLastName + '"> </option>'
The browser sees
<option th:value="13505" th:text="Zah"></option>
th:value isn't a valid HTML attribute, nor is th:text. Those attributes are only only understood by the Thymeleaf interpreter. If you want your JavaScript to work, you have to use regular HTML attributes.
'<option value="'+ ourData[i].surgeonId + '">' + ourData[i].surgeonLastName + '</option>'
Which will output:
<option value="13505">Zah</option>
You will have to fix th:field="${waitinglist.waitingListSurgeonId}" as well.
Thanx to Maksim Zagorodsky in his post here
I managed to solve it :)
The HTML code:
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="ISO-8859-1">
<title>Add Procedure Form</title>
<link
href="https://cdn.jsdelivr.net/npm/bootstrap#5.0.2/dist/css/bootstrap.min.css"
rel="stylesheet"
integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC"
crossorigin="anonymous">
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script>
function sendAjaxRequest() {
var department = $("#department").val();
$.get(
"http://localhost:8080/surgerywaitinglist/getSurgeonsByDep?department="
+ department, function(data) {
$("#surgeonId").empty();
data.forEach(function(item, i) {
var option = "<option value = " + item + ">" + item
+ "</option>";
$("#surgeonId").append(option);
});
});
};
</script>
<script>
$(document).ready(function() {
$("#department").change(function() {
sendAjaxRequest();
});
});
</script>
</head>
<body>
<div class="container">
<br />
<h3>Add New Procedure</h3>
<br />
<hr />
<br />
<form th:action="#{/surgerywaitinglist/saveToWaitinList}" th:object="${waitinglist}"
method="POST">
<table class="table table-primary table-bordered table-striped"
id="employeeTable" style="width: 50%" align="center">
<tbody>
<tr>
<td>Department</td>
<td>
<div class="form-group">
<select name="departmentName"
th:with="departmentName = ${department.departmentName}"
class="form-control" id="department">
<option value="" th:selected="selected" th:disabled="disabled">select
option</option>
<option th:each="department: ${departments}"
th:value="${department.departmentName}"
th:text="${department.departmentName}"></option>
</select>
</div>
</td>
</tr>
<tr>
<td>Surgeon</td>
<td>
<div class="form-group">
<select th:field="${surgeon.surgeonLastName}"
class="form-control" id="surgeonId">
</select>
</div>
</td>
</tr>
</tbody>
</table>
</div>
</body>
</html>
Now I do get the expected outcome as you can see in the images below:
I try to save file on google drive and information in google sheets. But information in Sheets comes like Java.object.
Here is how it looks like in Code.gs :
var FOLDER_ID = '1jxBwrsz0JdBHcADpUUMespe';
var SHEET_ID = '1oJcKQ2RrtxxE1mn_CP-UAHefDxV7zg4';
function doPost(e) {
var data = Utilities.base64Decode(e.parameters.data);
var blob = Utilities.newBlob(data, e.parameters.mimetype, e.parameters.name);
var folder = DriveApp.getFolderById(FOLDER_ID);
var file = folder.createFile(blob);
folder.createFolder(name)
var res = [];
SpreadsheetApp.openById(SHEET_ID).getSheets()[0].appendRow([e.parameters.name, file.getUrl()].concat(res));
return ContentService.createTextOutput("Done.")
}
Here is how it looks like in the HTML file :
<form action="https://script.google.com/macros/s/AKfycbxkzg6ud1VyTI2W4gs-CRJRS3i3qLDXQIGevtyy/exec" id="form" method="post">
<div id="data"></div>
<div class="form-group">
<label for="name">Имя</label>
<input type="text" id='name' name="name" placeholder="Имя" />
</div>
<div class="form-group">
<label for="comment">Комм</label>
<input type="text" name="comment" placeholder="Комментарий" />
</div>
<input name="file" id="uploadfile" type="file">
<input id="submit" type="submit">
</form>
<script>
$('#uploadfile').on("change", function() {
var file = this.files[0];
var fr = new FileReader();
var name = $('#name').value;
fr.fileName = file.name
fr.onload = function(e) {
e.target.result
html = '<input type="hidden" name="data" value="' + e.target.result.replace(/^.*,/, '') + '" >';
html += '<input type="hidden" name="mimetype" value="' + e.target.result.match(/^.*(?=;)/)[0] + '" >';
html += '<input type="hidden" name="filename" value="' + e.target.fileName + '" >';
html += '<input type="hidden" name="name" value="' + name + '" >';
$("#data").empty().append(html);
}
fr.readAsDataURL(file);
});
</script>
Result in Google sheet
How to get data in a readable format?
Personally, I never use forms. Here's an examples that creates 5 text boxes. Validates that you put something into them and returns the code to the server via google.script.run for further processing (i.e. Logger.log the data). I create the html server side and loaded it on the on DOM ready event with JQuery.
Codes.gs
function buildForm(){
var s='';
for(var i=0;i<5;i++){
s+=Utilities.formatString('<br /><input class="jim" type="text" value="" id="%s" />%s',"txt" + i,"text" + Number(i+1));
}
s+='<br /><input type="button" value="Submit" onClick="getValues();" /><input type="button" value="Close" onClick="google.script.host.close();" />';
return s;
}
function saveValues(A){
for(var i=0;i<A.length;i++){
Logger.log('\nid=%s\nvalue=%s',A[i].id,A[i].value);
}
}
function showFormDialog(){
var ui=HtmlService.createHtmlOutputFromFile('form')
SpreadsheetApp.getUi().showModelessDialog(ui,'My Form');
}
form.html:
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
$(function(){
google.script.run
.withSuccessHandler(function(html){$('#form').html(html);})
.buildForm();
});
function getValues(){
var elements=document.getElementsByClassName('jim');
var el=[];
console.log('elements.length=%s',elements.length);
for(var i=0;i<elements.length;i++){
var obj={};
obj['id']='txt' + i;
obj['value']=$('#' + 'txt' + i).val();
el.push(obj);
}
var dataValid=true;
for(var i=0;i<el.length;i++){
console.log('id=%s, value=%s',el[i].id, el[i].value);
if(!el[i].value){
dataValid=false;
$('#'+el[i].id).css('background','#ffff00');
}else{
$('#'+el[i].id).css('background','#ffffff');
}
}
if(dataValid){
google.script.run.saveValues(el);
}else{
alert('Invalid Data Found...Try again sucker....');
}
}
console.log('MyCode');
</script>
<style>
input {margin:5px 5px 0 0;}
</style>
</head>
<body>
<div id="form"></div>
</body>
</html>
Looking to make YEAR the third search criteria that then leads to the example URL. I believe that there are 2 kinds of syntax to do this but if you could use this syntax I would appreciate it, and if you need to use another please explain why. Here is the plnkr I am trying to modify. http://plnkr.co/edit/RnCdfnrX0jy3RvmXjF56 Thank you.
"bmw":[
["1","series 1","http://www.example.com/bmw-1-series.htm"],
["2","series 3","http://www.example.com/bmw-2-series.htm"],
["3","series 5"],
["4","series 7"]
],
"mercedes":[
["6","class A"],
["7","class B"],
["8","class C"],
["9","class E"]
],
"audi":[
["10","a3"],
["11","a4"],
["12","a5"],
["13","a6"]
],
"volkswagen":[
["14","polo"],
["15","golf"],
["16","cady"]
]
Please take a look at this updated plunker or snippet: http://plnkr.co/edit/4zJoRr26CSSjPa3T74rs?p=preview
$(document).ready(function() {
var tabMarque = [];
$.getJSON('https://api.myjson.com/bins/e9xkz', function(data) {
// alert(data);
$.each(data, function(index, val) {
tabMarque[index] = val;
});
});
$('#Serie').change(function(event) {
// alert('Marque_change');
var marque = $('#Marque').val();
// alert(marque);
var htmlOption = '<option value="0">Choix du an</option>';
if (marque !== '0') {
var itemsMarque = tabMarque[marque];
//alert(JSON.stringify(itemsMarque));
$.each(itemsMarque, function(key, value) {
//alert("k=" + key + " v=" + JSON.stringify(value));
htmlOption += '<option value="' + value[0] + '">' + value[2] + '</option>';
});
}
$('#Year').empty();
$('#Year').html(htmlOption);
});
$('#Marque').change(function(event) {
// alert('Marque_change');
var marque = $(this).val();
// alert(marque);
var htmlOption = '<option value="0">Choix du serie</option>';
if (marque !== '0') {
var itemsMarque = tabMarque[marque];
//alert(JSON.stringify(itemsMarque));
$.each(itemsMarque, function(key, value) {
//alert("k=" + key + " v=" + JSON.stringify(value));
htmlOption += '<option value="' + value[0] + '" data-href="' + value[2] + '">' + value[1] + '</option>';
});
}
$('#Year').empty();
$('#Serie').html(htmlOption);
});
$('#go').click(function() {
//alert('go_click');
var selected = $('#Serie').find('option:selected');
var href = selected.data('href');
// alert('Go to: '+href);
window.location = href;
});
});
/* Put your css in here */
h1 {
color: red;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
<link rel="stylesheet" href="style.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</head>
<body>
<div>
<select id="Marque">
<option value="0">Choix du marque</option>
<option value="bmw">bmw</option>
<option value="mercedes">mercedes</option>
<option value="audi">audi</option>
<option value="volswagen">volswagen</option>
</select>
<select id="Serie"></select>
<select id="Year"></select>
<input type="button" id="go" value="Go!" />
</div>
</body>
</html>
Currently am having a form which detects the user input text and prints the respective text,but my issue is if user want to input as ctrl key how can i accomplish that
For example :
If user presses key a it will get displayed,but at the same time if user press cntrl key it should also get displayed.
Fiddled here.
<script src= "http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<div ng-app="">
<p>Choose your control</p>
<p>Option : <input type="text" ng-model="name"></p>
<p ng-bind="name"></p>
Thanks
Here is you answer for control key detect with angular JS:
angular.module("mainModule", [])
.controller("mainController", function ($scope)
{
// Initialization
$scope.onKeyDownResult = "";
$scope.onKeyUpResult = "";
$scope.onKeyPressResult = "";
// Utility functions
var getKeyboardEventResult = function (keyEvent, keyEventDesc)
{
return keyEventDesc + " (keyCode: " + (window.event ? keyEvent.keyCode : keyEvent.which) + ")";
};
// Event handlers
$scope.onKeyDown = function ($event) {
if($event.keyCode === 17)
{
$scope.name += " ctrl ";
$scope.onKeyDownResult = getKeyboardEventResult($event, name);
}
else if($event.keyCode === 16)
{
$scope.name += " shift ";
$scope.onKeyDownResult = getKeyboardEventResult($event, name);
}
else if($event.keyCode === 18)
{
$scope.name += " Alt ";
$scope.onKeyDownResult = getKeyboardEventResult($event, name);
}
else
{
$scope.onKeyDownResult = getKeyboardEventResult($event, name);
}
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.0-beta.1/angular.min.js"></script>
</head>
<body ng-app="mainModule">
<div ng-controller="mainController">
<label>Type something:
<input type="text"
ng-keydown="onKeyDown($event)"
ng-model="name" />
</label><br />
<p>KEY DOWN RESULT:<p>{{name}}<br />
</div>
</body>
</html>
Hope it helps.
See AngularJS keyboard events: http://www.angularjshub.com/examples/eventhandlers/keyboardevents/
You can capture keycodes by using these events on input box:
<input type="text"
ng-keydown="onKeyDown($event)"
ng-keyup="onKeyUp($event)"
ng-keypress="onKeyPress($event)" />
Try to use "ng-keypress=check($event)", the $event object have "keyCode", check the keyCode and update your model inside the function.
Ctrl is keycode 17. So inside your function you will check specific keys like this: if($event.keyCode === 17){ $scope.model += " ctrl" };
You can see all keycodes here: http://www.cambiaresearch.com/articles/15/javascript-char-codes-key-codes
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?