I recently built a Mailchimp addon plugin for the Chamber Dashboard plugins. The plugin uses the Mailchimp api key to connect to Mailchimp and display the lists in the plugin options page. The admin can select a Mailchimp list to which new member emails can be automatically added.

Without Ajax, the user would have to save the api key first to display the Mailchimp lists dropdown. After they select the list, they would have to save the options again so that their list gets saved.

Using Ajax, it is easy to give them an option to save the api key temporarily and display the Mailchimp list. Once the user selects the list, they can save the options all at once.

Here is how to implement the Ajax functionality. The first step is to add the fields for api key and the MailChimp list.

Here is the callback function that renders the api input field.


function cdash_mailchimp_api_key_render($args){
  //specifying the ajax url
  $ajax_url = admin_url( 'admin-ajax.php' );
  $options = get_option('cdash_addon_options');
  if(!isset($options['cdash_mailchimp_api_key'])){
    $options['cdash_mailchimp_api_key'] = '';
  }
  ?>
  <input type='text' name='cdash_addon_options[cdash_mailchimp_api_key]' id="cdash_mailchimp_api_key" value='<?php echo $options['cdash_mailchimp_api_key']; ?>'>
  <br /><span class="description"><?php echo $args[0]; ?></span><br />
  <?php
  //Displaying the save button only if the api key is empty
  if($options['cdash_mailchimp_api_key'] == ''){
    ?>
    <button type="button" name="cdashmc_save_api_key" class="cdashmc_button" id="cdashmc_save_api_key">Save Api Key</button><span class="cdashmc_success_message save_api"></span>
    <?php
  }else{
    //if api key is not empty, we are displaying the Delete button
    ?>
    <button type="button" name="cdashmc_delete_api_key" class="cdashmc_button" id="cdashmc_delete_api_key">Delete Api Key</button><span class="cdashmc_success_message delete_api"></span>
    <?php
  }
}

The api key render form has a couple of additional buttons. The ‘Save Api Key’ is displayed only if the api key is not saved in the database. If there is a valid Api Key, the ‘Delete Api Key’ is displayed.

The ‘Save Api Key’ button also triggers the JavaScript. When the Save button is clicked, the script checks if there is an api key. If there is a valid api key, it generates a drop down of lists from Mailchimp associated with that api.

The api key from the field is used to connect to MailChimp to get the lists.

Here is the JavaScript and Ajax functions that do the trick.

jQuery(document).ready(function($){
  // When the api key is saved, get the list drop down
  $('#cdashmc_save_api_key').click(function (event) {
    event.preventDefault();
    var api_key = $('#cdash_mailchimp_api_key').val();
    if(api_key == ''){
      $(".cdashmc_success_message.save_api").text(" Please enter an api key.");
    }else{
      $.ajax({
        url: ajaxurl,
        type:'post',
        data: {
          'action': 'cdashmc_list',
          'cdash_mailchimp_api_key': api_key,
        },
        beforeSend: function(){
          // Show loading container
          $("#cdashmc_ajax_loader").css("display", "block");
          $(".cdashmc_api_key_msg").css("display", "none");
        },
        success: function(response){
          $("#cdashmc_list").replaceWith(response);
          $(".cdashmc_api_key_msg").css("display", "none");
          $(".cdashmc_success_message.save_api").text(" API key successfully saved.");
        },
        complete:function(data){
          // Hide image container
          $("#cdashmc_ajax_loader").hide();
          $('#cdashmc_save_api_key').hide();
        }
      });
    }
  });

  $('#cdashmc_delete_api_key').click(function (event) {
    $("#cdash_mailchimp_api_key").val("");
    $("#cdash_mailchimp_list").hide();
    $(".cdashmc_list_desc, .cdashmc_check_api_msg").hide();
    $("#cdashmc_api_delete_notice").css("display", "block");
  });

});

The Ajax function is calling the cdashmc_list function which connects to the server and gets the results back to the Ajax. cdashmc_list calls the function that uses the api to get the Mailchimp lists and send the list as a response back to the Ajax function. Here is the cdashmc_list function.

