Unsure how to send image to backend using express file upload, - javascript

someone please help im trying to submit details together with image to databasei need help in figuring this whole thing out
<form id="register-form">
<!-- <div class="form-group">
<input type="file" id="imageInput" accept="image/*">
</div> -->
<div class="form-group">
<div class="file-upload">
<div class="image-upload-wrap">
<input name = 'sampleFile' enctype = "multipart/form-data" class="file-upload-input" type='file' id="profilepic" onchange="readImage(this)"
accept="image/*" />
<div class="drag-text">
<h3>Drag and drop a file or select add Image</h3>
</div>
</div>
<div class="file-upload-content d-none">
<img class="file-upload-image" src="#" id="imgPreview" />
<div class="image-title-wrap">
<button type="button" onclick="removeUpload()" class="remove-image">Remove <span
class="image-title">Uploaded Image</span></button>
</div>
</div>
</div>
</div>
<div class="form-group">
<label for="title">title:</label>
<input type="text" class="form-control" id="title" required>
</div>
<div class="form-group">
<label for="description">Description:</label>
<input type="text" class="form-control" id="description" required>
</div>
<div class="form-group">
<label for="release">Release:</label>
<input type="text" class="form-control" id="release" required>
</div>
<div class="form-group">
<label for="lang">Language_id:</label>
<input type="text" class="form-control" id="lang" required>
</div>
<div class="form-group">
<label for="rental_duration">Rental Duration:</label>
<input type="text" class="form-control" id="rental_duration" required>
</div>
<div class="form-group">
<label for="rental_rate">Rental rate:</label>
<input type="text" class="form-control" id="rental_rate" required>
</div>
<div class="form-group">
<label for="length">Length:</label>
<input type="text" class="form-control" id="length" required>
</div>
<div class="form-group">
<label for="replacement_cost">Replacement Cost:</label>
<input type="text" class="form-control" id="replacement_cost" required>
</div>
<div class="form-group">
<label for="rating">Rating:</label>
<input type="text" class="form-control" id="rating" required>
</div>
<div class="form-group">
<label for="special_features">Special Features:</label>
<input type="text" class="form-control" id="special_features" required>
</div>
<div class="form-group">
<label for="category_id">Category ID:</label>
<input type="text" class="form-control" id="category_id" required>
</div>
<div class="form-group">
<label for="actors">Actors:</label>
<input type="text" class="form-control" id="actors" required>
</div>
<div class="form-group">
<label for="store_id">Store_id:</label>
<input type="text" class="form-control" id="store_id" required>
</div>
<button type="submit" class="btn btn-primary">Register</button>
<button type="reset" class="btn btn-primary ml-5">Reset</button>
<button type="button" class="btn btn-primary ml-5" id="Logout">Log Out</button>
<!-- <input type="reset" value="Reset"> -->
</form>
</div>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"
integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"
integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1"
crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"
integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM"
crossorigin="anonymous"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script>
const baseUrl = "http://localhost:8081";
const token = localStorage.getItem("token");
const loggedInUserID = parseInt(localStorage.getItem("loggedInUserID"));
console.log(token, loggedInUserID)
// document.getElementById("addImage").addEventListener("change", function () {
// readImage(this);
//});
// document.getElementById("submitBtn").addEventListener("click", function () {
// var title = document.getElementById("title").value;
//});
function readImage(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
var imgPreview = document.getElementById("imgPreview");
imgPreview.src = e.target.result;
document.getElementById("imgPreview").style.display = "block";
};
reader.readAsDataURL(input.files[0]);
}
}
if (token === null || isNaN(loggedInUserID)) {
window.location.href = "http://localhost:3001/home";
} else {
$("#register-form").submit((event) => {
// prevent page reload
event.preventDefault();
const pic = $("#profilepic").val()
const title = $("#title").val();
const description = $("#description").val();
const release = $("#release").val();
const lang = $("#lang").val();
const rental_duration = $("#rental_duration").val();
const rental_rate = $("#rental_rate").val();
const length = $("#length").val();
const replacement_cost = $("#replacement_cost").val();
const rating = $("#rating").val();
const feature = $("#special_features").val();
const category_id = $("#category_id").val();
const actors = $("#actors").val();
const store_id = $("#store_id").val();
const requestBody = {
image: pic,
title: title,
description: description,
release_year: release,
language_id: lang,
rental_duration: rental_duration,
rental_rate: rental_rate,
length: length,
replacement_cost: replacement_cost,
rating: rating,
special_features: feature,
category_id: category_id,
actors: actors,
store_id: store_id
};
const formData = new FormData();
formData.append("image", pic);
formData.append("title", title);
formData.append("description", description);
formData.append("release_year", release);
formData.append("language_id", lang);
formData.append("rental_duration", rental_duration);
formData.append("rental_rate", rental_rate);
formData.append("length", length);
formData.append("replacement_cost", replacement_cost);
formData.append("rating", rating);
formData.append("special_features", feature);
formData.append("category_id", category_id);
formData.append("actors", actors);
formData.append("store_id", store_id);
let token = localStorage.getItem("token");
console.log(requestBody);
axios.post(`${baseUrl}/film`, formData, { headers: { "Authorization": "Bearer " + token } })
.then((response) => {
console.log(formData)
window.location.href = "http://localhost:3001/home";
})
.catch((error) => {
console.log(error);
if (error.response.status === 400) {
alert("Validation failed");
} else {
alert("Something unexpected went wrong.");
}
});
});
$("#Logout").click(function () {
window.localStorage.clear();
localStorage.removeItem("token");
localStorage.removeItem("loggedInUserID");
window.location.assign("http://localhost:3001/home");
});
}
</script>
const fileUpload = require("express-fileupload");
app.use(fileUpload());
app.post("/upload", (req, res) => {
if (!req.files || Object.keys(req.files).length === 0) {
return res.status(400).send("No files were uploaded.");
}
let sampleFile = req.files.sampleFile;
// Use the mv() method to place the file in a upload directory
sampleFile.mv("./upload/" + sampleFile.name, (err) => {
if (err) return res.status(500).send(err);
res.send("File uploaded!");
});
});
my html form code and app.js code i just cannot send image to database idk why, i try usin express file upload but the code just cannot insert it in. Someone, please help i have 48 hours left before my deadline please!!!!!! this is my first time doing this , someone guide me

