This is my first attempt to write a plugin and I get an error 400 when trying to use admin-ajax.php. I've looked through some topics both here and in the WordPress support forum, but cannot figure it out.
What I am trying to do is dependant drop-down select. I.e. you chose an option from select #1, then it has to be passed via ajax to populate the second dropdown. To make it simple (for now), everything is on my "frontend" file.
Here is my code:
<div class="row">
<select class="cat-select" name="lvl1" id="lvl1">
<option value="">-- select category --</option>
<?php
foreach ($this->getTopLevelCategories() as $category) {
print '<option value="' . $category->term_id . '">' . $category->name . ' (' . $category->count . ')</option>';
}
?>
</select>
</div>
<script type="text/javascript">
jQuery(document).ready(function () {
jQuery('#lvl1').change(function () {
var lvl1Val = jQuery('#lvl1').val();
jQuery('#lvl2').empty();
jQuery.ajax({
url: "<?php bloginfo('wpurl'); ?>/wp-admin/admin-ajax.php",
method: 'POST',
data: {
'action':'getLVl2',
'lvl1' : document.getElementById('lvl1').value
},
success: function(response, status) {
jQuery('#lvl2').append(response);
alert(response);
console.log(response);
},
error: function(errorThrown){
console.log(errorThrown);
}
});
});
});
</script>
<div class="row">
<select class="cat-select" name="lvl2" id="lvl2">
<option value="" disabled selected>-- select category lvl2 --</option>
</select>
</div>
<?php
function getLVl2()
{
if (isset($_POST['lvl1'])) :
$parent = $_POST['lvl1'];
$option = '<option value="' . $parent . '">';
$option .= $parent;
$option .= '</option>';
echo $option;
wp_die();
endif;
}
add_action('wp_ajax_getLVl2', 'getLVl2');
add_action('wp_ajax_nopriv_getLVl2', 'getLVl2');
?>
Note:
- The code in the function will be changed. What I am trying to do is output the value of the option selected from the first dropdown just to see that it works.
- The function and the script will be moved to their places to "keep the code clean"
functions.php
file. Did you put yourgetLVl2()
function andadd_action()
code in the functions file? Also, have you considered using the REST API instead (which can give you a pretty route/path likemy-plugin/v1/getLVl2
)?/wp/v2/categories
for the corecategory
taxonomy. So for example,fetch( '/wp-json/wp/v2/categories' )
would let you, via JS, fetch the site's categories.add_action()
? Is it at the root in the plugin file, e.g.<?php /* Plugin Name: My Plugin */ ... add_action( ... );
?$_POST['lvl1']
was not set - and you just need to ensure that your JS sends the proper data. So you could just dovar_dump( $_POST );
before theif
block and you'd know for sure if my guess was correct.