1

I have a custom wordpress MetaBox assigned to post.

I have the function running on the post save_action.

However I was wonder if I can get a button inside of the metabox the will run the function on click without refreshing the page?

1

1 Answer 1

4

Yes you can. Here is a sample code to get you started and some links to follow up.

Add a button and a nonce-field to your form

<input type="hidden" name="my_ajax_nonce" value="<?php echo wp_create_nonce('my_ajax_action');?>" />
<button id="submit-my-form" type="submit"><?php _e('Save custom meta data')?></button>

You need to create and register your function you want to execute with your AJAX call:

function my_ajax_action() {
    if(!wp_verify_nonce( $_POST['my_ajax_nonce'], 'my_ajax_action' )) {
        die(-1);
    }
    //TODO: Add your button saving stuff here.
    var_dump($_POST['form_data']);
    exit;
}

function my_ajax_action_init() {
    if ($_POST['action'] == 'my_ajax_action') {
        do_action('wp_ajax_my_ajax_action');
    }
}

if (is_admin()){
    add_action('wp_ajax_my_ajax_action', 'my_ajax_action');
}

add_action( 'init', 'my_ajax_action_init');

NOTE Why calling the AJAX action on init and not when plugin is loaded? Because we need WordPress to be set up properly before we do our AJAX magic.

Now add your JS stuff in an extra file called my.ajax.action.js

jQuery(document).ready(function($) {
    $('body').on('click', '#submit-my-form', function(e) {
        e.preventDefault();
        var $me = $(this),
            action = 'my_ajax_action';
        var data = $.extend(true, $me.data(), {
            action: action,
            form_data: $('#post').serializeArray()
        });
        $.post(ajaxurl, data, function(response) {
            if(response == '0' || response == '-1'){
                //TODO: Add Error handling (Wrong nonce, no permissions, …) here.
            } else {
                //TODO: Do stuff with your response (manipulate DOM, alert user, …)
            }
        });
    });
});

Don't forget to enqueue your script.

function my_enqueue_scripts() {
    wp_enqueue_script( 'my-ajax-action', plugins_url('my.ajax.action.js', __FILE__), array('jquery'), NULL, true);
}
add_action( 'admin_enqueue_scripts', 'my_enqueue_scripts');

NOTE The global JS var adminurl is automatically included in the WP backend.

Further reading

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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