How to change PHP variables with AJAX request in WordPress

Is there a way to change the value of $msg and send it back to the
HTML?

Your code is basically already doing that, but there are a few issues:

  1. Your AJAX JS (jQuery.ajax()) is not sending the POST data named site-choice to your AJAX PHP callback (users_details_callback()) which reads the data via $_POST['site-choice'].

  2. Your AJAX PHP callback would result in WordPress echoing a zero (0) because you’re calling wp_die() before returning any output and even if you returned it before wp_die() is called, you should actually echo the output and not return it.

  3. Your AJAX JS is expecting a JSON data back from the server (because you set dataType to JSONdataType : "JSON"), so your AJAX PHP callback should return a valid JSON response.

So to fix the issues:

  • In your PHP function (users_details_callback()), you can use wp_send_json_success() to send a JSON response without having to call wp_die(): (note that I also optimized the if condition)

    function users_details_callback() {
        if ( isset( $_POST['site-choice'] ) ) {
            $msg = '';
    
            if ( $_POST['site-choice'] == 'site1' ) {
                $msg = 'hi';
            } elseif ( $_POST['site-choice'] == 'site2' ) {
                $msg = 'bye';
            }
    
            wp_send_json_success( $msg );
        }
    
        // Send an error if we receive an invalid data.
        wp_send_json_error( 'your error' );
    }
    
  • In your jQuery.ajax() (or $.ajax()) call:

    $.ajax( {
        ...
        data: {
            action: 'my_ajax_action',
            // Send the site-choice data.
            'site-choice': $( '#choose-site' ).val(),
        },
        success: function( data ) {
            // 'data' is now an object and the $msg value from the server is put in
            // data.data, so use that instead of just 'data'.
            $( '#test123' ).html( data.data );
        },
    } );