joeswann
11/2/2014 - 12:14 AM

Mailchimp ajax

Mailchimp ajax

//handler for Mailchimp form
handlerNewsletter: function() {
  var $form_wrap = $('.newsletter-wrap');
  var $form      = $form_wrap.find('.newsletter');
  var $success   = $form.find('.success');
  var $error     = $form.find('.error');

  var action = String($form.attr('action'));

  $form.submit(function(e) {
    e.preventDefault();

    $error.hide();
    $.ajax({
      type: $form.attr('method'),
      url: action,
      data: $form.serialize(),
      cache: false,
      dataType: 'json',
      contentType: "application/json; charset=utf-8",
      error: function(err) {
        alert("Could not connect to the registration server. Please try again later.");
      },
      success: function(data) {
        if (data.result != "success") {
          // Something went wrong, do something to notify the user. maybe alert(data.msg);
          $error.text('Please enter a valid email address').show();
        } else {
          // It worked, carry on...
          $form.find('input').val('');
          $success.show();
        }
      }
    });
  }); // end submit
}
<form class="newsletter" action="https://example.us2.list-manage.com/subscribe/post-json?u=xxxxxxx&id=xxxxxxxx&c=?" method="get" >
  <div class="close"></div>
  <div class="success">
      Thankyou for signing up!
  </div>
  <div class="error">
      Please check your email address is correct.
  </div>
  <input name="NAME" type="text" placeholder="Full Name" />
  <input name="EMAIL" type="text" placeholder="Email Address" />
  <button class="btn-alt" type="submit" value="Sign Up" name="submit">Sign Up</button>
</form>