Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

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

share|improve this question
add comment

2 Answers 2

up vote -17 down vote accepted

Include wp-load.php in your Ajax file

share|improve this answer
10  
This is not the proper way to handle AJAX in WordPress. If you're loading wp-load.php directly, you're doing something wrong. –  EAMann Apr 20 '12 at 18:28
5  
This is NOT the way to do it –  MZAweb Apr 20 '12 at 19:41
5  
@IvanDokov (Not meant sarcastic:) You get a badge for deleting downvoted Qs. That happens to the best :) –  kaiser Apr 20 '12 at 21:59
add comment

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:

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.

share|improve this answer
5  
This is the way to do it –  MZAweb Apr 20 '12 at 19:41
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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