/** * Refresh Resources * * @author ConvertKit */ document.addEventListener( 'DOMContentLoaded', convertKitRefreshResourcesInitEventListeners ); /** * Binds click event listeners to refresh resource buttons. * * @since 2.4.4 */ function convertKitRefreshResourcesInitEventListeners() { // Refreshes resources when the Refresh button is clicked. document .querySelectorAll('button.wp-convertkit-refresh-resources') .forEach(function (element) { element.addEventListener( 'click', function (e) { e.preventDefault(); convertKitRefreshResources(element); }, false ); }); } /** * Refresh resources when a button is clicked. * * @since 2.4.4 * * @param {Object} button Button element. */ function convertKitRefreshResources(button) { // Remove any existing error notices that might be displayed. convertKitRefreshResourcesRemoveNotices(); const resource = button.dataset.resource, field = button.dataset.field; // Disable button and set is-refreshing class. button.disabled = true; button.classList.add('is-refreshing'); // Perform AJAX request to refresh resource. fetch(convertkit_admin_refresh_resources.ajaxurl + resource, { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-WP-Nonce': convertkit_admin_refresh_resources.nonce, }, }) .then(function (response) { // Convert response JSON string to object. return response.json(); }) .then(function (response) { if (convertkit_admin_refresh_resources.debug) { console.log(response); } // Show an error if the request wasn't successful. if (typeof response.code !== 'undefined') { // Show error notice. convertKitRefreshResourcesOutputErrorNotice(response.message); // Enable button and remove is-refreshing class. button.disabled = false; button.classList.remove('is-refreshing'); return; } const selectedOption = document.querySelector(field).value; // Remove existing select options. document .querySelectorAll(field + ' option') .forEach(function (option) { // Skip if data-preserve-on-refresh is specified, as this means we want to keep this specific option. // This will be present on the 'None' and 'Default' options. if (option.dataset.preserveOnRefresh !== undefined) { return; } // Remove this option. option.remove(); }); // Depending on the resource we're refreshing, populate the