Save Plugin or Theme Setting Options using AJAX in WordPress

By Tejaswini Deshpande | May 8, 2014

Almost all of the WordPress plugins provide Plugins specific Options or Settings which provide an ability to the plugin user to change the default behavior of the plugin or specify some site specific values.

So if you are a plugin author, you would create the Settings Panel Page specific to your plugin. You can read on the WordPress Codex about how to register a Settings or Options admin page for your plugin.

This Options page form will save the options value to database (options table) thru the action=”options.php”. You should be having similar kind of form statement in your Options Page code as follows:

<form method="post" action="options.php">

In order to submit this form using AJAX, specify some ID to this form, say myOptionsForm i.e.

<form method="post" action="options.php" id="myOptionsForm">

We will be using jQuery Form plugin to submit the form using AJAX. jQuery Form comes shipped with WordPress itself (wp-includes), so no need to include any extra script in your plugin JS folder. Add the below code in your plugin file:

function myPlugin_admin_scripts() {
   if ( is_admin() ){ // for Admin Dashboard Only
      // Embed the Script on our Plugin's Option Page Only
      if ( isset($_GET['page']) && $_GET['page'] == 'myPluginOptions' ) {
         wp_enqueue_script( 'jquery-form' );
add_action( 'admin_init', 'myPlugin_admin_scripts' );

‘myPluginOptions’ is the Options Page Slug that you have specified in add_options_page function

After the form element closure i.e. after </form>, put the below code

<div id="saveResult"></div>
<script type="text/javascript">
jQuery(document).ready(function() {
   jQuery('#myOptionsForm').submit(function() { 
         success: function(){
            jQuery('#saveResult').html("<div id='saveMessage' class='successModal'></div>");
            jQuery('#saveMessage').append("<p><?php echo htmlentities(__('Settings Saved Successfully','wp'),ENT_QUOTES); ?></p>").show();
         timeout: 5000
      setTimeout("jQuery('#saveMessage').hide('slow');", 5000);
      return false; 

The CSS that could be included in admin CSS file or head for the modal could be as follows:

.successModal {
    display: block;
    position: fixed;
    top: 45%;
    left: 25%;
    width: 300px;
    height: auto;
    padding: 5px 20px;
    border: 3px solid green;
    background-color: #EFE;
    overflow: auto;
    -moz-border-radius: 15px; 
    -webkit-border-radius: 15px;
    -moz-box-shadow: 5px 5px 10px #cfcfcf;
    -webkit-box-shadow: 5px 5px 10px #cfcfcf;

This should help you guys to add some extra feel to your Options page. This is just a small tip on implementing AJAX submit on your Options page, you can change the message or CSS or modify the code as per the need.

Leave a Reply

Your email address will not be published. Required fields are marked *