This is my mail.js file which includes this code:
const sendMail = (mail) => {
fetch("/contact",{
method: "post",
body: mail,
}).then((response) => {
return response.json();
});
};
This is my sendMail function in the index.js file which is sending contact form data to the desired email id:
transporter.sendMail(mail, (err, data) => {
if (err) {
console.log(err);
res.status(500).send("Something went wrong.");
} else {
res.status(200).send("Email successfully sent to recipient!");
}
});
And this is the HTML code of my contact form:
<div class="form">
<form id="contact-form" action="contact" method="post" role="form" class="php-email-form" enctype = "multipart/form-data">
<div class="my-3">
<div class="loading">Loading</div>
<div class="error-message"></div>
<div class="sent-message">Your message has been sent. Thank you!</div>
</div>
<div class="text-center"><button type="submit" value="submit" title="Send Message">Send Message</button></div>
</form>
</div>
Whenever I try to submit contact from data it sends it successfully and displays the message "Email successfully sent to recipient!" But with class="error-message" styling how can I fix that?
Related
I have a question regarding POST method. I'm trying to record the data from form into txt file. But the string is empty (in txt file I have only "The request: ")
HTML:
<form
action=""
method="POST"
id="form"
class="section-contact-me-form"
>
<fieldset>
<div class="section-contact-me-input">
<label class="section-contact-me-input__label" for="name">Name*</label>
<input
type="text"
name="name"
class="section-contact-me-input__input _req"
id="name"
>
</div>
<div class="section-contact-me-input">
<label class="section-contact-me-input__label" for="email">E-mail*</label>
<input
type="text"
name="email"
id="email"
class="section-contact-me-input__input _req _email"
>
</div>
<div class="section-contact-me-input">
<label class="section-contact-me-input__label" for="phone">Phone</label>
<input
type="text"
name="phone"
id="phone"
class="section-contact-me-input__input phone"
>
</div>
<div class="section-contact-me-textarea">
<label class="section-contact-me-textarea__label" for="message">Your message*</label>
<textarea
rows="10"
cols="45"
name="message"
id="message"
class="section-contact-me-textarea__textarea _req"
></textarea>
</div>
</fieldset>
<div id="submit" class="submit-button">
<button class="submit-button_active">Send data</button>
</div>
</form>
JS:
form.addEventListener("submit", formSend);
async function formSend() {
const formData = {
name: document.querySelector("#name").value,
email: document.querySelector("#email").value,
phone: document.querySelector("#phone").value,
message: document.querySelector("#message").value
};
const formDatatoSend = JSON.stringify(formData)
sendData("http://localhost:3000/101_susov_newDesign/contactme.php", formDatatoSend)
.then(() => {
form.reset();
})
.catch((err) => console.log(err))
};
const sendData = async (url, data) => {
const response = await fetch (url, {
method: "POST",
body: data
})
if (!response.ok) {
throw new Error (`URL with error ${url}, status ${response}`)
};
return await response;
};
PHP:
<?php
$value = $_POST['value'];
$f = fopen('file.txt', 'a+');
fwrite($f, "The request: ".$value."\n");
fclose($f);
?>
So, the server works properly: there is the access to php code and txt file refreshes every time I use form button, but the content sended from form is empty. As I told before in txt file I have only "The request: "
Where is the eror in my code? Thanks in advance and have a good day!
You do not have a field called value so $_POST['value'] doesn't return anything. You can get the value of each field by adding it's name attribute as the array key:
$value = $_POST['phone'] would return 'The request: PHONE_NUMBER' into your TXT file.
$value = json_encode($_POST) would return the whole post into your TXT file
This should work:
$value = json_encode($_POST);
I'm trying to learn express/nodejs and implement a form, where after recaptcha you can click and download a file. But after form submission I'm being redirected to localhost/submit with only status code on the page. This is driving me crazy, I just want to enable download button after passing recaptcha. I believe this is obvious, but not for me.
server.js file
// Load Node modules
var express = require("express");
const fetch = require("isomorphic-fetch");
// Initialise Express
var app = express();
// Render static files
app.use(express.static("public"));
// Port website will run on
app.listen(8080);
// To accept HTML form data
app.use(express.urlencoded({ extended: false }));
// Here, HTML form is submit
app.post("/submit", (req, res) => {
const name = req.body.name;
// getting site key from client side
const response_key = req.body["g-recaptcha-response"];
// Put secret key here, which we get from google console
const secret_key = "6LdGoQohAAAAAJe6wa_-xayew_ht3N6Lm-kSdbW9";
console.log(res);
// Hitting POST request to the URL, Google will
// respond with success or error scenario.
const url = `https://www.google.com/recaptcha/api/siteverify?secret=${secret_key}&response=${response_key}`;
// Making POST request to verify captcha
fetch(url, {
method: "post",
})
.then((response) => response.json())
.then((google_response) => {
// google_response is the object return by
// google as a response
if (google_response.success == true) {
// if captcha is verified
return res.sendStatus(200);
} else {
// if captcha is not verified
console.log(google_response);
return res.sendStatus(400);
}
})
.catch((error) => {
// Some error while verify captcha
return res.json({ error });
});
});
html form
<form class="main-form" action="/submit" method="post" id="myForm">
<div class="form-row">
<div class="form-element">
<label for="form-delivery">Номер поставки:</label>
<input type="text" name="delivery" required id="form-delivery" />
</div>
<div class="form-element">
<label for="form-num">Номер ТТН:</label>
<input type="text" name="delivery2" id="form-num" />
</div>
</div>
<div class="form-row">
<div class="form-element">
<label for="form-date" req>Дата формирования:</label>
<input type="date" name="delivery3" id="form-date" required />
</div>
<div class="form-element">
<label for="form-client">Клиент:</label>
<input type="text" name="delivery4" id="form-client" />
</div>
</div>
<div class="form-row">
<div class="form-element">
<label for="form-car">Гос. номер:</label>
<input type="text" name="delivery5" id="form-car" />
</div>
<div class="form-element">
<label for="form-cert">Номер сертификата:</label>
<input type="text" name="delivery6" id="form-cert" />
</div>
</div>
<div id="g"></div>
<button class="download-link" type="submit">Скачать</button>
</form>
I have been trying to upload an image to the server for a few days now. But server does not receive any image because form data object is always empty. I then tried to use a library called dropzone for image upload and it worked. But I dont want to use any library. Can somebody please help me understand why form data object is always empty when I send it? I would really appreciate it cuz it will also help me in future. Thank you.
Html Code
<form class="editProfileForm" encType="multipart/form-data">
<div class="form-group">
<div class="row">
<div class="col-12 mt-3">
<div class="text-left">
<label for="certificateImg">CertificateImage</label>
</div>
<input id="certificateImg" type="file" />
</div>
</div>
<div class="row">
<div class="col-sm-12 text-center mt-3 mb-5">
<button class="saveBtn btn btn-primary btn-brand-lg" type="button">Save</button>
</div>
</div>
</div>
</form>
JS Code
const editProfileForm = document.querySelector('.editProfileForm');
const saveBtn = document.querySelector('.saveBtn');
saveBtn.addEventListener('click', () => {
let img = document.getElementById('certificateImg').files[0];
let formData = new FormData();
formData.append('img', img);
console.log(formData);
const doctorUpdateGeneral = async () => {
try {
const response = await axios.put(
'API here',
{
certificate: formData,
},
{
headers: {
Authorization: token,
},
}
);
console.log(response);
window.location.reload();
console.log(pmdc);
} catch (err) {
console.log(err);
}
};
doctorUpdateGeneral();
});
Change the encType attribute to enctype in the form element tag
index.js
document.addEventListener('DOMContentLoaded', function() {
document.querySelector('#compose').addEventListener('click', compose_email);
document.querySelector('#compose-form').onsubmit = send_email;
// By default, load the inbox
load_mailbox('inbox');
});
function compose_email() {
// Show compose view and hide other views
document.querySelector('#compose-view').style.display = 'block';
// Clear out composition fields
document.querySelector('#compose-recipients').value = '';
document.querySelector('#compose-subject').value = '';
document.querySelector('#compose-body').value = '';
}
function send_email()
{
const recipients = document.querySelector('#compose-recipients').value;
const subject = document.querySelector('#compose-subject').value;
const body = document.querySelector('#compose-body').value;
//console.log(recipients)
fetch('/emails', {
method: 'POST',
body: JSON.stringify({
recipients: recipients,
subject: subject,
body: body,
})
})
.then(response => response.json())
.then(result => {
// Print result
console.log(result);
});
}
inbox.html
<div id="compose-view">
<h3>New Email</h3>
<form id="compose-form">
<div class="form-group">
From: <input disabled class="form-control" value="{{ request.user.email }}">
</div>
<div class="form-group">
To: <input id="compose-recipients" class="form-control">
</div>
<div class="form-group">
<input class="form-control" id="compose-subject" placeholder="Subject">
</div>
<textarea class="form-control" id="compose-body" placeholder="Body"></textarea>
<input type="submit" class="btn btn-primary"/>
</form>
</div>
Submitting a form through Javascript via POST method but I am getting an output of GET /? HTTP/1.1" 200 1667 in terminal..
It should be 201 via POST
When I am writing the fetch function in Console.It is working fine
After submitting the form it is just returning back to the inbox page.
Since you are doing a "fetch" in your code, you should prevent the default form submission on the "submit" button click (This this the default behaviour). To achieve this you can receive the "event" as a parameter in the "send_email" function and then do a "event.preventDefault()".
function send_email(event) {
// Your code
...
// Prevent the default form submission
event.preventDefault();
}
More details # https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers/onsubmit
I have some code that is supposed to validate a user logging into my server, however it doesn't want to post it. My get request has no problem loading the very same "/login" as my post but for some reason it doesn't want to load it during the POST. Sorry if my code is a little inefficient and hard to read, still trying to get the hang of javascript.
app.post("/login", (req, res) => {
req.body.userAgent = req.get('User-Agent');
dataServiceAuth.checkUser(req.body).then((user) => {
req.session.user = {
userName: user.username,
email: user.email,
loginHistory: user.loginHistory
}
res.redirect('/employees');
}).catch((err) => {
res.render("login", {errorMessage: err, userName: req.body.userName});
});
});
and the function in the POST
module.exports.checkUser = function (userData) {
return new Promise(function (resolve, reject) {
User.find({ user: userData.userName }).exec().then((user) => {
if (user == undefined || user.length == 0) {
reject("Unable to find user: " + userData.userName);
}
else if (user[0].password != userData.password) {
reject("Incorrect Password for user: " + userData.userName);
}
else if (user[0].password == userData.password) {
users[0].loginHistory.push({dateTime: (new Date()).toString(), userAgent: userData.userAgent});
user[0].update({userName: userData.userName}, {$set: {loginHistory: user[0].loginHistory}}.exec().then((user) => {
resolve(user[0]);
}).catch((err) => {
reject("There was an error verifying the user: ${err}");
}))
}
}).catch((err) => {
reject("Unable to find user: " + userData.user);
});
});
};
My Tree looks like this
and my Handlebars file looks like this
<!DOCTYPE html>
<html lang="en">
<body>
<div class="container">
<div class="row">
<div class="col-md-12">
<h2>Log In</h2>
<hr />
{{#if errorMessage}}
<div class="alert alertdanger">
<strong>Error:</strong> {{errorMessage}}</div>
{{/if}}
<form method="post" action="/login">
<div class="row">
<div class="col-md-12">
<div class="form-group">
<input class="form-control" id="userName" name="userName" type="text" placeholder="User Name" required value=""
/>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="form-group">
<input class="form-control" id="password" name="password" type="password" placeholder="Password" required />
</div>
</div>
</div>
<input type="submit" class="btn btn-success pull-right" value="Login" />
</form>
</div>
</div>
</div>
</body>
</html>
Express version 4 and above requires extra middle-ware layer to handle POST request. This middle-ware is called as ‘bodyParser’. This used to be internal part of Express framework but here I think you need to install it separately like this npm install --save body-parser
Firstly, You should realize that requesting the same route through GET and POST methods does different things.
When you use the GET method, the reason that it has no problem loading the page is because (from what I assume) you would have specified a specific file (probably this login form) to be rendered when a request is received.
In case of the POST request though, you are carrying out operations on the form data sent with the request, and hence there could be a number of reasons you're facing issues with it. Maybe you haven't configured bodyParser to parse nested objects, as Yaswant's answer stated. Or maybe there's some other issue in your code.
It would be helpful if you could give a little more detail on what error you're facing, and if you could post your complete app.js file.