1

I have built this Mailchimp Newsletter sign up plugin. PHP its not my strength so I am not being able to fix the error it has.

I used This Mailchimp wrapper: https://github.com/drewm/mailchimp-api.

My PHP file is:

<?php

include('MailChimp.php');  // path to API wrapper downloaded from GitHub
use \DrewM\MailChimp\MailChimp;

function sm_mailchimp_subscribe()
{

    // Settings:
    $mcAPIKey = '70000000000000000007e-us00';
    $mcListID = '323231214212';
    $status = 'subscribed';
    // Settings End

    $MailChimp = new MailChimp($mcAPIKey);

    $email = $_POST['email'];
    $fname = $_POST['fname'];
    $sname = $_POST['sname'];
    $merge_vars = array(
        'FNAME' => $fname,
        'LNAME' => $sname
    );

    if (isset($email) and isset($fname) and isset($sname)) {
        $result = $MailChimp->post("lists/" . $mcListID . "/members", [
            'email_address' => $email,
            'merge_fields'  => $merge_vars,
            'status'        => $status,
        ]);

        return json_encode($result);
    }
}

if ($_POST['ajax']) {
    echo sm_mailchimp_subscribe();
} elseif ($_POST['action'] == 'setCookies') {
    echo setCookiesTemp();
}


function setCookiesTemp()
{
    setcookie('sm_mailchimp-temp', true, time() + (86400 * 28), '/');
}
function setCookiesPerm()
{
    setcookie('sm_mailchimp-perm', true, time() + (86400 * 28 * 24), '/');
}


And here is the JS:

jQuery(function($) {
  // From wp_localized
  const ajaxURL = ajax_obj.ajax_url;

  $(document).ready(function() {
    var body = $("body");
    var modal = `<div class="sm_mailchimp-modal">
                    <div class="sm_mailchimp-box">
                      <button class="sm_mailchimp-close">X</button>
                        <h3>Join Our Mailing List</h3>
                        <form name="sm_mailchimp-form" method="post" class="sm_mailchimp-form light">
                           <p>Subscribe to our newsletter and receive tips for a successful business.</p>
                            <input type="email" name="email" placeholder="Type Your Email" class="sm_sname">
                            <div class="sm_mailchimp-message"></div>
                            <button type="submit">SIGN UP</button>
                        </form>
                    </div>
                </div>`;

    if (!document.cookie.includes("sm_mailchimp-temp=1")) {
      $(modal)
        .hide()
        .appendTo(body);
      setTimeout(function() {
        $(".sm_mailchimp-modal").fadeIn();
      }, 5000);
    }

    $(".sm_mailchimp-close").click(function() {
      closeModal();
    });

    $(".sm_mailchimp-modal").click(function(e) {
      if (e.target == this) {
        closeModal();
      }
    });

    function closeModal() {
      $(".sm_mailchimp-modal").fadeOut();

      $.ajax({
        url: ajaxURL,
        method: "POST",
        data: { action: "setCookies" },
        success: function(data) {
          console.log("Cookie added as sm_mailchimp-temp=1");
        }
      });
    }

    $(".sm_mailchimp-form").submit(function() {
      var emailVal, fnameVal, snameVal;
      emailVal = $(".sm_email", this).val();
      fnameVal = $(".sm_fname", this).val();
      snameVal = $(".sm_sname", this).val();

      if (emailVal === "" || fnameVal === "" || snameVal === "") {
        $(".sm_mailchimp-message").html("Please fill out all the fields!");
        return false;
      } else {
        $(".sm_mailchimp-message").html("Adding your email address...");

        var form = $(this);
        $.ajax({
          url: ajaxURL,
          type: "POST",
          data: form.serialize() + "&ajax=true",
          success: function(msg) {
            var message = $.parseJSON(msg),
              result = "";
            if (message.status === "pending") {
              result =
                "Success!  Please click the confirmation link that will be emailed to you shortly.";
            } else if (message.status === "subscribed") {
              result =
                "Success!  You have been subscribed to our mailing list.";
            } else {
              result = "Oops: " + message.title;
              console.log("Error: ", message);
            }
            $(".sm_mailchimp-message").html(result);
          }
        });
        return false;
      }
    });
  });
});

The error is the following:

Once the Sign Up button is clicked the message "Adding your email address..." shows as it should but then it freezes there. The console shows the following error:

enter image description here

Weirdly, it used to work fine. And without a change it stopped. I built it a couple of months ago.


UPDATE

The error is actually coming from the success: function(msg) { line. The msg is empty. So, when it gets to message.status it cannot read the property of status null.

Question: Why is the success callback returning msg empty?

enter image description here

stemon
  • 599
  • 1
  • 5
  • 23
  • It looks like your Javascript is expecting a JSON response, but is getting an HTML response. This is _likely_ due to an error being spit out. View the raw response in your browser's Network Inspector to confirm this and update your question with the actual error message (you can also check your PHP error logs to see if the error is there too) – Patrick Q Jan 21 '20 at 15:56
  • THanks Patrick, question update. Hope you can help me out on this. – stemon Jan 23 '20 at 02:10
  • This is where you have to do your own debugging. Put some `echo`s in your `sm_mailchimp_subscribe()` function and find out where it stops doing what you expect it to do. View the output in your network inspector. It seems like probably either `$email`, `$fname`, or `$sname` are empty. – Patrick Q Jan 23 '20 at 13:17
  • Patrick, thanks so much again. You were right! However I am still stuck. Now I see that the ajax connection is returning 403. The plugin works well on my local env, but not live. https://peakintegratedmarketing.com/3088-2/. If you can check it out and see the console error, I noticed there is no access to the php file the ajax should connect to, https://peakintegratedmarketing.com/wp-content/plugins/stemon-mailchimp-form/assets/sm_mailchimp.php. Let me know your thoughts please. thanks – stemon Jan 24 '20 at 15:43
  • There might be a `.htaccess` rule (or apache conf file rule) that prevents direct access to that file or a whole directory of files. Impossible for me to say. – Patrick Q Jan 24 '20 at 15:57
  • Suppose it is a `.htaccess` rule. Do you know how to write a rule that allows it? Here is what I found and tried: ` Order allow,deny Allow from all ` – stemon Jan 24 '20 at 16:43

0 Answers0