Files
wp-prometheus/assets/js/admin.js

101 lines
3.5 KiB
JavaScript
Raw Normal View History

/**
* WP Prometheus Admin JavaScript
*
* @package WP_Prometheus
*/
(function($) {
'use strict';
$(document).ready(function() {
// Validate license button.
$('#wp-prometheus-validate-license').on('click', function(e) {
e.preventDefault();
performLicenseAction('wp_prometheus_validate_license', 'Validating...');
});
// Activate license button.
$('#wp-prometheus-activate-license').on('click', function(e) {
e.preventDefault();
performLicenseAction('wp_prometheus_activate_license', 'Activating...');
});
// Regenerate token button.
$('#wp-prometheus-regenerate-token').on('click', function(e) {
e.preventDefault();
if (confirm('Are you sure you want to regenerate the auth token? You will need to update your Prometheus configuration.')) {
var newToken = generateToken(32);
$('#wp_prometheus_auth_token').val(newToken);
}
});
/**
* Perform a license action via AJAX.
*
* @param {string} action AJAX action name.
* @param {string} message Loading message.
*/
function performLicenseAction(action, message) {
var $spinner = $('#wp-prometheus-license-spinner');
var $message = $('#wp-prometheus-license-message');
$spinner.addClass('is-active');
$message.hide();
$.ajax({
url: wpPrometheus.ajaxUrl,
type: 'POST',
data: {
action: action,
nonce: wpPrometheus.nonce
},
success: function(response) {
$spinner.removeClass('is-active');
if (response.success) {
$message
.removeClass('notice-error')
.addClass('notice notice-success')
.html('<p>' + response.data.message + '</p>')
.show();
// Reload page after successful validation/activation.
setTimeout(function() {
location.reload();
}, 1500);
} else {
$message
.removeClass('notice-success')
.addClass('notice notice-error')
.html('<p>' + (response.data.message || 'An error occurred.') + '</p>')
.show();
}
},
error: function() {
$spinner.removeClass('is-active');
$message
.removeClass('notice-success')
.addClass('notice notice-error')
.html('<p>Connection error. Please try again.</p>')
.show();
}
});
}
/**
* Generate a random token.
*
* @param {number} length Token length.
* @return {string} Generated token.
*/
function generateToken(length) {
var charset = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
var token = '';
for (var i = 0; i < length; i++) {
token += charset.charAt(Math.floor(Math.random() * charset.length));
}
return token;
}
});
})(jQuery);