Integración de formulario de suscripción AJAX Mailchimp


¿Hay alguna manera de integrar mailchimp simple (una entrada de correo electrónico) con AJAX, por lo que no hay actualización de página y no hay redirección a la página predeterminada de mailchimp.

Esta solución no funciona jQuery Ajax POST no funciona con MailChimp

Gracias

Author: Community, 2011-12-08

8 answers

No necesitas una clave API, todo lo que tienes que hacer es introducir el formulario estándar generado por mailchimp en tu código ( personaliza el aspecto según sea necesario ) y en el atributo forms "action" cambia post?u= a post-json?u= y luego al final de la acción forms append &c=? para evitar cualquier problema de dominio cruzado. También es importante tener en cuenta que cuando envíe el formulario debe usar GET en lugar de POST.

Su etiqueta de formulario se verá algo como esto por defecto:

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

Cámbialo para que se vea algo como esto

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

Mail Chimp devolverá un objeto json que contiene 2 valores: 'resultado' - esto indicará si la solicitud fue exitosa o no ( solo he visto 2 valores, "error" y "éxito" ) y 'msg' - un mensaje que describe el resultado.

Envío mis formularios con este bit de 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...
            }
        }
    });
}
 212
Author: gbinflames,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-10-03 10:50:52

Basado en la respuesta de gbinflames, mantuve el POST y la URL, para que el formulario siguiera funcionando para aquellos con JS desactivado.

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

Entonces, usando jQuery .submit () cambió el tipo y la URL para manejar repsonses 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;
});
 28
Author: skube,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-04-23 15:04:13

debes usar el código del lado del servidor para proteger tu cuenta de MailChimp.

La siguiente es una versión actualizada de esta respuesta que usa PHP :

Los archivos PHP están "protegidos" en el servidor donde el usuario nunca los ve, pero el jQuery todavía puede acceder y usar.

1) Descargue el ejemplo de PHP 5 jQuery aquí...

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

Si solo tiene PHP 4, simplemente descargue la versión 1.2 del MCAPI y reemplace el archivo MCAPI.class.php correspondiente anterior.

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

2) Siga las instrucciones en el archivo Readme agregando su clave de API e ID de lista al archivo store-address.php en las ubicaciones adecuadas.

3) Es posible que también desee recopilar el nombre de sus usuarios y / u otra información. Debe agregar un array al archivo store-address.php usando la combinación correspondiente Variable.

Aquí está cómo se ve mi archivo store-address.php donde también recojo el nombre, el apellido y el tipo de correo electrónico:

<?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) Crea tu formulario HTML/CSS/jQuery. No es necesario estar en una página PHP.

Aquí hay algo como cómo se ve mi archivo 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>

piezas Necesarias...

  • índice.html construido como arriba o similar. Con jQuery, la apariencia y las opciones son interminable.

  • dirección de la tienda.archivo php descargado como parte de ejemplos PHP en el sitio de Mailchimp y modificado con su API KEY y LIST ID. Necesita agregar sus otros campos opcionales a la matriz.

  • MCAPI.clase.archivo php descargado del sitio Mailchimp (versión 1.3 para PHP 5 o versión 1.2 para PHP 4). Colóquelo en el mismo directorio que su store-address.php o debe actualizar la ruta de url dentro dirección de la tienda.php para que pueda encontrarlo.

 18
Author: Sparky,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 11:33:26

Basado en la respuesta de gbinflames, esto es lo que funcionó para mí:

Genera un simple formulario de registro de lista de mailchimp , copia la URL de acción y el método (post) a tu formulario personalizado. También cambia el nombre de los campos de tu formulario a todos los capitales (name = 'EMAIL' como en el código original de mailchimp, EMAIL, FNAME, LNAME,... ), entonces usa esto:

      $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...
          }
      }
 6
Author: Reza Hashemi,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-08-30 19:26:33

Usa jquery.ajaxchimp plugin para lograr eso. Es muy fácil!

<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);
    }
  });
})
 4
Author: Nowaker,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-05-30 01:25:58

En cuanto a esta fecha (febrero de 2017), parece que mailchimp ha integrado algo similar a lo que gbinflames sugiere en su propio formulario generado por javascript.

Ahora no necesitas más intervención, ya que mailchimp convertirá el formulario a uno enviado con ajax cuando Javascript esté habilitado.

Todo lo que necesita hacer ahora es pegar el formulario generado desde el menú incrustar en su página html y NO modificar ni agregar ningún otro código.

Esto simplemente funciona. Gracias ¡MailChimp!

 2
Author: Doody P,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-02-02 10:53:43

Para cualquiera que busque una solución en una pila moderna:

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);
});
 1
Author: Grsmto,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-05-30 18:49:01

Por otro lado, hay algunos paquetes en AngularJS que son útiles (en AJAX WEB):

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

 0
Author: مصطفی,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-30 06:52:39