I have a html form with select boxes and I want to display different data depending on what the users select.
All I really need to do is change 1 variable in php based on the selection.
I make an external API call that returns data and displays it in an html table. I want to to change 1 small part of the api call (an id in the get uri) depending on the users choice.
Is there a simple way to do this?
I've got as far as making the jquery and enqueuing it with wordpress, and I'm getting a 200 response when changing the select box value. But I just can't seem to be able to change the PHP.
To avoid bombarding with code, I've changed the callback function to give an examlple of what I'd like to happen. Greatly appreciate any feedback. Thanks.
HTML
<form class="choose-site" action="" method="post">
<select id="choose-site" name="site-choice">
<option value="site1"><?php echo $primary_site ?></option>
<option value="site2"><?php echo $site_2 ?></option>
</select>
</form>
<div id="test123">
<p><?php echo $msg; ?></p>
</div>
JQUERY
(function($) {
$(document).ready(function() {
$("#choose-site").on("change",function() {
const val = this.value;
if (val) {
$.ajax({
type : "post",
dataType : "JSON",
url: my_ajax_object.ajax_url,
data : {
action: "my_ajax_action"
},
success: function(data) {
$("#test123").html(data);
}
});
}});
});
})(jQuery);
PHP in Functions.php
<?php
add_action( 'wp_ajax_my_ajax_action', 'users_details_callback' );
add_action( 'wp_ajax_nopriv_my_ajax_action', 'users_details_callback' );
function users_details_callback() {
if (isset($_POST['site-choice']) && $_POST['site-choice'] == 'site1') {
$msg = "hi";
}
if (isset($_POST['site-choice']) && $_POST['site-choice'] == 'site2') {
$msg = "bye";
}
wp_die();
return $msg;
}
?>
Is there a way to change the value of $msg and send it back to the HTML?
wp_die()
, but by "return", I mean echo the response, soecho $msg; wp_die();
. Then your JSsuccess
callback would receive the$msg
value in thedata
variable. However, if you set thedataType
tojson
, then you should echo a valid JSON string.admin-ajax
" - by the REST API handbook.