Custom code: admin-ajax.php 400 (Bad Request)
-
Hey guys,
I want to include a custom code into a page with dynamic selects. I am using code snippets plugin to write PHP. But I am stuck right now with a 400 ajax error when I try to select a value.
Here’s my php code:
add_shortcode('choix_produits', 'wpcode_elementor_shortcode'); function wpcode_elementor_shortcode($atts) { global $wpdb; $admin_url = admin_url( 'admin-ajax.php' ); echo '<form action="$admin_url" method="post" class="" >'; echo '<select name="marques" id="marques">'; $results = $wpdb->get_results("SELECT distinct(marque) FROM wpfir_module_bougies;"); if ($results) { foreach ($results as $row) { echo '<option value="' . esc_attr($row->marque) . '">' . esc_html($row->marque) . '</option>'; } } else { echo '<option value="">Aucune donnée trouvée</option>'; } echo '</select>'; echo '<select name="modeles" id="modeles"><option value="">Sélectionnez un modèle</option></select>'; echo '</form>'; add_action('wp_ajax_get_modeles', 'get_modeles_callback'); add_action('wp_ajax_nopriv_get_modeles', 'get_modeles_callback'); // Ajout du script wp_register_script('script_bougies', content_url() . '/plugins/bougies/script_bougies.js', array('jquery'), '1.0', true); wp_localize_script('script_bougies', 'ajax_object', array('ajax_url' => admin_url('admin-ajax.php'))); wp_enqueue_script('script_bougies'); function get_modeles_callback() { $marque_selected = $_POST['marque']; error_log("marque : ".print_r( $marque_selected, true ) ); $modeles = $wpdb->get_results("SELECT distinct(modele) FROM wpfir_module_bougies where marque=$marque_selected;"); /*if ($results) { foreach ($results as $row) { echo '<option value="' . esc_attr($row->modele) . '">' . esc_html($row->modele) . '</option>'; } } else { echo '<option value="">Aucune donnée trouvée</option>'; }*/ if ($modeles) { $options_html = ''; foreach ($modeles as $modele) { $options_html .= '<option value="' . $modele . '">' . $modele . '</option>'; } }else { echo '<option value="">Aucune donnée trouvée</option>'; } echo $options_html; wp_die(); } }
At first, I placed my jquery inside the elementor page where I imported my short_code, but reading a lot of stuff here and there, I placed it inside the plugin directory:
jQuery(document).ready(function ($) { $('#marques').on('change', function() { var marqueSelected = $(this).val(); $.ajax({ url: ajax_object.ajax_url, type: 'POST', data: { action: 'get_modeles', marque: marqueSelected }, success: function(response) { $('#modeles').html(response); }, error: function(xhr, status, error) { console.error(status + ': ' + error); } }); }); });
Can someone tell me what I am doing wrong? Would be great to get some pointers, developing alone is lonely sometimes ??
Thanks!
The page I need help with: [log in to see the link]
Viewing 6 replies - 1 through 6 (of 6 total)
Viewing 6 replies - 1 through 6 (of 6 total)
- The topic ‘Custom code: admin-ajax.php 400 (Bad Request)’ is closed to new replies.