programing

AJAX Mailchimp 등록 양식 통합

lastmoon 2023. 3. 23. 23:03
반응형

AJAX Mailchimp 등록 양식 통합

mailchimp simple(1개의 이메일 입력)을 AJAX와 통합하여 페이지를 새로 고치지 않고 기본 mailchimp 페이지로 리디렉션할 수 있는 방법이 있습니까?

이 솔루션은 Mail Chimp와 함께 작동하지 않는 jQuery Ajax POST를 사용할 수 없습니다.

감사해요.

키는 없습니다.에 따라 따라 " 변경 API .표준 mailchimp 생성 폼을 코드(필요에 따라 모양을 맞춤)와 "action" Atribute 변경 폼에 플롭하기만 하면 됩니다.post?u=로로 합니다.post-json?u=에 마지막에 을 추가해 주세요.&c=?모든 도메인 간 문제를 회피할 수 있습니다.을한가가 POST 을을 GET 을을을을 。

폼 태그는 기본적으로 다음과 같습니다.

<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는 'result'라는 두 가지 값을 포함하는 json 개체를 반환합니다. 이 개체는 요청의 성공 여부를 나타냅니다(저는 "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...
            }
        }
    });
}

gbinflames의 답변을 바탕으로 JS가 꺼진 경우에도 폼이 계속 작동하도록 POST와 URL을 유지했습니다.

<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()를 사용하여 JSON 응답을 처리하는 유형과 URL이 변경되었습니다.

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

MailChimp 계정을 보호하려면 서버 측 코드를 사용해야 합니다.

다음은 PHP를 사용하는 이 답변의 업데이트된 버전입니다.

PHP 파일은 사용자가 볼 수 없는 서버에서 "보안"되어 있지만 jQuery는 여전히 액세스하여 사용할 수 있습니다.

1) 여기에서 PHP 5 jQuery의 예를 다운로드합니다.

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

4만 1하는 PHP 4를 합니다.MCAPI.class.php를 참조해 주세요.

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

2)를 2) API에 .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(); }
?>

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.displaces 또는 이와 유사합니다.jQuery를 사용하면 모양과 옵션이 무한대로 표시됩니다.

  • Mailchimp 사이트의 PHP 예의 일부로 다운로드되어 API KEY와 LIST ID로 수정되었습니다.어레이에 다른 옵션 필드를 추가해야 합니다.

  • MCAPI.class.Mailchimp 사이트에서 다운로드한 php 파일(PHP 5의 경우 버전 1.3 또는 PHP 4의 경우 버전 1.2). 스토어 주소와 동일한 디렉토리에 저장합니다.php 또는 store-address의 URL 경로를 업데이트해야 합니다.찾을 수 있도록 php를 입력합니다.

최신 스택에서 솔루션을 찾고 있는 사용자:

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

gbinflames의 답변에 근거해, 다음과 같이 나에게 효과가 있었다.

간단한 메일 압축 목록 등록 양식을 생성하고 작업 URL 및 메서드(게시물)를 사용자 정의 양식에 복사합니다.또한 양식 필드 이름을 모두 대문자(name=')로 변경E-메일'은 원래 메일 압축 코드, E-메일, 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...
          }
      }

이 날짜(2017년 2월)는 gbinflames가 제안하는 것과 유사한 것을 자체 javascript 생성 양식에 통합한 것 같습니다.

javascript를 활성화하면 mailchimp가 폼을 전송된 Ajax로 변환하므로 더 이상 개입할 필요가 없습니다.

이제 당신이 해야 할 일은 임베드 메뉴에서 생성된 폼을 당신의 html 페이지에 붙여넣기만 하면 되며 다른 코드를 수정하거나 추가하지 않아도 됩니다.

이것은 간단하게 동작합니다.Mail Chimp 고마워요!

이를 수행하려면 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);
    }
  });
})

이 Github 코드는 나에게 완벽하게 작동한다.여기 사용법에 대한 자세한 설명이 있습니다.WP 사이트에서 사용하고 있습니다.https://gist.github.com/DmitriyRF/34f659dbbc02637cf7465e2efdd37ef5 의 링크는 다음과 같습니다.

한편, Angular에는 몇 가지 패키지가 있습니다.도움이 되는 JS(AJAX WEB):

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

이것을 fetch와 함께 사용할 수 없었기 때문에 GET와 구문 분석 폼 입력을 URL의 쿼리 문자열에 사용하여 여기서 몇 가지 답변을 결합해야 했습니다.또, 이 기능은,name(이 심플한 케이스에서는) 보다 읽기 쉽고, 코드도 깨지지 않는 것 같습니다.다른 양식 필드가 있는 경우 재생합니다).

제 암호는 이렇습니다.

<form action="https://me.usxx.list-manage.com/subscribe/post-json?" id="signup" method="GET">
  <input type="hidden" name="u" value="xxxxxxxxxxxxxxxxxx"/>
  <input type="hidden" name="id" value="xxxxxxxxx"/>
  <input type="hidden" name="c" value="?"/>
  <input name="EMAIL" type="text" />
</form>
// Form submission handler
const formData = new FormData(signup);

fetch(signup.action + new URLSearchParams(formData).toString(), {
  mode: 'no-cors',
  method: signup.method,
})
.then((res) => {
  // Success
})
.catch((e) => {
  // Error
})

안 된다고 하면...

<form action="https://me.usxx.list-manage.com/subscribe/post" id="signup">
fetch(signup.action + '-json?' + new URLSearchParams(formData).toString(), {

그리고 내가 불필요하게 어슬렁거리는 사람들을 구하기 위해서, 당신은 Mailchimp에서 Audience를 위한 등록 양식을 만들어야 합니다. 그리고 당신은 그 페이지를 방문함으로써 당신의 정보를 얻을 수 있습니다.u값어치id뿐만 아니라action나만 그랬을 수도 있지만 난 그게 명확하지 않다고 생각했다.

언급URL : https://stackoverflow.com/questions/8425701/ajax-mailchimp-signup-form-integration

반응형