Home Forums General Issues Callback for update succes Reply To: Callback for update succes

  • It isn’t so much more control, as it is a better frontend experience. People typically don’t want the entire page to have to refresh these days when submitting a form that shouldn’t change the rest of the page layout.

    Wordpress has builtin capabilities for adding custom AJAX function endpoints.

    You can add an AJAX handler using this code:

    // Sent from admin_users
    add_action( 'wp_ajax_my_ajax_action', 'my_ajax_handler' );
    // Sent from non-admin and anonymous users
    add_action( 'wp_ajax_nopriv_my_ajax_action', 'my_ajax_handler' );
    function my_ajax_handler() {
        // Access $_POST to see what your javascript sent to the AJAX endpoint here
        $result = array(
            'success' => false,
            'errorMessage' => 'Uh oh! An error has occurred...'
        // Manipulate your custom fields here, modifying $result as necessary
        echo json_encode( $result );
        // Note that AJAX handlers should exit() or wp_die() instead of returning
    wp_localize_script( 'your-js-script-id', 'ajax_object', array( 
        'ajax_url' => admin_url( 'admin-ajax.php' )
    ) );

    You may call this handler by sending an AJAX POST to the ajax_object.ajax_url defined above with action set to my_ajax_action (note that this is the suffix of the add_action calls’ action name.

    For example:

    var data = {
        'action': 'my_ajax_action',
        'someOtherData': 0
    };, data, function(response) {
        response = JSON.parse(response);
        if (response.success) {
            // Success processing
        } else {
            // What to do on failure....