Use AJAX to modify $wpdb query
-
Hello,
I work on a website where I display a list with a custom database table :
$resultats = $wpdb->get_results( $wpdb->prepare( "SELECT * FROM {$wpdb->prefix}prfs" ) ); foreach ( $resultats as $resultatProfs ) { }
I try to create an AJAX filter with select input. I tried since yesterday but I don’t understand how to make this.
My functions.php :
function blog_scripts() { // Register the script wp_register_script( 'custom-script', get_stylesheet_directory_uri(). '/js/ajax.js', array('jquery'), false, true ); // Localize the script with new data $script_data_array = array( 'ajaxurl' => admin_url( 'admin-ajax.php' ), ); wp_localize_script( 'custom-script', 'blog', $script_data_array ); // Enqueued script with localized data. wp_enqueue_script( 'custom-script' ); } add_action( 'wp_enqueue_scripts', 'blog_scripts' ); add_action('wp_ajax_get_states_by_ajax', 'get_states_by_ajax_callback'); add_action('wp_ajax_nopriv_get_states_by_ajax', 'get_states_by_ajax_callback');
My AJAX :
jQuery(function($) { $('#departement_select').change(function () { var departement = $(this).val(); console.log(departement); if(departement != '') { var data = { 'action': 'get_states_by_ajax', 'departementValue': departement, 'security': blog.security }; $.post(blog.ajaxurl, data, function(response) { $('.load-state').html(departement); }); } }); });
My php page :
<div class="load-state"></div> <?php function get_states_by_ajax_callback() { check_ajax_referer('load_states', 'security'); $departement = $_POST['departementValue']; var_dump($departement); global $wpdb; $aStates = $wpdb->get_results( $wpdb->prepare( "SELECT nom FROM ". $wpdb->prefix ."profs WHERE departement_fr = %d", $departement ) ); if ( $aStates ) { echo('yep'); } else{ echo('nope');} wp_die(); } ?>
Viewing 2 replies - 1 through 2 (of 2 total)
Viewing 2 replies - 1 through 2 (of 2 total)
- The topic ‘Use AJAX to modify $wpdb query’ is closed to new replies.