PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Tuesday, September 6, 2022

[FIXED] How do I effectively debug a JQuery GET request to MailChimp 3.0 servers?

 September 06, 2022     get, javascript, jquery, mailchimp-api-v3.0     No comments   

Issue

I am trying to add users' emails to my Mailchimp 3.0 audience list. I am using JQuery to make the GET request, but I keep the following error:

{"type":"http://developer.mailchimp.com/documentation/mailchimp/guides/error-glossary/","title":"API Key Invalid","status":401,"detail":"Your request did not include an API key.","instance":"1e63d45d-2f46-481f-a674-3c307033cd29"}

This error happens after I click my button to trigger the request.

Here is the section in my HTML code that the JQuery script is pulling from:

<form **action="https://us4.api.mailchimp.com/3.0/lists/8a99d9c7eb/members/>"**
                                method="get" **id="mc-embedded-subscribe-form"** name="mc-embedded-subscribe-form" class="validate">
                                    <p class="signUp mt-5">
                                        We are currently Beta testing our service and will reveal more
                                        soon. Enter your email address below to receive updates.
                                    </p>
                                    <div class="form-label-group">
                                        <input type="email" id="mc-embedded-subscribe-form" name="mc-embedded-subscribe-form" class="form-control"
                                            placeholder="Email address" required autofocus>
                                    </div>

                                <input type="submit" value="Notify me" name="subscribe" id="mc-embedded-subscribe" class="btn btn-sm btn-success mt-1 shadow-lg">
                                <div id="subscribe-result"></div>
                                    <!-- <button class="btn btn-sm btn-success mt-1 shadow-lg" id="submitInfo"
                                        type="submit">Notify
                                        Me</button> -->
                                </form>

Here is my JQuery Code:

$(document).ready(function () {
 var $form = $('#mc-embedded-subscribe-form')
 if ($form.length > 0) {
   $('form input[type="submit"]').bind('click', function (event) {
     if (event) event.preventDefault()
     register($form)
   })
 }
})

function register($form) {
 $('#mc-embedded-subscribe').val('Sending...');
 $.ajax({
   type: $form.attr('method'),
   url: $form.attr('action'),
   data: $form.serialize(),
   status: "unsubscribed",
   headers: {
     'Authorization': 'Basic ' + new Buffer(`anything': 'apikey xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx-usx`)
   },
   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) {
     $('#mc-embedded-subscribe').val('subscribe')
     if (data.result === 'success') {
       // Yeahhhh Success
       console.log(data.msg)
       $('#mce-EMAIL').css('borderColor', '#ffffff')
       $('#subscribe-result').css('color', 'rgb(53, 114, 210)')
       $('#subscribe-result').html('<p>Thank you for subscribing. We have sent you a confirmation email.</p>')
       $('#mce-EMAIL').val('')
     } else {
       // Something went wrong, do something to notify the user.
       console.log(data.msg)
       $('#mce-EMAIL').css('borderColor', '#ff8282')
       $('#subscribe-result').css('color', '#ff8282')
       $('#subscribe-result').html('<p>' + data.msg.substring(4) + '</p>')
     }
   }
 })
};

I have tried to make this request using Fetch and AJAX, but no cigar. This approach has helped me make progress but ran into this little issue. I have reviewed the following questions and answers for additional support:

Javascript + MailChimp API subscribe

AJAX Mailchimp signup form integration Access MailChimp API 3.0 (GET)

Lastly, here is the MailChimp API documentation.

Add a Contact to a List/Audience (1 paragraph)

Add a new list member (search on "Add a new list member")

HTTP Basic Authentication(fourth paragraph)

Thank you for the help!!


Solution

Exposing your API key on front-end is not a good idea. You can follow this approach to add users to specific List/ Audience

<!-- Please copy your form from Mailchimp Signup form ( condensed in your case ) or copy the form and input values from the form  -->
    <form action="Your url from signup form" method="get" id="mc-embedded-subscribe-form" name="mc-embedded-subscribe-form" class="validate" target="_blank" novalidate>
        <div id="mc_embed_signup_scroll">
        <label for="mce-EMAIL">Subscribe</label>
        <input type="email" value="" name="EMAIL" class="email" id="mce-EMAIL" placeholder="email address" required>
        <!-- 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="from signup form" tabindex="-1" value=""></div>
        <div class="clear"><input type="submit" value="Subscribe" name="subscribe" id="mc-embedded-subscribe" class="button"></div>
        </div>
    </form>

Below is the ajax request

$(document).ready(function () {
    $("#mc-embedded-subscribe-form").submit(function (e) {
        let form = $("#mc-embedded-subscribe-form")
        e.preventDefault();
        var settings = {
            url: form.attr('action'),
            type: form.attr('method'),
            data: form.serialize(),
            dataType: 'jsonp',
            contentType: "application/json; charset=utf-8",
        };
        $.ajax(settings).done(function (response) {
            console.log(response);
        });
    })
})


Answered By - Akbar Ali
Answer Checked By - Willingham (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing