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:
-
Your AJAX JS (
jQuery.ajax()
) is not sending the POST data namedsite-choice
to your AJAX PHP callback (users_details_callback()
) which reads the data via$_POST['site-choice']
. -
Your AJAX PHP callback would result in WordPress echoing a zero (
0
) because you’re callingwp_die()
before returning any output and even if you returned it beforewp_die()
is called, you should actuallyecho
the output and notreturn
it. -
Your AJAX JS is expecting a JSON data back from the server (because you set
dataType
toJSON
—dataType : "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 usewp_send_json_success()
to send a JSON response without having to callwp_die()
: (note that I also optimized theif
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 ); }, } );