Related

How to transfer image upload from form to backend upload?

I managed to upload an image in form, but i want to save it to backend and then when i call it again using frontend i will b able to save a picture
function code :
addFilm: (title, description, release_year, language_id, rental_duration, rental_rate, length, replacement_cost, rating, special_features, category_id, actors, store_id, callback) => { //1.(1 ~ 3 are places to change code )
var conn = db.getConnection(); // GET CONNECTION TO DB
conn.connect((err) => {
if (err) {
console.log(err);
return callback(err, null);
} else {
console.log('Connected Successfully!');
var SQLstatement = //use backtick to go onto next line
// first insert into film table
`insert into film (title,description,release_year,language_id,rental_duration,rental_rate,length,replacement_cost,rating,special_features)
Values(?,?,?,?,?,?,?,?,?,?)`; // 2.
conn.query(SQLstatement, [title, description, release_year, language_id, rental_duration, rental_rate, length, replacement_cost, rating, special_features], (error, result_id) => { //3.
if (error) {
console.log(error);
return callback(error, null);
}
else {
// second insert into film_category table
var SQLstatement = `insert into film_category (film_id,category_id) Values (?,?)`
conn.query(SQLstatement, [result_id.insertId, category_id], (error, result) => {
if (error) {
console.log(error);
return callback(error, null);
}
else {
console.log(result);
// neeed check actor
console.log(actors);
var SQLstatement = ''
values = []
// add a new actor id with the same film id to the film_actor table
for (var k = 0; k < actors.length; k++) {
if (k == actors.length - 1) {
SQLstatement += `(?,?)`
}
else {
SQLstatement += `(?,?),`
}
// console.log(actors[k])
values.push(actors[k])
values.push(result_id.insertId)
}
var finalSQLstatement = `insert into film_actor (actor_id,film_id) Values ` + SQLstatement
conn.query(finalSQLstatement, values, (error, result) => {
if (error) {
console.log(error);
return callback(error, null);
}
})
console.log(result_id.insertId);
var SQLstatement = //use backtick to go onto next line
// last insert into inventory with same film_id and store_id
`insert into inventory(film_id,store_id) Values(?,?)`; // 2.
conn.query(SQLstatement, [result_id.insertId, store_id], (error, result) => { //3.
conn.end();
if (error) {
console.log(error);
return callback(error, null);
}
else {
console.log(result);
return callback(null, result.insertId);
}
});
}
})
// });
}
});
}
});
},
app.get():
app.get('/view/:filmid',function(req, res){
var filmid = req.params.filmid;
actorDB.getDetails(filmid, function(err, result){
if(!err){
console.log(result);
res.send(result);
}else{
res.status(500).send("Some error");
}
});
});
index.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Customer</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"
integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
</head>
<body>
<div class="container">
<nav class="nav">
<a class="nav-link" href="/">Home</a>
<a class="nav-link" href="/users/">All Users</a>
</nav>
<h1>Register a new DVD</h1>
<form id="register-form">
<div class="form-group">
<div class="file-upload w-100">
<form class="image-upload-wrap d-flex justify-content-center align-items-center"
style="height: 240px">
<input class="file-upload-input" type="file" onchange="readImage(this);" accept="image/*"
id="imageFile" />
<div class="drag-text w-100 d-flex flex-column justify-content-center align-items-center">
<div id="imageErr" class="text-danger d-none">
Invalid Image
</div>
<h3>Drag photo here</h3>
<p>— or —</p>
<button class="btn bg-secondary text-white font-weight-bold text-center" type="button"
style="white-space: nowrap; z-index: 1055" id="addImage"
onclick="$('.file-upload-input').trigger( 'click' )">
Choose photo to upload
</button>
</div>
</form>
<div class="file-upload-content">
<img class="file-upload-image" style="border: 1px black solid" src="#" alt="your image"
id="imgPreview" />
</div>
</div>
</div>
<div class="form-group">
<label for="title">title:</label>
<input type="text" class="form-control" id="title" required>
</div>
<div class="form-group">
<label for="description">Description:</label>
<input type="text" class="form-control" id="description" required>
</div>
<div class="form-group">
<label for="release">Release:</label>
<input type="text" class="form-control" id="release" required>
</div>
<div class="form-group">
<label for="lang">Language_id:</label>
<input type="text" class="form-control" id="lang" required>
</div>
<div class="form-group">
<label for="rental_duration">Rental Duration:</label>
<input type="text" class="form-control" id="rental_duration" required>
</div>
<div class="form-group">
<label for="rental_rate">Rental rate:</label>
<input type="text" class="form-control" id="rental_rate" required>
</div>
<div class="form-group">
<label for="length">Length:</label>
<input type="text" class="form-control" id="length" required>
</div>
<div class="form-group">
<label for="replacement_cost">Replacement Cost:</label>
<input type="text" class="form-control" id="replacement_cost" required>
</div>
<div class="form-group">
<label for="rating">Rating:</label>
<input type="text" class="form-control" id="rating" required>
</div>
<div class="form-group">
<label for="special_features">Special Features:</label>
<input type="text" class="form-control" id="special_features" required>
</div>
<div class="form-group">
<label for="category_id">Category ID:</label>
<input type="text" class="form-control" id="category_id" required>
</div>
<div class="form-group">
<label for="actors">Actors:</label>
<input type="text" class="form-control" id="actors" required>
</div>
<div class="form-group">
<label for="store_id">Store_id:</label>
<input type="text" class="form-control" id="store_id" required>
</div>
<button type="submit" class="btn btn-primary">Register</button>
<button type="reset" class="btn btn-primary ml-5">Reset</button>
<button type="button" class="btn btn-primary ml-5" id="Logout">Log Out</button>
<!-- <input type="reset" value="Reset"> -->
</form>
</div>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"
integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"
integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1"
crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"
integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM"
crossorigin="anonymous"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script>
const baseUrl = "http://localhost:8081";
const token = localStorage.getItem("token");
const loggedInUserID = parseInt(localStorage.getItem("loggedInUserID"));
console.log(token, loggedInUserID)
function readImage(fileInput) {
if (fileInput.files && fileInput.files[0]) {
var imgReader = new FileReader();
imgReader.onload = function (event) {
var wrap = document.querySelector(".image-upload-wrap");
if (wrap) {
wrap.classList.add("d-none");
wrap.classList.remove("d-flex");
}
var imgData = event.target.result.split(',')[1];
var postData = { image: imgData };
fetch('/upload-image.php', {
method: 'POST',
body: JSON.stringify(postData),
headers: { 'Content-Type': 'application/json' }
})
.then(response => response.json())
.then(data => {
console.log('Success:', data);
})
.catch(error => {
console.error('Error:', error);
});
document.getElementById("addImage").style.display = "none";
var imgPreview = document.getElementById("imgPreview");
imgPreview.src = event.target.result;
var content = document.querySelector(".file-upload-content");
content.classList.add("d-flex", "justify-content-center", "align-items-center");
content.classList.remove("d-none");
var btnSave = document.getElementById("save");
if (btnSave.classList.contains("btn-danger")) {
btnSave.classList.toggle("btn-danger");
btnSave.classList.add("btn-primary");
btnSave.innerHTML = "Save as promo picture";
}
};
imgReader.readAsDataURL(fileInput.files[0]);
} else {
removeUpload();
}
}
if (token === null || isNaN(loggedInUserID)) {
window.location.href = "http://localhost:3001/home";
} else {
$("#register-form").submit((event) => {
// prevent page reload
event.preventDefault();
const title = $("#title").val();
const description = $("#description").val();
const release = $("#release").val();
const lang = $("#lang").val();
const rental_duration = $("#rental_duration").val();
const rental_rate = $("#rental_rate").val();
const length = $("#length").val();
const replacement_cost = $("#replacement_cost").val();
const rating = $("#rating").val();
const feature = $("#special_features").val();
const category_id = $("#category_id").val();
const actors = $("#actors").val();
const store_id = $("#store_id").val();
const requestBody = {
title: title,
description: description,
release_year: release,
language_id: lang,
rental_duration: rental_duration,
rental_rate: rental_rate,
length: length,
replacement_cost: replacement_cost,
rating: rating,
special_features: feature,
category_id: category_id,
actors: actors,
store_id: store_id
};
let token = localStorage.getItem("token");
console.log(requestBody);
axios.post(`${baseUrl}/film`, requestBody, { headers: { "Authorization": "Bearer " + token } })
.then((response) => {
console.log(requestBody)
window.location.href = "http://localhost:3001/home";
})
.catch((error) => {
console.log(error);
if (error.response.status === 400) {
alert("Validation failed");
} else {
alert("Something unexpected went wrong.");
}
});
});
$("#Logout").click(function () {
window.localStorage.clear();
localStorage.removeItem("token");
localStorage.removeItem("loggedInUserID");
window.location.assign("http://localhost:3001/login");
});
}
</script>
</body>
</html>
I need help in parsing the data, even now as i try to submit the form it says Cannot read properties of null (reading 'classList')
at imgReader.onload.

