I’m having trouble understanding how wp_send_json_error works to return error messages. It works fine as long as none of the error conditions are met. But if there is an error, then nothing gets returned.

How do I return the error messages set in wp_send_json_error() when there is an error?

See my code:

function submit_youtube_callback() {
    check_ajax_referer( 'randomnonce', 'security' );

    if (    !isset($_POST['post_id']) || 
            !is_numeric($_POST['post_id']) || 
            !get_post_status($_POST['post_id']) || 

            !isset($_POST['yt_url']) ||
            !isset($_POST['terms'])
            ) {

        wp_send_json_error( 'Error: Invalid data!' );
    }

    // Check if terms are checked
    $terms = $_POST['terms'];
    if ( $terms != true ) {
        wp_send_json_error( 'Error: You must accept the terms.' );
    }

    // Check if valid youtube URL   
    $youtube_url = $_POST['yt_url'];
    $preg = '~^(?:https?://)?(?:www\.)?(?:youtube\.com|youtu\.be)/watch\?v=([^&]+)~x';
    $has_match = preg_match($preg, $youtube_url, $matches); 
    if ( empty($matches[1]) ) {
        wp_send_json_error( 'Error: You did not enter a valid YouTube URL.');
    }   

    echo '<p>youtube: '. $youtube_url .'</p>';  
    echo '<p>terms accepted: ' . $terms .'</p>';

    wp_die();
} add_action( 'wp_ajax_cp_narrations_callback', 'submit_youtube_callback' );

And Javascript:

function submit_youtube_javascript() {
    if ( is_single() ) {

        $ajax_nonce = wp_create_nonce( "randomnonce" );

        ?>
        <script>
            ( function( $ ) {
                var ajaxurl = "<?php echo admin_url('admin-ajax.php'); ?>",
                    submit_youtube = $('#submitYouTubeForm');

                // Star rating button
                $(submit_youtube).on('submit', function(event) {
                    event.preventDefault();

                    var submit_youtube_url = $('#submitYouTubeURL').val(),
                    submit_youtube_terms = $('#youtube_terms').is(':checked');

                    // Data to be sent to function
                        var data = {
                            'action': 'submit_youtube_callback',
                            'security': '<?php echo $ajax_nonce; ?>',
                            'post_id': <?php echo get_the_ID(); ?>,

                            'yt_url': submit_youtube_url,
                            'terms': submit_youtube_terms
                        };

                        // Send Data
                        jQuery.post(ajaxurl, data, function(response) {
                            submit_youtube.replaceWith(response);
                        });                     
                });
            } )( jQuery );
        </script> 
        <?php
    }
} add_action( 'wp_footer', 'submit_youtube_javascript', 100 );

1 Answer
1

wp_send_json_error( 'Error: Invalid data!' )

Will echoes a JSON string:
{"success":false,"data":"Error: Invalid data!"}

The nice thing about wp_send_json_error() is, the parameter could also be a WP_Error object.

As opposed to wp_send_json_success( 'Everything okay.' ) which echoes this JSON string:
{"success":true,"data":"Everything okay."}

Both rely internally on wp_send_json() to echo the JSON data properly and die() afterwards.

But if there is an error, then nothing gets returned.

Actually, I can’t believe this right now. But when I look into your JS code, you do not handle the JSON response properly. Actually if everything works fine, you return HTML, which replaces $('#submitYouTubeForm'). But with the JSON response, you do not have HTML but a JSON response.

Use console.log( response ) to see, if you really do not get the JSON string. You should think about either using JSON for all your responses or instead of using wp_send_json_error() just return a plain HTML error message and die() by yourself.

Leave a Reply

Your email address will not be published. Required fields are marked *