3

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);
    });
}
Alexandra
  • 631
  • 1
  • 13
  • 24
  • Check on this: [Clear form after submission with jQuery](https://stackoverflow.com/questions/8701812/clear-form-after-submission-with-jquery) – Kousic Oct 16 '18 at 02:46

4 Answers4

0

You could do the following to achieve this:

$(function() {

  $('form').submit(function(event) {
    var userEmail = $('#email').val();
    console.log(userEmail);

    event.preventDefault();
    $.ajax({
        url: '/',
        type: 'POST',
        context : this, // <-- add this
        data: {
            email: userEmail
        },
        success: function(response) {
            console.log(response);

            $(this)[0].reset() // <-- resets the form
        },

    });

  });

});
Dacre Denny
  • 29,664
  • 5
  • 45
  • 65
  • Thanks, Dacre. I tried this. Submits email to mailchimp fine just as before but does not clear form. – Alexandra Oct 16 '18 at 02:31
  • @Alexandra Did you remember to add the `context:` line? – Barmar Oct 16 '18 at 02:34
  • Yes, I added the context line as well as the input line at the end. ? – Alexandra Oct 16 '18 at 02:35
  • @Alexandra that's strange - does the updated answer help? – Dacre Denny Oct 16 '18 at 02:37
  • @Alexandra yes, add the two lines where I have added comments - does that work for you? – Dacre Denny Oct 16 '18 at 02:37
  • @DacreDenny Yes, I used your code exactly and oddly the form is not clearing. Everything is pushing through to Mailchimp as well as my DOM message, but the form does not clear. – Alexandra Oct 16 '18 at 02:40
  • @Alexandra that's bizarre - I've just posted another update, perhaps that works? – Dacre Denny Oct 16 '18 at 02:42
  • @DacreDenny Very bizarre. I tried with updated code nothing. Does it have anything to do with my node.js file or that I also have webpack as a devDependency? I can add it here. – Alexandra Oct 16 '18 at 02:46
  • @Alexandra are you getting a successful response? do you know if `console.log(response);` is being called? It might be worth seeing what your nodejs code looks like as it might be an problem with an incorrect response type that's not interacting with your jquery correctly – Dacre Denny Oct 16 '18 at 02:48
  • Yes, I have it set up that it sends a "Success" message in my console. When it's submitted successfully, its says 'success' and the email is in mailchimp. I'll add the node.js file now and clear the API key. – Alexandra Oct 16 '18 at 02:50
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/181915/discussion-between-alexandra-and-dacre-denny). – Alexandra Oct 16 '18 at 02:56
0

If you want to clear form on the success of AJAX call then used $('#myForm')[0].reset(); this inside ajax call or if you want clear form on the submission of the form then used $(this)[0].reset() outside of the ajax call.

$.ajax({
    url: '/',
    type: 'POST',
    context : this, // <-- add this
    data: {
        email: userEmail
    },
    success: function(response) {
        console.log(response);

        $('#myForm')[0].reset(); // used this
    },

});
Kartik Bhalala
  • 390
  • 1
  • 10
0

You can do like this. Straight forward way to clear only input textboxes (you can alter this code to clear all inputs as per ur need, for Radio, Checkboxes etc.,) within a form using jQuery.

$('#myForm').find("input[type=text]").val("");

0

There are 3 ways to resetting or clearing form using jquery:

reset() and trigger reset method will clear only textfield and textarea etc,

it will not clear checkbox,select or radio button values for clearing all elements in form i prefer 3rd method for all elements.

But first 2 methods are easy and simple, and if you are not using all type of elements of form, but using only textfields and textareas as here in question then reset() and trigger('reset') will do it exactly the same.

  1. Using trigger reset

    $('#form_id').trigger("reset");
    
  2. Using reset()

    $('#form_id')[0].reset();
    
  3. Others For all elements

    $("#form_id").find('input:text, input:password, input:file, select, textarea').val('');
    $("#form_id").find('input:radio, input:checkbox').removeAttr('checked').removeAttr('selected');
    
Community
  • 1
  • 1
Haritsinh Gohil
  • 5,818
  • 48
  • 50