Every time I click on the icon which is defined on the following line of user.ejs
+
it is shown the openModal() is not defined at htmlanchorElement.onclick. the openModal function is defined in the script section of the file add-user-modal like this:
function openModal() {
modal.style.display = "block";
}
please help!
this is my user.ejs file
// starts here
<%- include('./partial/header.ejs'); %>
<div class="manageUser-container">
<div id="title">
<h2>Manage Users</h2>
</div>
<div class="new-message-container new-user">
+
</div>
<div id="users-table">
<table>
<thead>
<tr>
<th>Name</th>
<th>Email</th>
<th>Manage</th>
</tr>
</thead>
<tbody id="users-table">
<tr id="">
<td class="name">
<img src="./images/user1.png" />
<span>User 1</span>
</td>
<td>email#email.com</td>
<td class="manage">
<img src="./images/trash.png" alt="Delete" />
</td>
</tr>
</tbody>
</table>
</div>
</div>
<%- include('./partial/add-user-modal.ejs'); %>
</body>
</html>
// this is the add-user-modal.ejs file
<div class="modal-wrapper" id="add-user-modal">
<div class="modal">
+
<div class="modal-title">
<h2>Create New User</h2>
</div>
<div class="modal-body">
<form method="post" action="/users" enctype="multipart/form-data" id="add-user-form">
<input type="text" placeholder="enter name" name="name" />
<p class="error name-error"></p>
<input type="text" placeholder="enter email" name="email" />
<p class="error email-error"></p>
<input type="text" placeholder="enter mobile" name="mobile" />
<p class="error mobile-error"></p>
<input type="password" placeholder="enter password" name="password" />
<p class="error password-error"></p>
<input type="file" name="avatar" />
<p class="error avatar-error"></p>
<p class="error common-error"></p>
<input type="submit" value="Submit" />
</form>
</div>
</div>
</div>
<script>
console.log('Hello from console');
const modal = document.querySelector("#add-user-modal");
const form = document.querySelector("#add-user-form");
function closeModal() {
modal.style.display = "none";
}
function openModal() {
modal.style.display = "block";
}
// success toast
const successToast = Toastify({
text: "User was added successfully. Reloading the list...",
duration: 1000
})
// form submit handler
form.onSubmit = async function (event) {
event.preventDefault();
}
// clear all the error first
const errorPlaceHolder = document.querySelectorAll("p.error");
for (let index = 0; index < errorPlaceHolder.length; index++) {
errorPlaceHolder[index].style.display = "none";
}
const inputErrors = document.querySelectorAll("input", "error");
if (inputErrors.length > 0) {
for (let index = 0; index < inputErrors.length; index++) {
inputErrors[index].classList.remove("error");
}
}
// prepare the form data
const formData = new FormData(form);
// send the request to server
let response = await fetch("/users", {
method: "POST",
body: formData,
});
// get response
let result = await response.json();
// handle error and response
if (result.errors) {
//errors
Object.keys(result.errors).forEach((fieldName) => {
// add error class to all the input fields
form(fieldName).classlist.add("error");
// set all error to the place holder text content
const errorPlaceHolder = document.querySelector(`.${fieldName}-error`);
errorPlaceHolder.textContent = result.errors[fieldName].msg;
// make all place holder visible
errorPlaceHolder.style.display = "block";
});
} else {
// success
successToast.showToast();
closeModal();
document.querySelector("p.error".style.display) = "none";
// reload the page after one second
setTimeout(() => {
location.reload();
}, 1000);
}
</script>
Related
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
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 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';
}
I am trying to save some store details and getting a response from the controller using Ajax but when I am trying to do so the request is not received by the Controller please see the code and help me what I am doing wrong here.
MasterAjaxClass: The class is used to send the request and receive a response
class MasterAjax{
constructor(){
this.requestType = null;
this.url = null;
this.timeout = 100000;
this.enctype = null;
this.data = null;
this.processData = null;
this.contentType = null;
this.responseData = null;
this.responseStatus = null;
this.responseStatusCode = null;
}
requestData(callBack){
var parameterError=false;
if(null == this.requestType){
parameterError=true;
console.log("Error: Request Type can't be null");
}
if(null === this.url || undefined === this.url || "undefined" === this.url){
parameterError=true;
console.log("Error: URL can't be null");
}
if(null == this.data || this.data.length <= 0){
//console.log("Warning: Data is null");
}
if(parameterError === false){
/*toggleSpinnerOn(); */
$.ajax({
type : this.requestType,
enctype : this.enctype,
processData : this.processData,
contentType : this.contentType,
// url : global_contextPath+"/"+this.url,
url : global_contextPath+"/"+this.url,
data: this.data,
timeout : this.timeout,
success : function(responseData,textStatus) {
/*toggleSpinnerOff();*/
callBack(responseData,textStatus);
},
error : function(responseData,textStatus) {
/*toggleSpinnerOff(); */
callBack(responseData,textStatus);
}
});
}
//return this.responseData;
}
}
Ajax Request method
function saveStore(){
let formData = new FormData();
//formData.append("key" , Value ) ;
formData.append("storeName", $("#storeName").val());
formData.append("country", $("#country").val());
formData.append("city", $("#city").val());
formData.append("street", $("#street").val());
formData.append("address", $("#address").val());
formData.append("zipCode", $("#zipCode").val());
formData.append("storeDescription", $("#storeDescription").val());
formData.append("storeOpenTime", $("#storeOpenTime").val());
formData.append("logoURL", $("#file-input-2").val());
console.log($("#storeName").val());
console.log($("#country").val());
console.log($("#city").val());
console.log($("#street").val());
console.log($("#address").val());
console.log($("#zipCode").val());
console.log($("#storeDescription").val());
console.log($("#storeOpenTime").val());
console.log($("#file-input-2").val());
var obj = new MasterAjax();
obj.requestType = "POST";
obj.url = "store/saveStore";
obj.data = formData;
obj.enctype ="multipart/form-data";
obj.contentType = false;
console.log("---------------------------")
for (var pair of formData.entries()) {
console.log(pair[0]+ ': ' + pair[1]);
}
console.log("---------------------------")
obj.requestData(function(responseData){
console.log(responseData);
if(responseData.status == "OK" || responseData.status == "ok"){
alert("success");
console.log(responseData)
}else{
alert(" failed");
console.log(responseData)
}
});
}
StoreForm.jsp
<form:form name="storeForms" modelAttribute="storeForm"
method="POST" enctype="multipart/form-data">
<%-- <c:if test="${not empty error}">
<div class="alert alert-danger" role="alert">
<h5 class="alert-heading">Failed to Save</h5>
<hr>
<p>${error}</p>
</div>
</c:if>
--%>
<!-- Hidden For Update employee -->
<form:input type="hidden" path="id" />
<!-- First row -->
<div class="form-row row-eq-spacing-sm">
<div class="col-sm">
<label for="first-name" class="required">Store Name</label>
<form:input type="text" path="storeName" class="form-control"
id="storeName" placeholder="Store Name" required="required" />
</div>
<div class="col-sm">
<label for="last-name" class="required">Country</label>
<form:input type="text" id="country" path="country" class="form-control" />
</div>
</div>
<!-- Second row container -->
<div class="form-row row-eq-spacing-sm">
<div class="col-sm">
<label for="first-name" class="required">City</label>
<form:input type="text" id="city" path="city" class="form-control" />
</div>
<div class="col-sm">
<label for="last-name" class="required">Street</label>
<form:input type="text" id="street" path="street" class="form-control" />
</div>
</div>
<!-- Third row container -->
<div class="form-row row-eq-spacing-sm">
<div class="col-sm">
<label for="first-name" class="required">Address</label>
<form:input type="text" id="address" path="address" class="form-control" />
</div>
<div class="col-sm">
<label for="last-name" class="required">Zip Code</label>
<form:input type="text" id="zipCode" path="zipCode" class="form-control" />
</div>
</div>
<div class="form-row row-eq-spacing-sm">
<div class="col-sm">
<label for="first-name" class="required">Store Description</label>
<form:input type="text" path="storeDescription" id="storeDescription"
class="form-control" />
</div>
<div class="col-sm">
<label for="last-name" class="required">Store Timings</label>
<form:input type="text" path="storeOpenTime" id="storeOpenTime" class="form-control" />
</div>
</div>
<div class="custom-file">
<form:input type="file" path="logoURL" id="file-input-2"
data-default-value="Size of logo should not Exeed 1mb" />
<label for="file-input-2">Choose logo</label>
</div>
<!-- Submit button container -->
<div class="text-right">
<!-- text-right = text-align: right -->
<input class="btn btn-primary" type="button" onclick="saveStore();" value="Add Store">
</div>
</form:form>
Controller Method
#Controller
#RequestMapping("/store")
public class StoreController {
#ResponseBody
#RequestMapping(value = "/saveStore" , method = {RequestMethod.POST},consumes = {"multipart/form-data"})
public APIResponseModal saveStore(#ModelAttribute("storeForm") StoresDTO store,#RequestPart("logoURL") MultipartFile file) {
logger.info("Store Save MEthod callled !!!!!!!!");
Stores storeModal = new Stores();
String logopath = "";
APIResponseModal apiResponse = new Utils().getDefaultApiResponse();
List<String> errorList = new ArrayList<String>();
try {
if(store !=null){
storeModal = new Stores(store);
if(!file.isEmpty()) {
if(file.getSize()>1000000) {//1000000 bytes == 1 mb
errorList.add("File size should be less than 1 MB");
}
logopath = Utils.storeLogoPath(file);
}
storeService.saveStore(storeModal, errorList,logopath);
if(errorList.isEmpty() && !Utils.isNotNull(errorList)) {
apiResponse.setStatus(HttpStatus.OK);
apiResponse.setData("--");
apiResponse.setMessage("Store Saved Successfully !!");
}else {
apiResponse.setMessage("Failed to save store !!");
apiResponse.setStatus(HttpStatus.BAD_REQUEST);
}
}
} catch (Exception e) {
e.printStackTrace();
apiResponse.setStatus(HttpStatus.BAD_REQUEST);
apiResponse.setData("--");
apiResponse.setMessage("Error Occured at our end !!");
}
logger.info("API RESPONSE:: ::"+ apiResponse);
return apiResponse;
}
}
Error On browser Console
Status :403
I call postAjax on button click, which calls signupUser, this works fine, but then I want signupUser to call showWelcomeMessage which for some reason it doesn't work. I get no error in the console but ´no success message shows up in the HTML´. I am also thinking that maybe the way I am targeting the html is not correct ( and there is no problem with the callback itself ) and that´s why I do not see any message.
NOTE: The sSuccessMessage should show up on the LOGIN page (html div), cause after succesfull signup, SIGNUP page ( html div ) gets hidden and LOGIN shows up.
Please help me find what´s wrong.
// GLOBAL ARRAY for storing any DATA from the SERVER
var ajDataFromServer = [];
/************************************************************************/
/************************************************************************/
/************************************************************************/
// Main ajax function using callback for posting data to the server
function postAjax( sUrl , frmData, callback ){
var ajax = new XMLHttpRequest();
ajax.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var ajDataFromServer = JSON.parse(this.responseText);
callback( ajDataFromServer, showSuccessMessage );
}
}
ajax.open( "POST", sUrl , true );
var jFrm = new FormData( frmData );
ajax.send( jFrm )
}
// DO the SIGNUP, POST data to the SERVER with AJAX
btnSignupForm.addEventListener("click", function (e) {
//var lblErrorMessage = e.target.parentNode.nextSibling.contains.classList("lblErrorMessage");
postAjax("api_signup_users.php", frmSignup, signupUser);
});
function signupUser( ajUserDataFromServer, showSuccessMessage ) {
if ( ajUserDataFromServer.status == "ok" ) {
//console.log( "SIGNUP SUCCESFULL" );
pageLogin.style.display = "flex";
pageSignup.style.display = "none";
showSuccessMessage( "Account succesfully created - Signup please" );
} else {
//console.log( "SIGNUP FAIL - TRY AGAIN" );
pageViewProducts.style.display = "none";
pageLogin.style.display = "none";
pageSignup.style.display = "flex";
lblSignupErrorMessage.innerHTML = "";
var sSignupErrorMessage = "Signup Failed - Try again";
lblSignupErrorMessage.insertAdjacentHTML( 'beforeend', sSignupErrorMessage );
}
}
/************************************************************************/
/************************************************************************/
/************************************************************************/
function showSuccessMessage ( sSuccessMessage ) {
var lblErrorMessage = document.querySelector(".lblErrorMessage");
lblErrorMessage.innerHTML = "";
var sSuccessMessage = sSuccessMessage.fontcolor( "#549839" );
lblErrorMessage.insertAdjacentHTML('beforeend', sSuccessMessage);
}
Here is the HTML part:
<!-- SIGNUP for USERS and ADMIN -->
<div id="pageSignup" class="page popup">
<div class="wrapper">
<h3>SIGNUP</h3>
<form class="form" id="frmSignup">
<input type="text" name="txtEmailorPhoneNumber" placeholder="Mobile number or Email" required>
<input type="text" name="txtName" placeholder="Name" required>
<input type="text" name="txtLastName" placeholder="Lastname" required>
<input type="password" name="txtPassword" placeholder="Password" required>
<div class="lblFileUpload">
<p>Select your picture:</p>
<input type="file" name="fileUserImage" required>
</div>
<button type="button" class="btnForm" id="btnSignupForm">Signup</button>
<div class="lblFormExtention">
<p class="pyesAccount">Already have an account?</p>
<button type="button" class="btnShowPage" id="btnLogin" data-showThisPage="pageLogin">Login</button>
</div>
</form>
<h3 class="lblErrorMessage" id="lblSignupErrorMessage"></h3>
</div>
</div>
<!-- ********************************************************************** -->
<!-- ********************************************************************** -->
<!-- ********************************************************************** -->
<!-- LOGIN for USERS and ADMIN -->
<div id="pageLogin" class="page popup">
<div class="wrapper">
<h3>LOGIN</h3>
<form class="form" id="frmLogin">
<input type="text" name="txtEmailorPhoneNumber" placeholder="Mobile number or Email" required>
<input type="text" name="txtPassword" placeholder="Password" required>
<button type="button" class="btnForm" id="btnLoginForm">Login</button>
<div class="lblFormExtention">
<p class="pnoAccount">Don´t have an account?</p>
<button type="button" class="btnShowPage" id="btnSignup">Signup</button>
</div>
</form>
<h3 class="lblErrorMessage" id="lblLoginErrorMessage"></h3>
</div>
</div>
<!-- ********************************************************************** -->
<!-- ********************************************************************** -->
<!-- ********************************************************************** -->
<!-- SUBSCRIBE for USERS -->
<div id="pageSubscribe" class="page popup">
<div class="wrapper">
<h3>SUBSCRIBE TO OUR NEWSLETTER</h3>
<form class="form" id="frmSubscribe">
<input type="text" name="txtEmail" placeholder="Email" required>
<input type="text" name="txtName" placeholder="Name" required>
<input type="text" name="txtLastName" placeholder="Lastname" required>
<input type="text" name="txtAddress" placeholder="Address" required>
<div id="mapinForm">
<!-- Generated dynamically -->
</div>
<button type="button" class="btnForm" id="btnSubscribeForm">Subscribe</button>
</form>
<h3 class="lblErrorMessage" id="lblSubscribeErrorMessage"></h3>
</div>
</div>
When you query element via document.querySelector(".lblErrorMessage") you get your first element of that class which is <h3 class="lblErrorMessage" id="lblSignupErrorMessage"></h3> and it's hidden at the time you call showSuccessMessage().
You probably need to query element by its ID, using document.getElementById()
Update:
If you don't want to query each element by ID, your solution will be to update every .lblErrorMessage element:
function showSuccessMessage ( sSuccessMessage ) {
Array.prototype.forEach.call(document.querySelectorAll(".lblErrorMessage"), function (el) {
el.innerHTML = "";
el.insertAdjacentHTML('beforeend', sSuccessMessage.fontcolor( "#549839" ));
// or simply use the following form:
// el.innerHTML = sSuccessMessage.fontcolor( "#549839" );
});
}
It works this way, however I am not sure if this is the most optimal way.
function showSuccessMessage ( sSuccessMessage ) {
var alblMessages = document.getElementsByClassName( "lblMessage" );
for ( var i = 0; i < alblMessages.length; i++ ) {
alblMessages[i].insertAdjacentHTML('beforeend', sSuccessMessage.fontcolor( "#549839" ));
}
}