Site icon Anthony Carbon

How to fix ajax POST /wp-admin/admin-ajax.php 500 (Internal Server Error)?

How to fix ajax POST /wp-admin/admin-ajax.php 500 (Internal Server Error)? I’m receiving this error in console when I’m about to call my ajax code backend. It appears to me that I am missing global variable in enable the code to work. See the wrong and correct coding below. It might be not the same issue on you but you can found a clue how to fix 500 (Internal Server Error) error.

Wrong code, missing “global $wpdb;” global variable and this is causing 500 (Internal Server Error) error

// JS CODE
jQuery( document ).ready( function( $ ){
    $( '#gallery #select-friend' ).keyup( function(){
        $.ajax({
            url	: ajaxurl,
            type	: 'post',
            data	: {
                        action	: 'ys_creadit_to',
                        keyword : $( '#gallery #select-friend' ).val()
                    },
            success	: function(data){
                console.log(data);
            }
        });
    });
});
// PHP CODE
add_action( 'wp_ajax_ys_creadit_to', 'ajax_creadit_to' );
add_action( 'wp_ajax_nopriv_ys_creadit_to', 'ajax_creadit_to' );
function ajax_creadit_to(){
	$keyword = isset( $_POST['keyword'] ) ? explode( ' ', $_POST['keyword'] ) : array();
	$s = "";
	if( $keyword ) :
		foreach( $keyword as $id => $word ) :
			if( $id != 0 && ( ( count( $keyword ) - 1 ) < $id ) ) :
				$s .= " OR ";
			endif;
			$s .= "(display_name LIKE '%$word%')";
		endforeach;
	endif;
	$results = $wpdb->get_results( "SELECT ID, display_name FROM wp_users WHERE display_name LIKE '%$s%' LIMIT 0, 50" );
	print_r( $results );
	die();
}

Correct and working code

// JS CODE
jQuery( document ).ready( function( $ ){
    $( '#gallery #select-friend' ).keyup( function(){
        $.ajax({
            url	: ajaxurl,
            type	: 'post',
            data	: {
                        action	: 'ys_creadit_to',
                        keyword : $( '#gallery #select-friend' ).val()
                    },
            success	: function(data){
                console.log(data);
            }
        });
    });
});
// PHP CODE
add_action( 'wp_ajax_ys_creadit_to', 'ajax_creadit_to' );
add_action( 'wp_ajax_nopriv_ys_creadit_to', 'ajax_creadit_to' );
function ajax_creadit_to(){
	global $wpdb;
	$keyword = isset( $_POST['keyword'] ) ? explode( ' ', $_POST['keyword'] ) : array();
	$s = "";
	if( $keyword ) :
		foreach( $keyword as $id => $word ) :
			if( $id != 0 && ( ( count( $keyword ) - 1 ) < $id ) ) :
				$s .= " OR ";
			endif;
			$s .= "(display_name LIKE '%$word%')";
		endforeach;
	endif;
	$results = $wpdb->get_results( "SELECT ID, display_name FROM wp_users WHERE display_name LIKE '%$s%' LIMIT 0, 50" );
	print_r( $results );
	die();
}
Exit mobile version