//Function to display the Mailchimp lists via Ajax
//Used the code from https://rudrastyh.com/mailchimp-api/get-lists.html to display the Mailchimp lists using the api key
function cdashmc_list(){
    $options = get_option('cdash_addon_options');
  if(isset($_POST['cdash_mailchimp_api_key'])){
    $api_key = $_POST['cdash_mailchimp_api_key'];
  }else{
    $api_key = '';
  }
  $response = '';
  if($api_key == ''){
    $response = "No api key found";
  }else{ //if there is an api key
    $data = array(
    	'fields' => 'lists', // total_items, _links
    );
    $url = 'https://' . substr($api_key,strpos($api_key,'-')+1) . '.api.mailchimp.com/3.0/lists/';
    $result = json_decode( cdashmc_mailchimp_curl_connect( $url, 'GET', $api_key, $data) );
    if( !empty($result->lists) ) {
      $response = "<select name = 'cdash_addon_options[cdashmc_list]'>";
      $response .= "<option value=''>Select your Mailchimp List</option>";
      foreach( $result->lists as $list ){
        if ( $options['cdashmc_list'] == $list->id ){
          $selected = 'selected="selected"';
      }else{
          $selected = '';
      }
        $member_count = $list->stats->member_count;
        $response .= "<option value='$list->id' $selected>$list->name ($member_count)</option>";
      }
      $response .= "</select><br />";
      $response .= "<span class='description'>Your members will be subscribed to this list.</span>";
    }elseif ( is_int( $result->status ) ) { // full error glossary is here http://developer.mailchimp.com/documentation/mailchimp/guides/error-glossary/
    	$response = "<strong> $result->title :</strong> $result->detail";
    }else{
      $response = "<p class='cdashmc_check_api_msg'>Please check your api key.</p>";
    }
    //$response = $api_key;
  }
  die($response);
}
/We only need this as we are doing this only for the logged in users
add_action( 'wp_ajax_cdashmc_list', 'cdashmc_list' );

The last function we need is the cdashmc_list_render. The ‘<div id=”cdashmc_list”></div>’ which displays the Ajax response is inside this function. This function is almost the same as the cdashmc_list().


function cdashmc_list_render($args){
  ?>
  <!-- Display the loading button when Ajax is running -->
  <div id="cdashmc_list"></div><div id="cdashmc_ajax_loader">Loading...</div>
  <!--Display this message when the api key is deleted -->
  <div id="cdashmc_api_delete_notice">Please save the changes and enter the api key again to select the list.</div>
  <?php
  $options = get_option('cdash_addon_options');
  if(!isset($options['cdashmc_list'])){
    $options['cdashmc_list'] = '';
  }
  if($options['cdash_mailchimp_api_key'] == ''){
    echo "<p class='cdashmc_api_key_msg'>Please enter your MailChimp API key.</p>";
  }else{
    $api_key = $options['cdash_mailchimp_api_key'];
    // Query String Perameters are here
    // for more reference please vizit http://developer.mailchimp.com/documentation/mailchimp/reference/lists/
    $data = array(
    	'fields' => 'lists', // total_items, _links
    );
    $url = 'https://' . substr($api_key,strpos($api_key,'-')+1) . '.api.mailchimp.com/3.0/lists/';
    $result = json_decode( cdashmc_mailchimp_curl_connect( $url, 'GET', $api_key, $data) );
    //print_r( $result);


    if( !empty($result->lists) ) {
      ?>
    	<select name = "cdash_addon_options[cdashmc_list]"  id="cdash_mailchimp_list"  >
        <option value="">Select your Mailchimp List</option>
        <?php
    	foreach( $result->lists as $list ){
        ?>
        <option value = "<?php echo $list->id; ?>" <?php selected( $options['cdashmc_list'], $list->id ); ?>><?php echo $list->name . ' (' . $list->stats->member_count . ')'; ?></option>
        <?php
    		//echo '<option value="' . $list->id . '">' . $list->name . ' (' . $list->stats->member_count . ')</option>';
    		// you can also use $list->date_created, $list->stats->unsubscribe_count, $list->stats->cleaned_count or vizit MailChimp API Reference for more parameters (link is above)
    	}
      ?>
    	</select>
      <br /><span class="description cdashmc_list_desc"><?php echo $args[0]; ?></span>
      <?php
    } elseif ( is_array($result) && is_int( $result->status ) ) { // full error glossary is here http://developer.mailchimp.com/documentation/mailchimp/guides/error-glossary/
    	echo '<strong>' . $result->title . ':</strong> ' . $result->detail;
    }else{
      echo "<p class='cdashmc_check_api_msg'>Please check your api key.</p>";
    }
  }
}

Leave a Reply

Leave a Reply

%d bloggers like this: