AJAX Mailchimp注册表单集成

ale*_*ndm 112 javascript forms ajax newsletter mailchimp

有没有办法将mailchimp简单(一个电子邮件输入)与AJAX集成,因此没有页面刷新,也没有重定向到默认的mailchimp页面.

此解决方案无法使用jQuery Ajax POST无法使用MailChimp

谢谢

小智 226

您不需要API密钥,您只需将标准mailchimp生成的表单放入您的代码中(根据需要自定义外观)并在表单"action"属性中更改post?u=post-json?u=,然后在表单操作结束时附加&c=?以解决任何跨域问题.另外需要注意的是,提交表单时必须使用GET而不是POST.

默认情况下,您的表单标记看起来像这样:

<form action="http://xxxxx.us#.list-manage1.com/subscribe/post?u=xxxxx&id=xxxx" method="post" ... >
Run Code Online (Sandbox Code Playgroud)

改变它看起来像这样

<form action="http://xxxxx.us#.list-manage1.com/subscribe/post-json?u=xxxxx&id=xxxx&c=?" method="get" ... >
Run Code Online (Sandbox Code Playgroud)

Mail Chimp将返回一个包含2个值的json对象:'result' - 这将指示请求是否成功(我只见过2个值,"error"和"success")和'msg' - 一条消息描述结果.

我用这个jQuery提交我的表单:

$(document).ready( function () {
    // I only have one form on the page but you can be more specific if need be.
    var $form = $('form');

    if ( $form.length > 0 ) {
        $('form input[type="submit"]').bind('click', function ( event ) {
            if ( event ) event.preventDefault();
            // validate_input() is a validation function I wrote, you'll have to substitute this with your own.
            if ( validate_input($form) ) { register($form); }
        });
    }
});

function register($form) {
    $.ajax({
        type: $form.attr('method'),
        url: $form.attr('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);
            } else {
                // It worked, carry on...
            }
        }
    });
}
Run Code Online (Sandbox Code Playgroud)

  • 您也可以使用JSONP.如上所述使用`post-json`.如果您在表单操作URL中有它,请删除`&c =`.使用`dataType:'jsonp'`和`jsonp:'c'`进行jQuery ajax调用. (21认同)
  • 我做了一个使用这个方法的jquery-plugin:https://github.com/scdoshi/jquery-ajaxchimp (8认同)
  • 请注意,电子邮件表单字段必须具有name ="EMAIL"才能处理mailchimp (5认同)
  • 仅供参考,如果有人遇到问题,电子邮件参数的名称应为"EMAIL"(全部上限).否则,您将收到一条错误消息,指出该电子邮件地址为空. (5认同)
  • 由于这个答案是写的,MailChimp是否禁用了访问API的方法?我没有在文档中看到没有API密钥的GET/POST可以将用户订阅到列表. (5认同)
  • 由于 cors 错误,尝试使用 fetch() 执行此操作不起作用。 (2认同)

sku*_*ube 32

根据gbinflames的回答,我保留了POST和URL,这样表格将继续适用于JS关闭的人.

<form class="myform" action="http://XXXXXXXXXlist-manage2.com/subscribe/post" method="POST">
  <input type="hidden" name="u" value="XXXXXXXXXXXXXXXX">
  <input type="hidden" name="id" value="XXXXXXXXX">
  <input class="input" type="text" value="" name="MERGE1" placeholder="First Name" required>
  <input type="submit" value="Send" name="submit" id="mc-embedded-subscribe">
</form>
Run Code Online (Sandbox Code Playgroud)

然后,使用jQuery的.submit()更改了类型,并使用URL来处理JSON repsonses.

$('.myform').submit(function(e) {
  var $this = $(this);
  $.ajax({
      type: "GET", // GET & url for json slightly different
      url: "http://XXXXXXXX.list-manage2.com/subscribe/post-json?c=?",
      data: $this.serialize(),
      dataType    : 'json',
      contentType: "application/json; charset=utf-8",
      error       : function(err) { alert("Could not connect to the registration server."); },
      success     : function(data) {
          if (data.result != "success") {
              // Something went wrong, parse data.msg string and display message
          } else {
              // It worked, so hide form and display thank-you message.
          }
      }
  });
  return false;
});
Run Code Online (Sandbox Code Playgroud)


Spa*_*rky 18

应该使用服务器端代码来保护您的MailChimp帐户.

以下是此答案的更新版本,它使用PHP:

PHP文件在用户永远不会看到它们的服务器上"安全",但jQuery仍然可以访问和使用它们.

1)在这里下载PHP 5 jQuery示例...

http://apidocs.mailchimp.com/downloads/mcapi-simple-subscribe-jquery.zip

如果您只有PHP 4,只需下载MCAPI 1.2版并替换MCAPI.class.php上面的相应文件.

http://apidocs.mailchimp.com/downloads/mailchimp-api-class-1-2.zip

2)通过将API密钥和列表ID添加到store-address.php适当位置的文件,按照自述文件中的说明进行操作.

3)您可能还想收集用户的姓名和/或其他信息.您必须store-address.php使用相应的合并变量将数组添加到文件中.

这是我的store-address.php文件的样子,我还收集了名字,姓氏和电子邮件类型:

<?php

