I have a HTML page with a form, that has 2 inputs, an email, and a username. I want to pass these inputs to a node.js express server called exampleserver.com with fetch(). I have no problems with the server, however, I have problems with the form. Here is my html form:
<h1 align="center">Form</h1>
<input type="text" placeholder ="person#email.com" id="email">
<br>
<input type="text" id="username" placeholder="person">
<br>
<button type="submit" onclick="myfunc()" id="demo">Click Me</button>
<script type="text/javascript">
var email = document.getElementById('email')
var formattedemail = email.value.replace(/\./, '-') //periods dont work as a path in the express server, so this changes the period to a hyphen.
var username = document.getElementById('username');
function myfunc() {
let fetchRes = fetch("https://exampleserver.com/inputform/" + formattedemail + "/" + username.value);
fetchRes.then(res =>
res.json()).then(response => {
console.log(response.status)
})
}
</script>
Thank you!
Your code is working fine with jsonplaceholder api, make sure your API is working as expected.
var email = document.getElementById('email')
var formattedemail = email.value.replace(/\./, '-') //periods dont work as a path in the express server, so this changes the period to a hyphen.
var username = document.getElementById('username');
function myfunc() {
// temp data
formattedemail = "todos";
username.value = "1";
let fetchRes = fetch("https://jsonplaceholder.typicode.com/" + formattedemail + "/" + username.value);
fetchRes.then(res =>
res.json()).then(response => {
console.log(response);
})
}
<h1 align="center">Form</h1>
<input type="text" placeholder="person#email.com" id="email">
<br>
<input type="text" id="username" placeholder="person">
<br>
<button type="submit" onclick="myfunc()" id="demo">Click Me</button>
Related
I would like to retrieve the values of a form and send them to a pdfkit document generated in back end.
For the moment, I only have created a simple document by a "get" route :
router.get(
"/",
authCheck,
asyncHandler(async (req: express.Request, res: express.Response) => {
const doc = new PDFDocument();
let filename = "toto";
filename = encodeURIComponent(filename) + ".pdf";
res.setHeader(
"Content-disposition",
'attachment; filename="' + filename + '"'
);
res.setHeader("Content-type", "application/pdf");
const content = "contenu";
doc.y = 300;
doc.text(content, 50, 50);
doc.pipe(res);
doc.end();
})
);
Here is the code to retrieve the created document :
<iframe className="preview-pdf__container" src={pdfContent} />
How do I send my form data and get it back into the document? With a POST?
This is how I was able to get data from my form into my server then export it to different files with in my server using node.js if it helps. I am not entirely sure on how to get it back out of your server into an iframe though.
HTML:
<div class="wrapper">
<form action="/login" method="POST">
<label id="email-label">Email</label>
<div class="textarea" id="email">
<input type="email" name="email" id="authentactor-email" value="" required>
</div>
<label>Password</label>
<div class="textarea" id="password">
<input type="password" name="password" id="authentactor-password" value="" required>
</div>
<div id="button-wrapper">
<button type="submit" id="button">Login</button>
</div>
</form>
</div>
node.js
//Allows you to Export form data from index.js
app.post('/login');
I am very new to programming. I would like to add a phone number and text message to the below code using values from text boxes, How to do that? Pls see the code below. in the user interface I need two text boxes and a send button. Send button will trigger this below code.
<a href="sms://+15552345678?body=Hello,%20World">Phone(+1) and ?body (sms://)
If you’re on a supported mobile platform, you can try this way:
Send a SMS message
<input type="text" id="phone" placeholder="Type Phone" />
<input type="text" id="msg" placeholder="Type Message" />
<script>
var PhoneNumber = document.getElementById("phone")
var Msg = document.getElementById("msg")
function handleSendMsg() {
document.getElementById("btn").onclick = function () {
this.href = "sms:" + PhoneNumber.value + "?body=" + encodeURI(Msg.value);
// console.log(btn)
};
}
</script>
I have a dynamic section in my html form. When clicking on a button, user can add a tag name and tag type. At a point, imagine that there are 3 set of tag names and tag types, the data should be submitted in the following format.
Array[0][name] = tag1 name, Array[0][type] = tag1 type
Array[1][name] = tag2 name, Array[1][type] = tag2 type
Array[2][name] = tag3 name, Array[2][type] = tag3 type
Can someone help me on this ?
I think you are looking to have a multidimensional array that can store an array within each position of the array. Assuming you have already a form, html should look something like this:
<form class="" action="index.html" method="post">
<div class="inputs">
<input type="text" name="tagName" value="">
<input type="text" name="tagType" value="">
</div>
Add new tag name and type
<button type="submit" name="button">Submit form data</button>
</form>
For the functionality, you could have something like this to store the information and then submit the form:
//Initialization of array
var javascriptArray = [];
//Function to replicate fields in the form
function replicateFields(){
var elementToReplicate = $('.inputs').first(), //Only clone first group of inputs
clonedElement = elementToReplicate.clone();//Cloned the element
clonedElement.find('input').val(''); //Clear cloned elements value on each new addition
clonedElement.insertBefore($('form a'));
}
//Calling function on click
$('.addRow').click(function(){
replicateFields();
});
//Go through inputs filling up the array of arrays.
$('form').submit(function(){
$('.inputs').each(function(){
javascriptArray.push([$(this).find('input[name="tagName"]').val(), $(this).find('input[name="tagType"]').val()]);
});
console.log(javascriptArray);
return false; // remove this to submit the form.
});
You can check in the console in the developer tools for the information you are about to submit.
Let me know if this helps,
Leo.
//Initialization of array
var javascriptArray = [];
//Function to replicate fields in the form
function replicateFields(){
var elementToReplicate = $('.inputs').first(), //Only clone first group of inputs
clonedElement = elementToReplicate.clone();//Cloned the element
clonedElement.find('input').val(''); //Clear cloned elements value on each new addition
clonedElement.insertBefore($('form a'));
}
//Calling function on click
$('.addRow').click(function(){
replicateFields();
});
//Go through inputs filling up the array of arrays.
$('form').submit(function(){
$('.inputs').each(function(){
javascriptArray.push([$(this).find('input[name="tagName"]').val(), $(this).find('input[name="tagType"]').val()]);
});
console.log(javascriptArray);
return false; // remove this to submit the form.
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form class="" action="index.html" method="post">
<div class="inputs">
<input type="text" name="tagName" value="">
<input type="text" name="tagType" value="">
</div>
Add new tag name and type
<button type="submit" name="button">Submit form data</button>
</form>
here is another possibility for how to make this work. a simple form with a div to contain the tags and a small input field to add a new tag.
var tagid = 1;
function addTag() {
var div = document.getElementById("tags");
var name = document.getElementById("tname").value;
var type = document.getElementById("ttype").value;
div.innerHTML += "tag" + tagid + "<br><input type='text' name='tag[" + tagid + "][name]' value='" + name + "'><br><input type='text' name='tag[" + tagid + "][type]' value='" + type + "'><hr>";
tagid++;
}
<html>
<body>
<form id="form">
tags:<br>
<div id="tags">
</div>
<input type="submit" value="Submit">
</form>
<hr> tag name: <input id="tname" type="text" name="tname"><br> tag type: <input id="ttype" type="text" name="ttype"><br>
<button onclick="addTag()">add tag</button>
</body>
</html>
I am beginner to web development. I created a simple form using HTML and CSS, which contained three widgets i.e. name, email and phone. Now I want to send data to the server and store in it using NodeJS.
What should I do?
Here is my HTML file.
<!DOCTYPE html>
<html>
<head>
<Meta charset = "uft-8">
<title> Singing up for The Event </title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<form action = "/registration-form" method = "post">
<div>
<label for="name"> Name: </label>
<input type="text" id="name" name="user_name">
</div>
<div>
<label for="mail"> E-mail: </label>
<input type="email" id="mail" name="user_mail">
</div>
<div>
<label for="phone"> Phone:</label>
<input type="number" id="phone" name="user_phone"></input>
</div>
<div class="button">
<button type="submit">Register!</button>
</div>
<div class="button">
<button type="Reset">Reset!</button>
</div>
</form>
</body>
</html>
Here is my server.js file.
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
var port = process.env.PORT || 63342;
//POST
app.post('/api/users', function(req, res) {
var user_name = req.body.user_name;
var user_mail = req.body.user_mail;
var user_phone = req.body.user_phone;
res.send(user_name + ' ' + user_mail + ' ' + user_phone);
})
//starting the server
app.listen(port);
console.log("Running at port 63342...");
I am not sure what to do next. How to check if the request was successful and is there any way to make a request via opening and filling the HTML form directly.
How did you define your model schema(database) or collections : you can check value of the response(res).
if(err) {
res.json({success: false, message: `Failed to create a new list. Error: ${err}`});
}
else
res.json({success:true, message: "Added User successfully."});
I'm fairly new to coding in HTML. After hours of searching the internet for a way to do this, I failed and so I'm here. I was setting up a CSRF Proof of concept page here, I want it to redirect to another page which will execute the payload that the CSRF had implemented.
<html>
<body>
<form action="https://website.com/action.php?" method="POST">
<input type="hidden" name="fullname" value="john" />
<input type="hidden" name="address" value="street 2, 32 ave" />
<input type="submit" value="Submit request" />
</form>
</body>
</html>
So after this form is submitted using, all it does is redirect to this page
But instead of that, I want it to redirect to another URL as well as submit that form.
For anyone else having the same problem, I figured it out myself.
<html>
<body>
<form target="_blank" action="https://website.com/action.php" method="POST">
<input type="hidden" name="fullname" value="Sam" />
<input type="hidden" name="city" value="Dubai " />
<input onclick="window.location.href = 'https://website.com/my-account';" type="submit" value="Submit request" />
</form>
</body>
</html>
All I had to do was add the target="_blank" attribute to inline on form to open the response in a new page and redirect the other page using onclick on the submit button.
You need to use the jQuery AJAX or XMLHttpRequest() for post the data to the server. After data posting you can redirect your page to another page by window.location.href.
Example:
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
window.location.href = 'https://website.com/my-account';
}
};
xhttp.open("POST", "demo_post.asp", true);
xhttp.send();
in case you are generating the form programmatically you can add this script at the end of the form
<script type="text/javascript">document.forms["FormId"].submit();</script>
What you could do is, a validation of the values, for example:
if the value of the input of fullanme is greater than some value length and if the value of the input of address is greater than some value length then redirect to a new page, otherwise shows an error for the input.
// We access to the inputs by their id's
let fullname = document.getElementById("fullname");
let address = document.getElementById("address");
// Error messages
let errorElement = document.getElementById("name_error");
let errorElementAddress = document.getElementById("address_error");
// Form
let contactForm = document.getElementById("form");
// Event listener
contactForm.addEventListener("submit", function (e) {
let messageName = [];
let messageAddress = [];
if (fullname.value === "" || fullname.value === null) {
messageName.push("* This field is required");
}
if (address.value === "" || address.value === null) {
messageAddress.push("* This field is required");
}
// Statement to shows the errors
if (messageName.length || messageAddress.length > 0) {
e.preventDefault();
errorElement.innerText = messageName;
errorElementAddress.innerText = messageAddress;
}
// if the values length is filled and it's greater than 2 then redirect to this page
if (
(fullname.value.length > 2,
address.value.length > 2)
) {
e.preventDefault();
window.location.assign("https://www.google.com");
}
});
.error {
color: #000;
}
.input-container {
display: flex;
flex-direction: column;
margin: 1rem auto;
}
<html>
<body>
<form id="form" method="POST">
<div class="input-container">
<label>Full name:</label>
<input type="text" id="fullname" name="fullname">
<div class="error" id="name_error"></div>
</div>
<div class="input-container">
<label>Address:</label>
<input type="text" id="address" name="address">
<div class="error" id="address_error"></div>
</div>
<button type="submit" id="submit_button" value="Submit request" >Submit</button>
</form>
</body>
</html>
For me this one worked pretty well.
=> form target to blank (opens in a new tab) + input id to be recognized in Javascript + script that redirects.
<html>
<body>
<form target="_blank" action="https://website.com/action.php" method="POST">
<input type="hidden" name="fullname" value="Sam" />
<input type="hidden" name="city" value="Dubai " />
<input type="submit" value="Submit request" id="submitBtn"/>
<script>
document.getElementById("submitBtn").addEventListener("click", myFunction);
function myFunction() {
window.location.href="http://programminghead.com";
}
</script>
</form>
</body>
</html>
I found it here: https://programminghead.com/submit-button-redirect-to-another-page-in-html