Admin ajax error 400 when passing select value to populate another select

This may not definitively answer the question, but I hope this helps you in finding the most appropriate solution. And actually, I’ve tried the super simple plugin at the bottom with your HTML and JS, and everything worked fine for me.

This is my first attempt to write a plugin and I get an error 400 when trying to use admin-ajax.php

These are the common reasons why would admin-ajax.php return a 400 error (or a HTTP status of “400 Bad Request”) and then display a 0:

  1. Your AJAX action was never registered or it’s registered late.

  2. Your JS script or AJAX request did not include the correct action value, i.e. the part after wp_ajax_ and wp_ajax_nopriv_.

  3. The current user is not logged-in and your AJAX action was registered only for logged-in users.

    Or the other way round — the user is logged-in, but your AJAX action was only for non logged-in users.

And in your case, where the AJAX action is getLVl2, the 400 error was likely due to reason #1 above, because your JS is sending the correct action and it’s also registered for both logged-in and non logged-in users, i.e. you hooked on both wp_ajax_getLVl2 and wp_ajax_nopriv_getLVl2.

So you’d just need to ensure you are calling add_action() at the right time, e.g. in the main plugin file like so (which should be located at wp-content/plugins/my-plugin/my-plugin.php):

<?php
/*
 * Plugin Name: My Plugin
 */

function getLVl2() {
//  echo 'test';
    echo '<option>test</option>';
    wp_die();
}
add_action( 'wp_ajax_getLVl2', 'getLVl2' );        // for logged-in users
add_action( 'wp_ajax_nopriv_getLVl2', 'getLVl2' ); // for non logged-in users

Now try, using your browser, visiting https://example.com/wp-admin/admin-ajax.php?action=getLVl2 and check if the test is displayed on the page.