I am following an example on AJAX in Plugins on WordPress website. It’s very simple example, and I am trying to modify the example as I intend.
What I am trying to achieve is simple:
- When a new option is selected in select/option dropdown, detect the selected value
- Pass the selected value to PHP function via AJAX
However, the selected value doesn’t seem to be passed via AJAX.
The result I am getting is: whatever = 1234 | whatever2 =
How do I properly pass my variable to AJAX?
My code:
// Select/Option Dropdown
<select id="_type" name="_type">
<option value="AAA"> AAA </option>
<option value="BBB"> BBB </option>
<option value="CCC"> CCC </option>
</select>
// Detect change and call and AJAX
<script type="text/javascript">
jQuery('#_type'.change(function($) {
var val = jQuery('#_type').val(); <-- Here I am properly getting val as it changes.
console.log( '_type is changed to ' + val );
var data = {
'action': 'my_action',
'type': 'post',
'whatever': 1234,
'whatever2': val <-- But here val becomes empty.
};
jQuery.post(ajaxurl, data, function(response) {
alert( 'Got this from the server: ' + response );
});
}).change();
</script>
// PHP function 'my_action'
add_action( 'wp_ajax_my_action', 'my_action' );
function my_action() {
global $wpdb;
$whatever = $_POST['whatever'];
$whatever2 = $_POST['whatever2'];
echo 'whatever=" . $whatever . " | whatever2 = ' . $whatever2;
wp_die();
}