Scenario:
I've designed a website that features a form with a POST action. The objective is for users to input their email addresses into the form. Once an email is submitted, a POST request is dispatched to the server. By utilizing Express and the MailChimp API, I'm able to store this email in my MailChimp account through the backend app.js file.
Issue:
Upon successfully adding the email, I respond with a dummy JSON object using res.json(). Currently, this JSON object is just a placeholder, but in the future, it will be used to relay success details. The setback arises when my browser redirects from my index.html to showcase this JSON file. I aim to prevent the page from reloading or redirecting to the JSON response. What am I missing in this setup?
I would greatly appreciate any assistance that can be provided, thank you :)
Methods I've attempted: res.end(), res.send(), and res.sendStatus(200)
APP.JS (for POST operations):
// Signup Route
app.post('/signup', (req, res) => {
const {email} = req.body;
console.log(req);
// Ensure all fields are filled
if(!email){
res.redirect('/fail.html');
return;
}
// Create request data
const data = {
members: [
{
email_address: email,
status: 'subscribed',
merge_fields: {} // may consider removing this line....
}
]
};
const postData = JSON.stringify(data);
const options = {
url: 'myprivateurl',
method: 'POST',
headers: {
Authorization: 'myprivatekey'
},
body: postData
};
request(options, (err, response, body) => {
if(err) {
res.redirect('/fail.html');
}
else{
if(response.statusCode == 200){
//res.redirect('/success.html');
console.log("server side success");
res.json({
success: true,
message: "Some success message",
data: "some data if there's any"
});
}
else{
res.redirect('/fail.html');
}
}
});
});
HTML (exclusive to form features):
<!--Email List-->
<div id="mailListHolder">
SIGN UP FOR OUR MAIL LIST!
<br>
<div id="successtext"> Thanks! </div>
<form id="emailform" action="/signup" method="POST">
<input name="email" type="text" placeholder="example@email.com" onfocus="this.placeholder = ''"/>
<input type="submit" />
</form>
</div>
CLIENT JS (pertaining to form functionality):
$('#emailform').submit(function() {
console.log("emailform submit case WORKING!");
$("#emailform").css({
"display": "none",
});
$("#successtext").css({
"display": "block"
});
return false;
});