All the Javascript functions for my web page suddenly stopped being recognized

All of the buttons on my web site suddenly stopped working. When I try to press them, in the console it says that they don't exist. I've checked to make sure the Javascript filename in the script tag is correct. I made a folder only for my current Javascript, html, and CSS files. I tried changing the script tag from being at the end of the html document to in the header. None of these things did anything.
medAppFreshStart3.html:33 Uncaught TypeError: noteModal is not a function
at HTMLButtonElement.onclick (medAppFreshStart3.html:33)
onclick # medAppFreshStart3.html:33
<!DOCTYPE html>
<html>
<header>
<script src="medAppFreshStart3.js"></script>
<link rel="stylesheet" href="medAppStyle3.css" />
</header>
<body>
<div class="container">
<div class="d1">
demographics
<button onclick="newPatient()" id="newPatient">+ New Patient</button>
<button onclick="localStorage.clear()" id="clearPtData">
Clear Patient Data</button
><br />
<!--<label for="search">Patient Search</label>-->
<input id="search" placeholder="Enter patient name" />
<button id="searchButton">search</button>
<p id="nameDisplay"></p>
<p id="ageDisplay"></p>
<!--<label for="search">patient search</label>
<input
type="search"
onsearch="findPatient()"
name="search"
id="search"
/>-->
</div>
<div class="d2 flex-container">
current note
<button onclick="noteModal()" id="newNote">+ Add</button>
<div class="content">
<div class="current-note-sub content-1" id="subjective">
Subjective:
</div>
<div class="current-note-sub content-1" id="objective">
Objective:
</div>
<div class="current-note-sub content-1" id="assessment">
Assessment:
</div>
<div class="current-note-sub content-1" id="plan">Plan</div>
</div>
</div>
<div class="d3">
Problem-list
<button onclick="addProblem()" id="new problem">+ Add</button>
<div class="content">
<div class="problem">Problem:</div>
<div class="problem">Problem:</div>
<div class="problem">Problem:</div>
<div class="problem">PRoblem:</div>
</div>
</div>
<div class="d4 flex-container">
prescriptions
<button onclick="addPrescription()" id="new prescription">+ Add</button>
<div class="content" id="prescriptions">
<div class="prescription" id="prescription1">prescription1</div>
<div class="prescription" id="prescription2">prescription2</div>
<div class="prescription" id="prescription3">prescription3</div>
<div class="prescription" id="prescription4">prescription3</div>
</div>
</div>
<div class="d5 flex-container">
Previous Notes
<div class="content">
<div class="past-note" id="past-note1">Date: Complaint:</div>
<div class="past-note" id="past-note2">Date: Complaint:</div>
<div class="past-note" id="past-note3">Date: Complaint:</div>
<div class="past-note" id="past-note4">Date: Complaint:</div>
</div>
</div>
</div>
<div id="addPrescription" class="modal">
<!-- Modal content -->
<div class="modal-content">
<span onclick="closePrescription()" class="close">×</span>
<form action="" method="post" id="prescriptionForm">
<label for="Drug"> Drug:</label>
<input
type="text"
id="Drug"
name="Drug"
type="text"
reqired
aria-required="true"
/>
<label for="Dosage"> Dosage:</label>
<input
type="number"
id="Dosage"
name="Dosage"
required
aria-required="true"
/>
<label for="measurement">Measurement</label>
<select id="measurement" name="measurement">
<option value="micrograms">micrograms</option>
<option value="milligrams">milligrams</option>
<option value="grams">grams</option>
</select>
</form>
<button
type="submit"
value="submit"
form="PrescriptionForm"
onclick="createPrescription(); closePrescription()"
>
+ Create
</button>
</div>
</div>
<div id="noteModal" class="modal">
<!-- Modal content -->
<div class="modal-content">
<span onclick="closeNote()" class="close">×</span>
<form action="" method="post" id="noteForm" name="noteform">
<label for="Date"> Date: </label>
<input
type="text"
id="Date"
name="Date"
reqired
aria-required="true"
/>
<label for="complaint"> Complaint: </label>
<input
type="text"
id="complaint"
name="complaint"
reqired
aria-required="true"
/>
<label for="subjective">Subjective</label>
<textarea id="subjective" name="subjective"></textarea>
<label for="objective">Objective</label>
<textarea id="objective" name="objective"></textarea>
<label for="assessment">Assessment</label>
<textarea id="assesment" name="assessment"></textarea>
<label for="plan">Plan</label>
<textarea id="plan" name="plan"></textarea>
</form>
<button onclick="createNote(), closeNote()">+ Create</button>
</div>
</div>
<div id="addProblem" class="modal">
<!-- Modal content -->
<div class="modal-content">
<span onclick="closeProblem()" class="close">×</span>
<form action="" method="post" id="problemForm">
<label for="problem"> Problem:</label>
<input
type="text"
id="problemForm"
name="problemForm"
reqired
aria-required="true"
/>
</form>
<button
type="submit"
value="submit"
form="problem"
onclick="closeProblem()"
>
+ Create
</button>
</div>
</div>
<div id="newPtDemographics" class="modal">
<!-- Modal content -->
<div class="modal-content">
<span onclick="closeDemo()" class="close">×</span>
<form action="" method="post" id="demoForm">
<label for="name"> Name:</label>
<input
type="text"
id="name"
name="name"
reqired
aria-required="true"
/>
<label for="age"> Age:</label>
<input
type="number"
id="age"
name="age"
reqired
aria-required="true"
/>
</form>
<button onclick="createPatient(), closeDemo()">+ Create</button>
</div>
</div>
</body>
</html>
```
```function newPatient() {
const addPatient = document.getElementById('newPtDemographics');
addPatient.style.display = 'block';
}
function findPatient() {
let name = document.getElementById(search);
name = name.innerText;
console.log(name);
}
const button1 = document.getElementById('searchButton');
searchButton.addEventListener('click', () => {
const name = document.getElementById('search').value;
//console.log(name);
let patients = localStorage.getItem('patients');
patients = JSON.parse(patients);
let patient = patients[name];
nameDisplay = document.getElementById('nameDisplay');
ageDisplay = document.getElementById('ageDisplay');
nameDisplay.innerHTML = 'Name: ' + patient[key];
ageDisplay.innerHTML = 'Age' = patient.age;
//console.log(patient);
//patients = JSON.parse(patients);
});
function createPatient() {
let patients = localStorage.getItem('patients');
const name = document.getElementById('name').value;
const age = document.getElementById('age').value;
if (patients !== null) {
//instead of parsing here can just append array with new patient if it already exists.
//Will need to parse to retrieve data to fill patient details when select new patient or
//reopen broswer.
patients = JSON.parse(patients);
} else {
patients = {};
}
patients[name] = { age: age };
//patients.push({ [name]: { age: age } });
localStorage.setItem('patients', JSON.stringify(patients));
//console.log(patients[name]);
}
function addPrescription() {
const addPrescription = document.getElementById('addPrescription');
addPrescription.style.display = 'block';
}
function createPrescription() {
const div = document.getElementById('prescriptions');
const newPrescription = document.createElement('div');
newPrescription.classList.add('prescription');
const name = document.getElementById('name').value;
console.log(name);
//var patient = JSON.parse(localStorage.getItem('patients.[name]'));
//newPrescription.innerHTML = patient;
//div.appendChild(newPrescription);
//console.log('testing');
//console.log(patient);
//console.log('testing');
/*
newPrescription.innerHTML =
'Drug: ' +
document.getElementById('prescriptionForm').Drug.value +
' Dosage: ' +
document.getElementById('prescriptionForm').Dosage.value +
' ' +
document.getElementById('prescriptionForm').measurement.value;
div.appendChild(newPrescription);
*/
}
function createNote() {
let noteForm = document.getElementById('noteForm');
let formData = new FormData(noteForm);
var object = {};
formData.forEach(function (value, key) {
object[key] = value;
});
var note = JSON.stringify(object);
}
function noteModal() {
const noteModal = document.getElementById('noteModal');
noteModal.style.display = 'block';
}
function addProblem() {
const addProblem = document.getElementById('addProblem');
addProblem.style.display = 'block';
}
function closeProblem() {
const addProblem = document.getElementById('addProblem');
addProblem.style.display = 'none';
}
function closeNote() {
const noteModal = document.getElementById('noteModal');
noteModal.style.display = 'none';
}
function closePrescription() {
const addPrescription = document.getElementById('addPrescription');
addPrescription.style.display = 'none';
}
function closeDemo() {
const addPatient = document.getElementById('newPtDemographics');
addPatient.style.display = 'none';
}

