AJAX Mailchimp注册表单集成


122

是否有任何方法可以将简单的mailchimp(一个电子邮件输入)与AJAX集成在一起,所以没有页面刷新,也没有重定向到默认的mailchimp页面。

此解决方案不起作用jQuery Ajax POST不适用于MailChimp

谢谢


提交表单后,它将重定向到mailchimp“确认”页面。
alexndm 2011年

3
您的解决方案具有巨大的安全漏洞,由于API密钥确实提供对MailChimp帐户的完全访问权限,因此应将其视为私有密钥。#justsaying

1
该解决方案暴露了您的mailchimp API,这不是一个好主意
Ruairi Browne

3
mailchimp网站上的默认HTML embed选项也不会公开您的api密钥吗?那个解决方案再好不过了。
Bob Bobbio 2012年

使用以下jquery插件:github.com/scdoshi/jquery-ajaxchimp
sid

Answers:


241

您不需要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" ... >

改变它看起来像这样

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

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...
            }
        }
    });
}

8
我制作了一个使用此方法的jquery-plugin:github.com/scdoshi/jquery-ajaxchimp
sid

22
您还可以使用JSONP。按照说明使用post-json&c=如果您在表单操作网址中添加了,请将其删除。将dataType: 'jsonp'jsonp: 'c'用于jQuery ajax调用。
czerasz 2013年

5
请注意,电子邮件表单字段必须具有name =“ EMAIL”才能处理mailchimp
Ian Warner

5
仅供参考,以防万一有人遇到问题,电子邮件参数的名称应为EMAIL(全大写)。否则,您将收到一条错误消息,指出电子邮件地址为空。
Nick Tiberi 2015年

5
自编写此答案以来,MailChimp是否已禁用这种访问API的方法?我在文档中没有看到没有API密钥的GET / POST可以将用户预订到列表的指示。
格雷格·贝尔

34

根据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>

然后,使用jQuery的.submit()更改类型和URL以处理JSON回复。

$('.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;
});

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)按照自述文件中的指示,store-address.php在适当的位置将API密钥和列表ID添加到文件中。

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(); }
?>

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>

必需品...

  • 如上所述或类似构造的index.html。使用jQuery,外观和选项无穷无尽。

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

  • 从Mailchimp网站下载的MCAPI.class.php文件(PHP 5版本1.3或PHP 4版本1.2)。将其放置在与store-address.php相同的目录中,或者必须更新store-address.php中的url路径才能找到它。


2
如果您只想向网站添加注册表单并通过AJAX提交,则@gbinflames的答案有效。我自己尝试过。
帕特里克·坎菲尔德

1
不,没有必要
Nowaker

2
废话,我得说-我之前在网站上实现了@skube的答案,后来又添加了整个网站范围的https。现在刚刚发现它无法与mailchimp http AJAX调用一起使用。如果您的站点可能需要或考虑使用SSL,则强烈建议立即使用此方法。
squarecandy16年

12

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

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);
});

6

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

生成一个简单的mailchimp列表注册表单,将操作URL和方法(发布)复制到您的自定义表单中。还要将表单字段名称重命名为全部大写(如原始mailchimp代码中的name ='EMAIL',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...
          }
      }

5

截至该日期(2017年2月),mailchimp似乎已经将类似于gbinflames建议的内容集成到了自己的javascript生成形式中。

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

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

这很有效。感谢MailChimp!


4
如果您可以添加一些文章链接/博客文章来做同样的事情,那将真的有帮助
仿冒了

我已将Mailchimp嵌入代码添加到我的html页面中,但是Ajax不能如上述建议那样自动工作。我被重定向到另一个页面。我如何在没有重定向的情况下进行这项工作?
Petra

1
在MailChimp管理员中,转到列表->注册表单->嵌入式表单->经典。您会看到代码片段中包含一些JS。这将启用表单验证和AJAX提交。
MarcGuay

1
使用mailchimp代码-如何将自定义操作插入到ajax成功中?[例如隐藏表格]
Adeerlike

1
@Masiorama我选择删除mc-validate脚本,因为该脚本还包含一个旧的jquery并且太大且易受攻击。因此,只需进行html验证并使用像stackoverflow.com/a/15120409/744690中的
Adeerlike

4

使用jquery.ajaxchimp插件来实现。太简单了!

<form method="post" action="YOUR_SUBSCRIBE_URL_HERE">
  <input type="text" name="EMAIL" placeholder="e-mail address" />
  <input type="submit" name="subscribe" value="subscribe!" />        
  <p class="result"></p>
</form>

JavaScript:

$(function() {
  $('form').ajaxChimp({
    callback: function(response) {
      $('form .result').text(response.msg);
    }
  });
})

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.