Ajax in a settings page (update_option is undefined)

I’m making a request to my plugin’s php file via ajax and it’s supposed to save some data with update_option(), but php throws an error:

Call to undefined function update_option()

I’m guessing that when I call my php file with ajax WP doesn’t load it’s functions… or something?

Cheers

1
1

Don’t send AJAX to your PHP file directly. Instead, use WordPress’ built-in AJAX functions 1). You can register an AJAX callback from your plugin, and WordPress will route requests to your plugin file for you.

For example, this code will register a callback called “wpa_49691”:

add_action( 'wp_ajax_wpa_49691', 'wpa_49691_callback' );
add_action( 'wp_ajax_nopriv_wpa_49691', 'wpa_49691_callback' );
function wpa_49691_callback() {
    // Do whatever you need with update_option() here.
    // You have full access to the $_POST object.
}

Then, you post whatever data you need, just specify action in the object:

<script type="text/javascript">
    jQuery(document).ready(function($) {
        var data = {
            action: 'wpa_49691',
            my_var: 'my_data'
        };

        jQuery.post( ajaxurl, data, function(response) {
            // handle response from the AJAX request.
        });
    });
</script>

This script will post your data to the server. Inside the server callback, you’ll see $_POST['my_var'] = 'my_data'.

For further reading, check out:

  • The Codex
  • WordPress and AJAX – Free ebook on the topic

1) Use wp_register_script( $handle ); » wp_enqueue_script( $handle ) » wp_localize_script( $handle ); – the last one to move php stuff into a js-var that can be access inside your AJAX script.

Leave a Comment