How do I group inputs in Local storage to be one "Event" categorized by my Date time input

In my app I collect information from the user and store it in Local storage using javascript like this.
Event Name (1 to 20 characters):
<input type="text" id="eventname" name="eventname" required
minlength="1" maxlength="20" size="20">
<label for="datetime">Event Date and Time:</label>
<input type="datetime-local" id="date" name="date" required
minlength="1" maxlength="20" size="20">
<label for="eventlocation">Event Location (1 to 20 characters):</label>
<input type="text" id="location" name="location" required
minlength="1" maxlength="20" size="20">
<label for="notes">Notes (0 to 50 characters): </label>
<input type="text" id="notes" name="notes" required
minlength="0" maxlength="50" size="50">
<script src="app.js"></script>
I then have an app.js document which puts it into local storage
const locationTxt = document.querySelector('#location');
locationTxt.addEventListener('change', (event) => {
localStorage.setItem('location', event.target.value);
function getSavedData() {
console.log('location', localStorage.getItem('location'));
(except i have these fucntions for each of the inputs.)
How Would i go about taking all these inputs in locale storage and displaying it as 1 event that is able to be categorized by time?
One way would be to store event data in an object:
{
'01-02-1900': [
... // Array of events
],
'01-01-1900': [
... // Array of events
],
...
}
And then using JSON.parse and JSON.stringify to read/write to localStorage. 😊
For instance:
/**
* This override localStorage in Stack Snippet
*/
const customStorage = { data: {} };
customStorage.getItem = index => customStorage.data[index] || null;
customStorage.setItem = (index, payload) =>
(customStorage.data[index] = payload);
/**
* Replace customStorage with localStorage below.
*/
const inputs = document.querySelectorAll("input");
const storageIndex = "myTestStorage";
const storeInLocal = formData => {
const { date, event } = formData;
const toStore = JSON.parse(customStorage.getItem(storageIndex)) || {};
if (!toStore[date]) toStore[date] = [];
toStore[date].push(event);
customStorage.setItem(storageIndex, JSON.stringify(toStore));
};
const readForm = () => {
let values = {};
inputs.forEach(({ name, value }) => {
values[name] = value;
});
const { date, eventname, location, notes } = values;
return {
date,
event: {
eventname,
location,
notes
}
};
};
const outputStorage = () => {
const storage = customStorage.getItem(storageIndex) || "";
document.getElementById("output").innerText = storage;
};
document.getElementById("eventForm").addEventListener("submit", e => {
e.preventDefault();
const formData = readForm();
storeInLocal(formData);
outputStorage();
});
<!DOCTYPE html>
<html lang="en">
<head>
<title>Store form data in localStorage</title>
<link
href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css"
rel="stylesheet"
/>
<style>
pre {
white-space: pre-wrap;
}
</style>
</head>
<body>
<main id="app" role="main" class="container">
<form id="eventForm">
<div class="form-group row">
<label for="eventname">Event Name</label>
<div class="col-sm-6">
<input
type="text"
id="eventname"
name="eventname"
required
minlength="1"
maxlength="20"
/>
</div>
</div>
<div class="form-group row">
<label for="datetime">Event Date and Time:</label>
<div class="col-sm-6">
<input
type="datetime-local"
id="date"
name="date"
required
minlength="1"
maxlength="20"
/>
</div>
</div>
<div class="form-group row">
<label for="eventlocation">Event Location</label>
<div class="col-sm-6">
<input
type="text"
id="location"
name="location"
required
minlength="1"
maxlength="20"
/>
</div>
</div>
<div class="form-group row">
<label for="notes">Notes</label>
<div class="col-sm-6">
<input
type="text"
id="notes"
name="notes"
required
minlength="0"
maxlength="50"
/>
</div>
</div>
<button type="submit" class="btn btn-primary">Save</button>
</form>
<h1 class="h4">Output</h1>
<p>Hit "save" multiple times, and change the date occasionally.
<p>
<pre id="output"></pre>
</p>
</main>
</body>
</html>

JavaScript form validation not working as intended

Good morning,
I'm working on some simple form validation. Whenever I submit my form, the error message appears, but I can repeatedly spam the button for numerous error messages. Is there a way I can change this to only show the error message once? I've also noticed that even if I populate both fields it will still flash quickly in my console with the error log but not show the error.
Can anyone tell me what I'm doing wrong here?
var uname = document.forms['signIn']['userame'].value;
var pword = document.forms['signIn']['password'].value;
function validateMe (e) {
if (uname.length || pword.length < 1 || '') {
var container = document.getElementById('error-container');
var errorMsg = document.createElement('div');
errorMsg.className = 'error-message';
errorMsg.innerHTML = '<span class="heading-large">Please enter a valid username or password</span>';
container.appendChild(errorMsg);
console.log('An error occured');
return false;
}
}
<form id="signIn" action='#'>
<div class="boxed left-floater">
<h1 class="heading-large margin-top">Sign in</h1>
<div id="error-container"></div>
<div class="form-group">
<label class="form-label-bold" for="username">Username</label>
<input class="form-control log-in-form-control" id="username" name="username" type="text">
</div>
<div class="form-group">
<label class="form-label-bold" for="password">Password</label>
<input class="form-control log-in-form-control" id="password" type="password" name="password">
</div>
<div>
<a class="right-floater forgotten-password" href="forgottenpassword.html">Forgotten Password</a>
<button class="button clear right-floater" type="submit" onclick="validateMe();">Sign In</button>
</div>
</div>
</form>
Fiddle
You must be clearing the contents of your container to avoid duplication of elements. Below are few things to note:
You were trying to get userame instead of username in your fiddle. May be spelling mistake.
Keep input type=submit instead of button
Pass the event to your validateMe function to prevent the default action of post.
Move the variables within the function to get the actual value all the time
function validateMe(e) {
e.preventDefault();
var uname = document.forms['signIn']['username'].value;
var pword = document.forms['signIn']['password'].value;
var container = document.getElementById('error-container');
container.innerHTML = ''; //Clear the contents instead of repeating it
if (uname.length < 1 || pword.length < 1) {
var errorMsg = document.createElement('div');
errorMsg.className = 'error-message';
errorMsg.innerHTML = '<span class="heading-large">Please enter a valid username or password</span>';
container.appendChild(errorMsg);
console.log('An error occured');
return false;
}
}
<form id="signIn" action='#'>
<div class="boxed left-floater">
<h1 class="heading-large margin-top">Sign in</h1>
<div id="error-container"></div>
<div class="form-group">
<label class="form-label-bold" for="username">Username</label>
<input class="form-control log-in-form-control" id="username" name="username" type="text">
</div>
<div class="form-group">
<label class="form-label-bold" for="password">Password</label>
<input class="form-control log-in-form-control" id="password" type="password" name="password">
</div>
<div>
<a class="right-floater forgotten-password" href="forgottenpassword.html">Forgotten Password</a>
<input value="Sign In" class="button clear right-floater" type="submit" onclick="validateMe(event);" />
</div>
</div>
</form>
Updated Fiddle
Edit - if condition was failing and have updated it accordingly
this is full work code
var uname = "";
var pword = "";
function validateMe(e) {
e.preventDefault();
uname = document.forms['signIn']['username'].value;
pword = document.forms['signIn']['password'].value;
if (uname.length || pword.length < 1 || '') {
var container = document.getElementById('error-container');
var errorMsg = document.createElement('div');
errorMsg.className = 'error-message';
errorMsg.innerHTML = '<span class="heading-large">Please enter a valid username or password</span>';
container.appendChild(errorMsg);
console.log('An error occured');
return false;
}
return true;
}
<form id="signIn">
<div class="boxed left-floater">
<h1 class="heading-large margin-top">Sign in</h1>
<div id="error-container"></div>
<div class="form-group">
<label class="form-label-bold" for="username">Username</label>
<input class="form-control log-in-form-control" id="username" name="username" type="text">
</div>
<div class="form-group">
<label class="form-label-bold" for="password">Password</label>
<input class="form-control log-in-form-control" id="password" type="password" name="password">
</div>
<div>
<a class="right-floater forgotten-password" href="forgottenpassword.html">Forgotten Password</a>
<button class="button clear right-floater" type="submit" onclick="validateMe(event);">Sign In</button>
</div>
</div>
</form>

Codeigniter file form upload

I'm getting this error when I try to update a file on my form..."You did not select a file to upload." ...and the problem is that I really am selecting a new file to upload...help me pls, I don't understand what is happening ...here is my code:
FORM
<form class="col s12" id="update_form" required="" enctype="multipart/form-data" aria-required="true" name="update_form" method="post" >
<div class="row">
<div class="input-field col s6">
<input id="update_name" type="text" required="" aria-required="true" name="name" class="validate">
<label for="first_name">Nombre</label>
</div>
<div class="input-field col s6">
<input id="update_last_name" name="lastname" required="" aria-required="true" type="text" class="validate">
<label for="last_name">Apellido</label>
</div>
</div>
<div class="row">
<div class="input-field col s6">
<input id="update_side" type="text" required="" aria-required="true" name="side" class="validate">
<label for="partido">Partido</label>
</div>
<div class="input-field col s6">
<input id="update_charge" type="text" required="" aria-required="true" name="charge" class="validate">
<label for="cargo">Cargo</label>
</div>
</div>
<div class="row">
<div class="input-field col s6">
<div class="file-field input-field no-margin-top">
<div class="btn light-blue darken-4">
<span>Animación/Imagen</span>
<input type="file" name="animation">
</div>
<div class="file-path-wrapper">
<input class="file-path validate" id="animation" name="animation" type="text">
</div>
</div>
</div>
<div class="input-field col s6">
<select id="update_section" required="" aria-required="true" name="section" autocomplete="off">
<option value="" disabled selected>Seleccione una opción</option>
<option value="1">Presidencia</option>
<option value="2">Senadores</option>
<option value="3">Diputados</option>
</select>
<label>Sección</label>
</div>
</div>
<input type="hidden" name="update_politic_hide" id="update_politic_hdn" value="">
</form>
CONTROLLER
public function update_politic(){
$this->load->model("politic");
$params;
if ($this->input->is_ajax_request()) {
if (empty($this->input->post("animation"))){
echo "first";
$data = $this->politic->get_file_name($this->input->post("update_politic_hide"));
$file = $data->POLITIC_FILE;//recupero el nombre de la imagen
$params["name"] = $this->input->post("name");
$params["lastname"] = $this->input->post("lastname");
$params["side"] = $this->input->post("side");
$params["charge"] = $this->input->post("charge");
$params["section"] = $this->input->post("section");
$params["animation"] = $file;
$params["id"] = $this->input->post("update_politic_hide");
if ($params["section"]=="Presidencia") {
$params["section"]=1;
}
if ($params["section"]=="Senadores") {
$params["section"]=2;
}
if ($params["section"]=="Diputados") {
$params["section"]=3;
}
}
else {
echo "second";
$config['upload_path'] = "./public/uploads/";
$config['allowed_types'] = "*";
//$config['overwrite'] = "true";
$config['max_size'] = "500000";
$config['max_width'] = "2000";
$config['max_height'] = "2000";
$this->load->library('upload', $config);
//$file = "animation";
if (!$this->upload->do_upload("animation")) {
$data['uploadError'] = $this->upload->display_errors();
echo $this->upload->display_errors();
}
else {
$file_info = $this->upload->data();
$params["name"] = $this->input->post("name");
$params["lastname"] = $this->input->post("lastname");
$params["side"] = $this->input->post("side");
$params["charge"] = $this->input->post("charge");
$params["animation"] = $file_info['file_name'];
$params["section"] = $this->input->post("section");
$params["id"] = $this->input->post("update_politic_hide");
if ($params["section"]=="Presidencia") {
$params["section"]=1;
}
if ($params["section"]=="Senadores") {
$params["section"]=2;
}
if ($params["section"]=="Diputados") {
$params["section"]=3;
}
}
}
$this->politic->update($params);
}
}
MODEL
public function update($param){
$id = $param["id"];
$values = array(
"POLITIC_NAME" => $param["name"],
"POLITIC_LASTNAME" => $param["lastname"],
"POLITIC_SIDE" => $param["side"],
"POLITIC_CHARGE" => $param["charge"],
"POLITIC_FILE" => $param["animation"],
"SECTION_ID" => $param["section"],
);
$this->db->where("POLITIC_ID",$id);
$this->db->update("politics",$values);
}
JAVASCRIPT
$("#update_politic_btn").click(function(event) {
/* Act on the event */
var chango = $("#update_form").serialize();
$.post(baseurl + 'admin/update_politic', chango,
function(data) {
console.log(data);
list_politic();
});
event.preventDefault();
});
function update_politic(id, name, lastname, section, side, charge, file) {
$("#update_politic_hdn").val(id);
$("#update_name").val(name);
$("#update_last_name").val(lastname);
$("#update_side").val(side);
$("#update_charge").val(charge);
$('[name=section]').val(section);
$("#animation").val(file);
$('select').material_select();
}
There are two name attributes having the same value animation.
<input type="file" name="animation">
and
<input class="file-path validate" id="animation" name="animation" type="text">
The second name attribute is overriding the first one. You need to give it a different name.
Change your Ajax code :
$("#update_politic_btn").click(function(event) {
var chango = new FormData($("#update_form")[0]);
// try this if above one not work
//var chango = new FormData($("#update_form"));
$.ajax({
url: baseurl + 'admin/update_politic',
type: 'POST',
data: chango,
async: false,
success: function (data) {
console.log(data);
list_politic();
},
cache: false,
contentType: false,
processData: false,
error : function() {
}
});
event.preventDefault();
});

Categories