1

I wrote some extra fields for my custom taxonomy. I added the form fields to the add form. I got it to save by handling the appropriate values in $_POST. In 4.1.x, the add form is Ajax-ified. How can I clear out the form fields on success?

More specifically, how can I view the response to the add-tag admin ajax action?

  • Please post your javascript AJAX request code, there is an argument of the AJAX code reserved for a callback on success or failure and this would be the best place to reset the fields. – Jason Murray Feb 28 '15 at 14:58
  • i'm not making any outside of the core functionality. i'm pigging back on the existing WP functionality. – Daniel A. White Feb 28 '15 at 14:59
2

You could achieve this with a little bit of jQuery:

Create this file within THEMEFOLDER/js/ called field-clear.js and replace #formID with the ID of the form you would like to reset:

//Code runs when an ajax request succeeds
jQuery( document ).ajaxSuccess(function( event, xhr, settings ) {
    //Check ajax action of request that succeeded
    if(settings.action == 'add_tag') {
        //Reset the form
        jQuery('#formID')[0].reset();

        //Send ajax response to console.
        console.log("Triggered ajaxSuccess handler. The ajax response was: " + xhr.responseText );
    }
});

Then in functions.php load your javascript:

wp_register_script('field-clear-script', get_stylesheet_directory_uri() . '/js/field-clear.js', array('jquery'), null, true);

function field_clear_load_scripts() {
    wp_enqueue_script('field-clear-script');
}
add_action('admin_enqueue_scripts', 'field_clear_load_scripts');

EDIT - Added code to display ajax response text. Added check for ajax action parameter. Changed enqueue function to enqueue on admin as I think this is where it's required.

  • 1
    a little regex on settings.data and all is well, thanks – logic8 Jun 15 '18 at 17:16
0

Jason's answer is very close, which led to this solution for me on WP 4.9:

$(document).ajaxSuccess(function(evt, xhr, opts) {
    if (
        xhr.status >= 200
        && xhr.status < 300
        && opts.data
        && /(^|&)action=add-tag($|&)/.test(opts.data)
        && /(^|&)taxonomy=YOUR_TAXONOMY($|&)/.test(opts.data)
        && xhr.responseXML
        && $('wp_error', xhr.responseXML).length == 0
    ) {
        // clear your fields
    }
});

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.