HOME / BLOG / BLOG-POST

How to show data by live search from mysql database using ajax?

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');

 


about authors

Sandip Das

Web Developer

Once a legend said “Any fool can write code that a computer can understand. Good programmers write code that humans can understand.” – Martin Fowler.



POST COMMENTS

Leave a Reply

Your email address will not be published. Required fields are marked *