function storeAddress(){

    require_once('MCAPI.class.php');  // same directory as store-address.php

    // grab an API Key from http://admin.mailchimp.com/account/api/
    $api = new MCAPI('123456789-us2');

    $merge_vars = Array( 
        'EMAIL' => $_GET['email'],
        'FNAME' => $_GET['fname'], 
        'LNAME' => $_GET['lname']
    );

    // grab your List's Unique Id by going to http://admin.mailchimp.com/lists/
    // Click the "settings" link for the list - the Unique Id is at the bottom of that page. 
    $list_id = "123456a";

    if($api->listSubscribe($list_id, $_GET['email'], $merge_vars , $_GET['emailtype']) === true) {
        // It worked!   
        return 'Success!&nbsp; Check your inbox or spam folder for a message containing a confirmation link.';
    }else{
        // An error ocurred, return error message   
        return '<b>Error:</b>&nbsp; ' . $api->errorMessage;
    }

}

// If being called via ajax, autorun the function
if($_GET['ajax']){ echo storeAddress(); }
?>
Run Code Online (Sandbox Code Playgroud)

4)创建HTML/CSS/jQuery表单.它不需要在PHP页面上.

这是我的index.html文件的样子:

<form id="signup" action="index.html" method="get">
    <input type="hidden" name="ajax" value="true" />
    First Name: <input type="text" name="fname" id="fname" />
    Last Name: <input type="text" name="lname" id="lname" />
    email Address (required): <input type="email" name="email" id="email" />
    HTML: <input type="radio" name="emailtype" value="html" checked="checked" />
    Text: <input type="radio" name="emailtype" value="text" />
    <input type="submit" id="SendButton" name="submit" value="Submit" />
</form>
<div id="message"></div>

<script src="jquery.min.js" type="text/javascript"></script>
<script type="text/javascript"> 
$(document).ready(function() {
    $('#signup').submit(function() {
        $("#message").html("<span class='error'>Adding your email address...</span>");
        $.ajax({
            url: 'inc/store-address.php', // proper url to your "store-address.php" file
            data: $('#signup').serialize(),
            success: function(msg) {
                $('#message').html(msg);
            }
        });
        return false;
    });
});
</script>
Run Code Online (Sandbox Code Playgroud)

所需件......

  • index.html如上构建或类似.使用jQuery,外观和选项是无止境的.

  • store-address.php文件作为PHP示例的一部分在Mailchimp站点上下载,并使用您的API KEYLIST ID进行修改.您需要将其他可选字段添加到数组中.

  • 从Mailchimp站点下载的MCAPI.class.php文件(PHP 5版本1.3或PHP 4版本1.2).将它放在store-address.php所在的目录中,或者必须更新store-address.php中的url路径,以便找到它.

  • 如果您只想在网站上添加注册表单并通过AJAX提交,@ gbinflames的答案可行.我自己试了一下. (2认同)
  • 废话,我得说 - 我刚刚在一个网站上实现了@skube的答案,然后又添加了网站范围的https.刚发现它现在没有使用mailchimp http AJAX调用.如果您的站点可能需要或考虑使用SSL,强烈建议立即使用此方法. (2认同)

adr*_*nat 7

对于寻找现代堆栈解决方案的任何人:

import jsonp from 'jsonp';
import queryString from 'query-string';

// formData being an object with your form data like:
// { EMAIL: 'emailofyouruser@gmail.com' }

jsonp(`//YOURMAILCHIMP.us10.list-manage.com/subscribe/post-json?u=YOURMAILCHIMPU&${queryString.stringify(formData)}`, { param: 'c' }, (err, data) => {
  console.log(err);
  console.log(data);
});
Run Code Online (Sandbox Code Playgroud)


Rez*_*emi 6

根据gbinflames的回答,这对我有用:

生成一个简单的mailchimp列表注册表单,将操作URL和方法(post)复制到您的自定义表单.同时将表单字段名称重命名为all capital(name ='EMAIL',如原始mailchimp代码,EMAIL,FNAME,LNAME,...),然后使用:

      $form=$('#your-subscribe-form'); // use any lookup method at your convenience

      $.ajax({
      type: $form.attr('method'),
      url: $form.attr('action').replace('/post?', '/post-json?').concat('&c=?'),
      data: $form.serialize(),
      timeout: 5000, // Set timeout value, 5 seconds
      cache       : false,
      dataType    : 'jsonp',
      contentType: "application/json; charset=utf-8",
      error       : function(err) { // put user friendly connection error message  },
      success     : function(data) {
          if (data.result != "success") {
              // mailchimp returned error, check data.msg
          } else {
              // It worked, carry on...
          }
      }
Run Code Online (Sandbox Code Playgroud)


Doo*_*y P 5

至于这个日期(2017 年 2 月),似乎 mailchimp 已将类似于 gbinflames 建议的内容集成到他们自己的 javascript 生成表单中。

您现在不需要任何进一步的干预,因为在启用 javascript 时,mailchimp 会将表单转换为 ajax 提交的表单。

您现在需要做的只是将嵌入菜单中生成的表单粘贴到您的 html 页面中,而不是修改或添加任何其他代码。

这很简单。感谢 MailChimp!

  • 如果您可以添加一些文章链接/博客文章来做同样的事情,那真的很有帮助 (4认同)