i've been having a problem where i have a form in which several entities within an unordered list are displayed, a name and a button dinamically with vanilla javascript. The problem is, im changing the action value from the html form, from javascript this so i can add an id that i get in a JSON from a http request so i can manipulate a specific object, but it doesnt send the "delete" request, which is actually a post request that im managing from my server side correctly (tested in postman and works like a charm), but when calling from the front-end it stops working. Here are my html and script.
PANEL.HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!-- <meta http-equiv="Content-Security-Policy" content="default-src https://cdn.example.net; child-src 'none'; object-src 'none'"> -->
<link rel="stylesheet" type="text/css" href="css/panel-style.css">
<script defer src="panel-script.js"></script>
<title>Panel de Control</title>
</head>
<body>
<header>
<img src="assets/mrvapeslogo.png" alt="mrvapes logo">
</header>
<section>
<form id="files-form" accept-charset="UTF-8" enctype="multipart/form-data" action="#" autocomplete="off" method="POST" onsubmit="return validate(this);">
<label for="user">Banners Activos</label><br/>
<ul id="files-container">
</ul>
</form>
<form accept-charset="UTF-8" enctype="multipart/form-data" action="http://localhost:3000/banner" autocomplete="off" method="POST" target="_blank">
<div class="container">
<div class="button-wrap">
<!-- <label class="button" for="upload">Subir</label> -->
<input type="text" id="name" placeholder="Nombre de Archivo" value="" name="name" required>
<input id="image" name="file" value="Subir" placeholder="Subir Archivo" type="file" required>
<button id="upload" value="post-request" type="submit">Enviar</button>
<!-- <input id="upload" type=" submit " value="Enviar " onclick="submit() "> -->
</div>
</div>
</form>
</section>
</body>
PANEL-SCRIPT.JS
const list = document.getElementById("files-container");
const filesForm = document.getElementById("files-form");
fetch('http://localhost:3000/banner')
.then(response => response.json())
.then(json => {
console.log(json)
console.log(json.message)
for (let i = 0; i < json.message.length; i++) {
var item = `<li>${json.message[i].name}
<button id="delete-button" onclick="deleteButton('${json.message[i].name}','${json.message[i]._id}')">Borrar</button>
</li>`;
list.innerHTML += item;
}
});
function deleteButton(name, id) {
var answer = confirm(`Seguro que deseas borrar ${name}?`);
if (answer) {
filesForm.action = `http://localhost:3000/banner/${id}`;
alert('Borrado Correctamente!');
window.location.reload(true);
} else {
validate();
}
}
function validate() {
return false
}
HAPPY HOLIDAYS! :D
-- UPDATE --
When making these changes below to my panel-script.js, my delete function starts working but everytime i cancel the confirm dialog it forwards me to a "cannot post page".
function deleteButton(name, id) {
var answer = confirm(`Seguro que deseas borrar ${name}?`);
if (answer) {
filesForm.action = `http://localhost:3000/banner/${id}`;
alert('Borrado Correctamente!');
// window.location.reload(true);
} else {
// validate();
return false;
}
}
// function validate() {
// return false
// }
Related
I am submitting 2 forms with one button using JavaScript. But when I am trying to access it using request.form in flask, it is only showing the 2nd form(the last submitted form). How can I access both forms in the backend? Will I have to use ajax? I am new to JS, flask, HTML. Thanks!
Here's my HTML code:
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<form method ="post" id="f1" name = "form1" action="{{url_for('process')}}">
<input type="text" name = "name">
</form>
<form method ="post" id="f2" name="form2" action="{{url_for('process')}}">
<input type="text" name = "name">
</form>
<button type="button" value="submit" onclick="sub()">sub
</button>
</body>
<script>
function sub(){
document.getElementById("f1").submit();
document.getElementById("f2").submit();
}
</script>
</html>
Here's my flask code:
from flask import Flask, request, render_template
app = Flask(__name__)
#app.route('/')
def home():
return render_template('forms.html')
#app.route('/processing', methods=['POST',"GET"])
def process():
print(request.form) #This only prints ImmutableMultiDict([('name', 'name submitted by f2')])
return "processsed"
if '__main__' == __name__:
app.run(debug=True)
Use form data and send.
Not tested, if there's any problem please comment.
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<form method ="post" id="f1" name = "form1" action="{{url_for('process')}}">
<input type="text" name = "name">
</form>
<form method ="post" id="f2" name="form2" action="{{url_for('process')}}">
<input type="text" name = "name">
</form>
<button type="button" value="submit" onclick="sub()">sub
</button>
</body>
<script>
async function sub() {
var form = new XMLHttpRequest();
form.open(document.getElementById("f1").method, document.getElementById("f1").action);
var p = new Promise(r => {
form.onreadystatechange = function() {
if (form.readyState === XMLHttpRequest.DONE && form.status === 200) r();
}
});
form.send(new FormData(document.getElementById("f1")));
await p;
form = new XMLHttpRequest();
form.open(document.getElementById("f2").method, document.getElementById("f2").action);
p = new Promise(r => {
form.onreadystatechange = function() {
if (form.readyState === XMLHttpRequest.DONE && form.status === 200) r();
}
});
form.send(new FormData(document.getElementById("f2")));
await p;
window.location.reload();
}
</script>
</html>
I managed to import a function from my main.js to my signin.js, but for some reason, I get this error on my sign in html page Cannot read properties of null (reading 'addEventListener')
and the function for the signin js is not working and I need to import the function of the main.js as the signin js function relys on the main.js function to work.
HTML 1 - signin js
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="../js/main.js" type="module"></script>
<script src="../js/signin.js" type="module"></script>
<title>Sign in</title>
</head>
<body>
<main>
<form class="form-container">
<input class="email" type="text" placeholder ="Email Address">
<input class="password" type="password" placeholder ="Password">
Sign In
Register
</form>
</main>
</body>
signin.js imported function
//import function
import { validate } from "../js/main.js";
let registration = validate();
let signInbtn = document.querySelector(".sign-in");
signInbtn.addEventListener("click", check);
function check(){
let storedEmail = localStorage.getItem('email');
let storedPw = localStorage.getItem("password");
let email = document.querySelector(".email");
let password = document.querySelector(".password");
if(email.value == storedEmail && password.value == storedPw){
alert("You are logged in")
}
else{
alert("Email or Password is incorrect please check and try again.")
}
}
}
HTML 2 - main.js
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="stylesheet" href="../css/main.css" />
<script src="../js/main.js" type="module"></script>
<title>Register</title>
</head>
<body>
<main>
<div class="heading">
<h1>User Registration</h1>
</div>
<form action="../index.html" class="form-container">
<ul>
<li><label for="name">Name</label>
<input class="name" type="text" name="name" required />
</li>
<li><label for="surname">Surname</label>
<input class="surname" type="text" name="surname" required />
</li>
<li><label for="phone">Phone</label>
<input class="phone" type="text" name="phone" />
</li>
<li><label for="email">Email</label>
<input class="email" type="text" name="email" required /></li>
<li><label for="password">Password</label>
<input class="password" type="text" name="password" required /></li>
<button class="reg">Register</button>
</ul>
</form>
</main>
</body>
</html>
main.js
let registration = document.querySelector(".reg");
registration.addEventListener("click", validate);
export function validate() {
//get html elements
const formEl = {
id: createId(),
name: document.querySelector(".name").value,
surname: document.querySelector(".surname").value,
phone: document.querySelector(".phone").value,
email: document.querySelector(".email").value,
password: document.querySelector(".password").value,
};
let name = formEl.name;
let surname = formEl.surname;
let email = formEl.email;
let password = formEl.password;
if (!name) {
alert("Please fill in name");
}
if (!surname) {
alert("Please fill in Surname");
}
if (!email) {
alert("Please fill in email");
}
if (!password) {
alert("Please create a password");
}
usersArray.push(formEl);
store();
return formEl;
}
This error I get in the HTML 1 page
for some reason, it is preventing the sign-in function from executing. I am doing it this way for practice purposes, I know local storage is not the best method for this, but I am getting used to how local storage works.
I have a first page, which, onload, shows the default get params.
Page1.html
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script defer src="assets/main.js"></script>
<title>Document</title>
</head>
<body">
<div>
<h1>Nous avons reçu : </h1>
<h2 style="display: inline-block">LOGIN : </h2>
<p style="display: inline-block" id="login"></p>
</div>
<div >
<h2 style="display: inline-block">PASSWORD : </h2>
<p style="display: inline-block" id="password"></p>
</div>
</body>
<script>
</script>
</html>
Page1_main.js
// Version 1
const url = new URL(window.location.href);
const params = url.searchParams;
params.set('LOGIN', 'Licois');
params.append('PASSWORD', 'Johanne')
url.search = params.toString();
window.history.replaceState({}, '', location.pathname + '?' + params);
if (params.has('LOGIN')) {
alert("Licois !");
} else {
alert("Licois est introuvable !")
}
if (params.has('PASSWORD')) {
alert("Johanne !");
} else {
alert("Johanne a disparu !")
}
document.getElementById("login").innerHTML = params.get("LOGIN");
document.getElementById("password").textContent = params.get("PASSWORD");
Result : page1 result
Ok, this is what I wanted.
But then, I have to have another page (with html only), which will send new get parametes to the first page, and shown them there in the HTML and URL. But in this case I cannot show "Joanne" and "Licois" anymore, or show the new params as "param3= " and "param4= ".
Page2_html
<!DOCTYPE html>
<html lang="fr">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Exercice 2</title>
</head>
<body>
<form action="Page1.html" method="GET">
<label for="login">Login</label>
<input type="text" name="login" id="login" >
<div><br></div>
<label for="password">Password</label>
<input type="text" type="password" for="password" name="password" id="password">
<div><br></div>
<button type="submit" id="envoyer">Envoyer</button>
</form>
</body>
</html>
Page2_form
I succeed at sending the new params to the first page ("action='Page1.html'").
But I can't manage to show them in the HTML and URL.
No, nevermind, I got it.
Changed Page2.html to
<body>
<form action="Page1.html" method="GET">
<label for="login">Login</label>
<input type="text" name="NEW_LOGIN" id="NEW_LOGIN" >
<div><br></div>
<label for="password">Password</label>
<input type="text" type="password" for="password" name="NEW_PASSWORD" id="NEW_PASSWORD">
<div><br></div>
<button type="submit" id="envoyer">Envoyer</button>
</form>
</body>
</html>
And added this to Page1_main.js
if (params.has('NEW_LOGIN')) {
document.getElementById("login").innerHTML = params.get("NEW_LOGIN");
} else if ((params.has('LOGIN'))) {
document.getElementById("login").innerHTML = params.get("LOGIN");
}
if (params.has('NEW_PASSWORD')) {
document.getElementById("password").innerHTML = params.get("NEW_PASSWORD");
} else if ((params.has('PASSWORD'))) {
document.getElementById("password").innerHTML = params.get("PASSWORD");
}
EZ
I'm making a code where the user enters information and it stores it in an object, but when I check if the object is saved by alerting one of its values it says there is no such object.
here is my code.
let users = {};
function user(name,real){
this.username = name,
this.realname = real,
this.id = Math.floor(Math.random() *1000);
this.subs = 0,
this.videos = [],
this.listuser = function() {
return this.username;
}
};
function newuser(name, email,username){
users[name] = new user(username, name);
};
let savefile = () => {
var channame = string(document.getElementById('channame'));
var name = string(document.getElementById('name'));
var email = string(document.getElementById('email'));
newuser(name,email,channame);
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>youtube ripoff</title>
<link href="style.css" rel="stylesheet" type="text/css" />
</head>
<body>
<br> <br><br><br><br><br>
<form action="">
<label for="username">Channel Name: </label>
<input type="text" id="channame" name="channelname"><br>
Real Name
<input type="text" id="name" name="name"><br>
Email
<input type="text" id="email" name="email"><br>
<input type="submit" value="Submit" onmousedown="newuser('name1','name#gmail.com','channelname1');">
<br><br><br><br>
<input type="button" value="Load Channels" id="seech" name="seechannels" onmousedown="alert(users['name1'].listuser());"><br>
</form>
<script src="script.js">
function fun(){
window.alert("starting program...")
//other code
}
</script>
</body>
</html>
Is there some sort of error that I'm not seeing?
After click on submit button in form with action="" page is reload and all data is lost. Pleas use:
<form action="javascript:void(0)">
instead of
<form action="">
This prevent page reload.
i am trying to make a phonebook that has an add button when i click it it opens a form and there for now i want to display my name and phonenumber
now when i fillout these 2 fields and click on send it does not display it on the webpage
this is my html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>PhoneBook</title>
<link rel="stylesheet" href="Css/Whole.css">
<script defer src="JavaScript/PU.js"></script>
</head>
<body>
<h1>PhoneBook</h1>
<div class="childContainer">
<div class="buttonsContainer">
<div>
<input type="search" placeholder="search" class="searchBar"></div>
<div class="buttonsRightSide"> <button value="submit" id="addBtn" class="addBtn">+</button>
<button value="submit" id="removeBtn" class="removeBtn">-</button>
<button value="submit" id="saveBtn" class="saveBtn">*</button></div>
</div>
<div class="formContainer">
<form class="addForm" id="addForm">
<h2>Create Contact</h2>
<label for="name">First name*:</label>
<input id="name" type="text" pattern="[A-Z][a-zA-Z]{3,7}" required><br>
<label for="phoneNumber">Phone number*:</label>
<input id="phone" type="number" pattern="[0][5][0-8][ -]?\d{7}" required><br>
<label for="Adress">Address:</label>
<input type="text" id="Address"><br>
<label for="Email">Email:</label>
<input type="email" id="Email"><br>
<label for="Description">Description:</label>
<textarea type="text" id="Description"></textarea><br>
<div class="sendCancelButtons">
<button type="submit" class="submitButton" id="submitButton">Send</button> <button value="submit"
class="cancelOverlay">Cancel</button></div>
</form>
</div>
<div class="outPutContainer">
</div>
</div>
</body>
</html>
and this is my javascript
"use strict";
function showOverlay(showButton, showContainer) { // this whole funciton opens up the overlay
const addButton = document.querySelector("." + showButton);
addButton.addEventListener("click", function addSomthing() {
document.querySelector("." + showContainer).style.display = 'block';
});
}
showOverlay("addBtn", "formContainer");
function cancelOverlay(cancelButton, showContainer) { //this dynamic funciton helps with closing overlays after we are done with the event
const removeOverlay = document.querySelector("." + cancelButton);
removeOverlay.addEventListener("click", function removeSomthing() {
document.querySelector("." + showContainer).style.display = 'none';
});
}
cancelOverlay("cancelOverlay", "formContainer");
function inputAndOutput() {
cancelOverlay("submitButton", "formContainer"); //this function helps me close the form window after i click on send
const form = document.getElementById("addForm");
form.addEventListener("submit", (e) => { //this is a submit event when the send button is pressed it makes an object and with the help of JSON it puts it into an array
let formOutput = {
name: document.getElementById("name").value,
phoneNumber: document.getElementById("phone").value
} //end of form
localStorage.setItem("formOutput", JSON.stringify(formOutput)); //array of obj
console.log(localStorage.getItem('formOutput')); //testing
displayOutput();
e.preventDefault(); //prevent the page to reload
} //end of Event
, );
}
inputAndOutput();
function displayOutput() {
if (localStorage.getItem('formOutput')) {
let {
name,
phoneNumber
} = JSON.parse(localStorage.getItem('formOutput'));
const output = document.getElementById("outPutContainer");
output.innerHTML = `
<ul>
<li>${name} </li>
<li>${phoneNumber} </li>
</ul>
`
}
}
any hints and suggestions are welcome and thanks in advance <3
Your JS code throws the error Uncaught TypeError: output is null.
The variable output gets defined here:
const output = document.getElementById("outPutContainer");
however, the container you want to get by id only has a class:
<div class="outPutContainer">
Change class="outPutContainer" to id="outPutContainer".
(Note: I found this solution using the Console tab of the Developer Tools of my browser. Press CTL+SHIFT+C in e.g. Firefox or Chrome and follow the errors/warnings. This is usually the fastest way to debug your scripts.)