search form with ajax
-
Hello,
I am trying to develop a search tool for my plugin using ajax. I would like that by filling in the “user” field it returns the ID corresponding to this data (user_login).
Here is my PHP code:$content= "Recherche"; wp_enqueue_script( 'jb_script-js', plugins_url( 'js/jb_script.js', __FILE__ ),array('jquery')); // Pass ajax_url to script.js wp_localize_script( 'jb_script-js', 'plugin_ajax_object', array( 'ajax_url' => admin_url( 'admin-ajax.php' ) ) ); $content.= ' <form id="search-form"> <label for="user_login">Rechercher utilisateur :</label> <input type="text" id="user_login" name="user_login"> <input type="button" value="Rechercher" onclick="searchUser()"> </form> <div id="search-results"></div> '; add_action( 'wp_ajax_search_user', 'search_user' ); add_action( 'wp_ajax_nopriv_search_user', 'search_user' ); function search_user() { global $wpdb; $user_login = $_POST['user_login']; $results = $wpdb->get_results( $wpdb->prepare( "SELECT ID FROM $wpdb->users WHERE user_login = %s", $user_login ) ); echo json_encode($results); wp_die(); }
and here is my javascript code:
function searchUser() { var user_login = jQuery('#user_login').val(); jQuery.ajax({ type: 'POST', url: plugin_ajax_object.ajax_url, data: { 'action': 'search_user', 'user_login': user_login }, success: function(results) { var output = ""; for (var i = 0; i < results.length; i++) { output += "ID utilisateur : " + results[i].ID + "<br>"; } jQuery('#search-results').html(output); } }); }
at the moment it doesn’t work. Where is the error?
Viewing 3 replies - 1 through 3 (of 3 total)
Viewing 3 replies - 1 through 3 (of 3 total)
- The topic ‘search form with ajax’ is closed to new replies.