0

I’ve found some good articles to guide me on how to post JSON data using javascript, this one was most to the point: How can I use JQuery to post JSON data?. Unfortunately I’m still not able to get a successful post. Here’s what I have right now, though I eventually will need to replace “email@gmail.com” with the variable from the email input field.

<!-- ========== START Mail Signup PopUp ========== -->
    <div id="popup-1" class="slickModal">
        <div class="window">
            <div class="wrap demo-1">
                <div class="title">SAVE 15% TODAY</div>
                <li>Exclusive Flash Sales</li>
                <li>Giveaways</li>
                <li>Free Shipping Coupons</li>
                <li>and more!</li>
                <br><br>
                <input type="email" value="" id="popupEmail" class="required email field" placeholder="Your email goes here">
                <input type="submit" value="submit" onclick="mcTest()">
<script>
function mcTest() {
     $.ajax({
        type: "POST",
        url: "https://us13.api.mailchimp.com/3.0/lists/123456/members/",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        data: JSON.stringify({"email_address": "email@gmail.com","status": "subscribed"}),
        success: function (data)
        {
            alert("success!") + data;
        },
        error: function()
        {
            alert("Cannot get data");
        }
    });
}
</script>
            </div>
            <div class="cta demo-1">
                <span class="icon"></span>
            </div>
        </div>  
    </div>
<!-- ========== END Mail Signup PopUp ========== -->

I keep getting the error “Cannot get data” error popup. I’m bundling and serving up the json2.js file in order to get the stringify function to work, and I’ve tested the call as a cURL cmd that also works:

curl --request POST --url "https://us13.api.mailchimp.com/3.0/lists/123456/members/" --user "chris:123456789123456789-us13" --header "content-type: application/json" --data @C:\curl\mc.txt

where this is the content of the mc.txt file:

{
"email_address": "email@gmail.com",
"status": "subscribed"
}

Any thoughts on what I’m doing wrong? Thank you for any help/suggestions!

Community
  • 1
  • 1
Chris
  • 1
  • 3
  • If you run this with some sort of developer tools / console visible you should see an error indicating a forbidden cross-origin request. Take a look here: http://stackoverflow.com/questions/21526408/mailchimp-subscribe-using-jquery-ajax#29443119 for an explanation and possible workaround. – Slippery Pete Jul 05 '16 at 19:41
  • Thanks for the quick response @SlipperyPete! The article you linked to provides the explanation, and in using their suggested work around I now get a successful POST response, but the data isn't showing up in Mail Chimp. I found this article too: http://stackoverflow.com/questions/5188418/jquery-ajax-post-not-working-with-mailchimp that seems to indicate I'll need to code a server-side post to properly integrate. Seems odd that there wouldn't be an easier way to POST an email subscribe to MailChimp's RESTful API... on to more research! – Chris Jul 06 '16 at 13:50
  • This is also a good article on how to approach this, but it's in PHP, and my app is asp.net: http://kovalent.co/blog/mailchimp-api-example/; I was also trying to accomplish this without having to add any code-behind... – Chris Jul 06 '16 at 14:12
  • Take a look at the example I've just posted.) – Francis Rodrigues Jan 22 '20 at 17:46

2 Answers2

0

I ended up accomplishing want I wanted using a simpler approach. Instead of trying to use the ajax json submission, I just used their embeded signup form, tweaking it for asp.net as described here: http://kb.mailchimp.com/lists/signup-forms/troubleshooting-the-embedded-signup-form. It's not as slick and re-deployable as I wanted, but at least I can get folks to subscribe for now without having to call their crazy huge js file... I'm marking this as answered, though if anyone wants to add/comment for the better way to handle this, the js/ajax solution could be re-used for other Mail Chimp integration points. Here's my final pop-up form code:

<div id="popup-1" class="slickModal">
    <div class="window">
        <div class="wrap demo-1">
            <div class="title">SAVE TODAY</div>
            <br><br>
        <div id="mc_embed_signup" class="newsletter">
            <div id="mc_embed_signup_scroll">
                <div class="mc-field-group">
                    <label for="mce-EMAIL">Sign up for special offers!</label>
                    <input type="email" value="" name="EMAIL" class="required email field" id="mce-EMAIL">
                </div>
                <div id="mce-responses" class="clear">
                    <div class="response" id="mce-error-response" style="display:none"></div>
                    <div class="response" id="mce-success-response" style="display:none"></div>
                </div>    <!-- real people should not fill this in and expect good things - do not remove this or risk form bot signups -->
                <div style="position: absolute; left: -5000px;" aria-hidden="true"><input type="text" name="b_af7b9e93e6d171c05f91e4e51_5ab805c384" tabindex="-1" value=""></div>
                <div class="clear"><input type="submit" value="Subscribe" name="subscribe" id="mc-embedded-subscribe" class="button"></div>
                <script>
                $("#mc-embedded-subscribe").click(function(){this.form.action="http://mailchimpaccountname.us13.list-manage.com/subscribe/post?u=abc123abc123abc123abc1234&amp;id=1234567890",this.form.submit()});
                </script>
            </div>
        </div>
        </div>
        <div class="cta demo-1">
            <span class="icon"></span>
        </div>
    </div>  
</div>
Chris
  • 1
  • 3
0

About Mailchimp's JSON POST requests, we need to serialize our form data.

we want to grab all of the form field data and create a query string of key/value pairs from it. For example, FNAME=Freddie%20Chimp&EMAIL=freddie@mailchimp.com.

  1. You can do that with jQuery
  2. Using `encodeURIComponent()

The encodeURIComponent()

The encodeURIComponent() function encodes a Uniform Resource Identifier (URI) component by replacing each instance of certain characters by one, two, three, or four escape sequences representing the UTF-8 encoding of the character (will only be four escape sequences for characters composed of two "surrogate" characters).

An example of it is below:

Let's suppose that our event.target is the form property.

// Setup our serialized data
    var serialized = '';

    // Loop through each field in the form
    for (i = 0; i < form.elements.length; i++) {

        var field = form.elements[i];

        // Don't serialize fields without a name, submits, buttons, file and reset inputs, and disabled fields
        if (!field.name || field.disabled || field.type === 'file' || field.type === 'reset' || field.type === 'submit' || field.type === 'button') continue;

        // Convert field data to a query string
        if ((field.type !== 'checkbox' && field.type !== 'radio') || field.checked) {
            serialized += '&' + encodeURIComponent(field.name) + "=" + encodeURIComponent(field.value);
        }
    }

    return serialized;

References:

Francis Rodrigues
  • 1,470
  • 4
  • 25
  • 61