I have a working newsletter form (name, email) using Node.js and jquery the only problem is the form does not clear once the email is submitted using the "sign-up" button.
I have tried using an empty string ' ' after onclick as well as the .reset() form method. Both of these approaches work, however it's clearing the email address and preventing it to be sent to Mailchimp. I've tested it with a handful amount of email addresses and nothing goes through. As well, my terminal messages show 'email_address: ' as an empty string. I'm assuming I'm ordering my code incorrectly? Any direction/feedback is appreciated. Also, please let me know if I need to add my Node.js code.
HTML:
<form action="/" method="post" id="myForm">
<h2 class="text-center mt-5"> Sign-Up Newsletter</h2>
<p>Using Mailchimp API</p>
<div class="form-group">
<input type="name" class="form-control" id="name" aria-describedby="emailHelp" placeholder="Name" style="width: 400px;">
</div>
<div class="form-group">
<input type="email" class="form-control" id="email" placeholder="Email" style="width: 400px;">
</div>
<p id="demo"></p>
<button type="submit" class="btn btn-info" id="submit" onclick="myFunction()" style="color:#fff; margin-bottom: 70px; width: 190px;">Sign up</button>
</form>
JS
var $ = require('jquery');
$('form').submit(function(event) {
var userEmail = $('#email').val();
console.log(userEmail);
event.preventDefault();
$.ajax({
url: '/',
type: 'POST',
data: {
email: userEmail
},
success: function(response) {
console.log(response);
},
});
});
//Message after newsletter sign-up
function myFunction() {
document.getElementById("demo").innerHTML = "Thank You, for signing up! You are now on our mailing list!";
}
Node.js
const express = require('express');
const app = express();
const bodyParser = require("body-parser");
//middleware
app.use(express.static(__dirname + "/public"));
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }));
// parse application/json
app.use(bodyParser.json());
//connecting cloud i9 host
app.listen(process.env.PORT, process.env.IP, function() {
console.log("The Server Has Started!");
});
//route
app.post('/', function(req, res) {
addEmailToMailchimp(req.body.email);
res.end('SUCCESS!');
});
function addEmailToMailchimp(email) {
var request = require("request");
var options = {
method: 'POST',
url: 'XXXXXXXX',
headers: {
'postman-token': 'XXXXXX',
'cache-control': 'no-cache',
'content-type': 'application/json',
authorization: 'Basic XXXXX},
body: { email_address: email, status: 'subscribed' },
json: true
};
request(options, function(error, response, body) {
if (error) throw new Error(error);
console.log(body);
});
}