Javascript AJAX Mailchimp 注册表单集成

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8425701/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 05:57:49  来源:igfitidea点击:

AJAX Mailchimp signup form integration

javascriptajaxformsnewslettermailchimp

提问by alexndm

Is there any way to integrate mailchimp simple (one email input) with AJAX, so there is no page refresh and no redirection to default mailchimp page.

有什么方法可以将 mailchimp simple(一个电子邮件输入)与 AJAX 集成,因此没有页面刷新,也没有重定向到默认的 mailchimp 页面。

This solution doesn't work jQuery Ajax POST not working with MailChimp

此解决方案不起作用jQuery Ajax POST not working with MailChimp

Thanks

谢谢

回答by gbinflames

You don't need an API key, all you have to do is plop the standard mailchimp generated form into your code ( customize the look as needed ) and in the forms "action" attribute change post?u=to post-json?u=and then at the end of the forms action append &c=?to get around any cross domain issue. Also it's important to note that when you submit the form you must use GET rather than POST.

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

Your form tag will look something like this by default:

默认情况下,您的表单标签将如下所示:

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

change it to look something like this

改变它看起来像这样

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

Mail Chimp will return a json object containing 2 values: 'result' - this will indicate if the request was successful or not ( I've only ever seen 2 values, "error" and "success" ) and 'msg' - a message describing the result.

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

I submit my forms with this bit of jQuery:

我用这个 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...
            }
        }
    });
}

回答by skube

Based on gbinflames' answer, I kept the POST and URL, so that the form would continue to work for those with JS off.

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

Then, using jQuery's .submit() changed the type, and URL to handle JSON repsonses.

然后,使用 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;
});

回答by Sparky

You shoulduse the server-side code in order to secure your MailChimp account.

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

The following is an updated version of this answer which uses PHP:

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

The PHP files are "secured" on the server where the user never sees them yet the jQuery can still access & use.

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

1) Download the PHP 5 jQuery example here...

1) 在此处下载 PHP 5 jQuery 示例...

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

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

If you only have PHP 4, simply download version 1.2 of the MCAPI and replace the corresponding MCAPI.class.phpfile above.

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

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

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

2) Follow the directions in the Readme file by adding your API key and List ID to the store-address.phpfile at the proper locations.

2) 按照自述文件中的说明将您的 API 密钥和列表 ID 添加到store-address.php文件的适当位置。

3) You may also want to gather your users' name and/or other information. You have to add an array to the store-address.phpfile using the corresponding Merge Variables.

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

Here is what my store-address.phpfile looks like where I also gather the first name, last name, and email type:

这是我的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) Create your HTML/CSS/jQuery form. It is not required to be on a PHP page.

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

Here is something like what my index.htmlfile looks like:

这是我的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>

Required pieces...

需要的零件...

  • index.htmlconstructed as above or similar. With jQuery, the appearance and options are endless.

  • store-address.phpfile downloaded as part of PHP examples on Mailchimp site and modified with your API KEYand LIST ID. You need to add your other optional fields to the array.

  • MCAPI.class.phpfile downloaded from Mailchimp site (version 1.3 for PHP 5 or version 1.2 for PHP 4). Place it in the same directory as your store-address.phpor you must update the url path within store-address.phpso it can find it.

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

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

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

回答by adriendenat

For anyone looking for a solution on a modern stack:

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

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

// formData being an object with your form data like:
// { EMAIL: '[email protected]' }

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

回答by Reza Hashemi

Based on gbinflames' answer, this is what worked for me:

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

Generate a simple mailchimp list sign up form , copy the action URL and method (post) to your custom form. Also rename your form field names to all capital ( name='EMAIL' as in original mailchimp code, EMAIL,FNAME,LNAME,... ), then use this:

生成一个简单的 mailchimp 列表注册表单,将操作 URL 和方法(发布)复制到您的自定义表单。还将您的表单字段名称重命名为所有大写( 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...
          }
      }

回答by Nowaker

Use jquery.ajaxchimpplugin to achieve that. It's dead easy!

使用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:

JavaScript:

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

回答by Doody P

As for this date (February 2017), it seems that mailchimp has integrated something similar to what gbinflames suggests into their own javascript generated form.

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

You don't need any further intervention now as mailchimp will convert the form to an ajax submitted one when javascript is enabled.

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

All you need to do now is just paste the generated form from the embed menu into your html page and NOT modify or add any other code.

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

This simply works. Thanks MailChimp!

这很简单。感谢 MailChimp!

回答by Mostafa

In the other hand, there is some packages in AngularJS which are helpful (in AJAX WEB):

另一方面,AngularJS 中有一些有用的包(在 AJAX WEB 中):

https://github.com/cgarnier/angular-mailchimp-subscribe

https://github.com/cgarnier/angular-mailchimp-subscribe