5

I created a Theme Options page where the user can edit some of the theme settings. Now I'm trying to save this options asynchronously but it seems I have some problems integrating the handler file into WP.

The Theme Options is a simple admin page nested under Appearance.

When pressing the save button:

<a id = "save-settings" href = "#" data-nonce = "<?php wp_create_nonce("sace_settings_nonce") ?>"><?php echo _('Save Settings') ?></a>

the following JS script is called:

function(){
    jQuery.ajax({
        type : 'POST',
        url : themeRoot + 'framework/AsyncAction.php',
        data: { action  : 'save_settings',
                name    : 'John',}
        }).done(function(resp) {
            alert(resp);
        });
},

The handler .php file contains:

<?php
include_once('SettingsController.php');
define ('SAVE_SETTINGS', 'save_settings');

add_action('wp_ajax_save_settings', 'save_settings');

function save_settings(){
    global $controller;
    $name = esc_attr($_POST['name']);
    echo 'Hi, ' . $name;
}

?>

Running this code throws the following error:

Fatal error: Call to undefined function add_action()

I also tryied:

  1. hook the action on init -> same problem
  2. remove the hook completely. This caused the undefined error to be thrown for esc_attr()

It seems that I don't have access to any of the WP functions but I have no idea how to fix it.

Thanks!

7

Wordpress has a native AJAX file that should do all that you want, and this will ensure that all native WP functions are included. If you require additional functionality from 'framework/AsyncAction.php', you can include_once(), as you do with 'SettingsController.php'.

See the Codex for more information and examples - AJAX in Plugins

If you wish to use AJAX on the front end of your website, you need to add the following lines to your functions.php file -

/** Declare the URL to the file that handles the AJAX request (wp-admin/admin-ajax.php) */
wp_enqueue_script('my-ajax-request', admin_url('admin-ajax.php'), array('jquery'));
wp_localize_script('my-ajax-request', 'MyAjax', array('ajaxurl' => admin_url('admin-ajax.php')));
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.