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 );