Show data by live search from MySQL database using ajax
//html form
<form method="post">
<h5>
SEARCH FOR USERS
</h5>
<input type="text" id="search" name="search" placeholder="search">
<!-- <input type="submit" name="sechsub" value="Search"> -->
</form>
<div id="result">
</div>
// jquery code
<script>
jQuery(document).ready(function($){
$("#search").keyup(function(){
//alert("srchval");
var srchval = $(this).val();
var datas = {
'action':'search_form',
'srchval':srchval,
}
$.post(myajax.ajaxurl,datas,function(response){
console.log(response);
$("#result").html(response);
});
});
});
</script>
// function.php
function search_form(){
$srchval = $_POST['srchval'];
if(empty($srchval))
{
$srchval = "abesaale";
}
global $wpdb;
$table_name1 = $wpdb->prefix . "test";
$result = $wpdb->get_results ( "SELECT * FROM $table_name1 WHERE username LIKE '%".$srchval."%' " );
foreach ( $result as $print ) {
echo $print->username ."<br>";
}
die();
}
add_action('wp_ajax_nopriv_search_form','search_form');
add_action('wp_ajax_search_form','search_form');