web-dev-qa-db-fra.com

Appelez la fonction javascript lorsque la catégorie a été ajoutée via ajax

J'ai créé un plugin pour gérer les images en vedette pour les catégories (enfin, pour la taxonomie personnalisée en fait, mais peu importe). Tout fonctionne correctement, sauf que l'image sélectionnée n'est pas effacée après l'ajout d'un nouveau terme. Tous les champs standard sont réinitialisés, mais l'image personnalisée ne l'est pas.

Le problème est que les termes de taxonomie sont ajoutés via ajax, sans rechargement de page (comme les posts ou les pages). J'ai donc besoin d'intercepter l'événement à succès ajax.

Essayé $(document).ajaxSuccess - ne fonctionne pas. Google n'a aucun résultat utile.

Des idées?

Voici la capture d'écran pour illustrer le problème.

Term image

Voici le code javascript que j'utilise:

/**
 * Callback function for the 'click' event of the 'Set featured image' anchor in its meta box.
 * Displays the media uploader for selecting an image.
 */
function renderMediaUploader() {
    'use strict';

    var file_frame, image_data;

    /**
     * If an instance of file_frame already exists, then we can open it
     * rather than creating a new instance.
     */
    if (undefined !== file_frame) {
        file_frame.open();
        return;
    }

    /**
     * If we're this far, then an instance does not exist, so we need to
     * create our own.
     *
     * Here, use the wp.media library to define the settings of the Media
     * Uploader. We're opting to use the 'post' frame which is a template
     * defined in WordPress core and are initializing the file frame
     * with the 'insert' state.
     *
     * We're also not allowing the user to select more than one image.
     */
    file_frame = wp.media.frames.file_frame = wp.media({
        frame: 'post',
        state: 'insert',
        multiple: false
    });

    /**
     * Setup an event handler for what to do when an image has been selected.
     *
     * Since we're using the 'view' state when initializing
     * the file_frame, we need to make sure that the handler is attached
     * to the insert event.
     */
    file_frame.on('insert', function () {

        var json, image;
        // Read the JSON data returned from the Media Uploader
        json = file_frame.state().get('selection').first().toJSON();
        image = json.url;

        // First, make sure that we have the URL of an image to display
        if (0 > image.length) {
            return;
        }

        // After that, set the properties of the image and display it
        jQuery('#taxonomy-image-container')
            .children('img')
            .attr('src', json.url)
            .attr('alt', json.caption)
            .attr('title', json.title)
            .show()
            .parent()
            .removeClass('hidden');

        // Next, hide the anchor responsible for allowing the user to select an image
        jQuery('#taxonomy-image-container')
            .prev()
            .hide();

        // Display the anchor for the removing the featured image
        jQuery('#taxonomy-image-container')
            .next()
            .show();

        // Add image url to hidden form field
        jQuery('#taxonomy-image-src').val(json.url);

    });

    // Now display the actual file_frame
    file_frame.open();

}

/**
 * Callback function for the 'click' event of the 'Remove Featured Image' anchor in its meta box.
 * Resets the meta box by hiding the image and by hiding the 'Remove Featured Image' container.
 */
function resetUploadForm($) {
    'use strict';

    // First, we'll hide the image
    $('#taxonomy-image-container')
        .children('img')
        .hide();

    // Then display the previous container
    $('#taxonomy-image-container')
        .prev()
        .show();

    // Finally, we add the 'hidden' class back to this anchor's parent
    $('#taxonomy-image-container')
        .next()
        .hide()
        .addClass('hidden');

    // Finally, we reset the hidden form field
    $('#taxonomy-image-src')
        .val('');

}

/**
 * Checks to see if the input field for the thumbnail source has a value.
 * If so, then the image and the 'Remove featured image' anchor are displayed.
 * Otherwise, the standard anchor is rendered.
 */
function renderFeaturedImage($) {

    /* If a thumbnail URL has been associated with this image
     * Then we need to display the image and the reset link.
     */
    if ('' !== $.trim($('#taxonomy-image-src').val())) {

        $('#taxonomy-image-container').removeClass('hidden');

        $('#set-taxonomy-image')
            .parent()
            .hide();

        $('#remove-taxonomy-image')
            .parent()
            .removeClass('hidden');

    }

}

(function ($) {
    'use strict';

    $(function () {

        $('#set-taxonomy-image').on('click', function (evt) {

            // Stop the anchor's default behavior
            evt.preventDefault();

            // Display the media uploader
            renderMediaUploader();

        });

        $('#remove-taxonomy-image').on('click', function (evt) {

            // Stop the anchor's default behavior
            evt.preventDefault();

            // Remove the image, toggle the anchors
            resetUploadForm($);

        });

        renderFeaturedImage($);

        /**
         * Now we need to remove the image and toggle the anchors
         * after we successfully added new term
         */
        $(document).ajaxComplete(function( event, xhr, settings ){
            /**
             * We should somehow intercept the correct event among lots of them fired by WordPress
             * and just call: resetUploadForm($);
             */
            console.log( event );
            console.log( xhr );
            console.log( settings );

        });

    });

})(jQuery);
1
Ihor Vorotnov

Récemment, j'ai juste le même problème et j'ai la solution.

  1. utilisez l'événement ajaxSuccess car nous devons réinitialiser l'entrée une fois l'ajax terminé.
  2. filtrer les données de paramètres pour une action et un écran spécifiques.

Code:

$(document).ajaxSuccess(function(e, request, settings){
        var object = $.deparam(settings.data);
        if(object.action === 'add-tag' && object.screen === 'edit-category' && object.taxonomy === 'category'){
            //DO RESET Your Input Here
        }
    });

J'ai utilisé le plugin jquery-deparam pour analyser la chaîne settings.data.

1
pxface