php - autocomplete in wordpress using ajax with json-data

The scenario is whenever client press the key, automatically the suggestion should come below the text box, and that sug

The scenario is whenever client press the key, automatically the suggestion should come below the text box, and that suggested value is fetched from the database.

Here i am stucked in a situation where my ajax is running 'error' property properly but unable to go to 'success' property in ajax .

Here is my js:-

jQuery(document).ready(function(){
     jQuery("#field_2").keyup(function(){
     var text = $(this).val();
     if(text === '')
     {
          jQuery("#result").html('');
     }
     else
     {
      jQuery("#result").html('');
      jQuery.ajax({
      url: ajax_object.ajaxurl,
      method:'get',
      data:
      {
          action : 'my_category',
          search :  text
      },
      dataType:'json',
      success:function(data)
      {
          console.log(data);
         jQuery("#result").html(data);

      },
      error:function(xhr)
       {
         alert("Ajax Failed Due To " +xhr.status+ " error.");
       },

         });
       }
   });  
});

and i enqueue this js in theme folder of function.php and it's code is

function my_category_ajax()
{
      wp_register_script('myAjax', get_template_directory_uri().'/js/custom-ajax.js',array('jquery'));
      wp_localize_script( 'myAjax', 'ajax_object', array( 'ajaxurl' =>admin_url( 'admin-ajax.php' ) ) );
      wp_enqueue_script( 'myAjax' );
}
add_action('wp_loaded', 'my_category_ajax');

and finally the function which is fetching the data from database is again kept in function.php of theme folder and it is:-

function category_from_value()
{
    global $wpbp;
    $mySearch = $_GET['search'];
    $result =  $wpbp->get_results(" SELECT *FROM my_table WHERE value LIKE '{$mySearch}%' ");

    if(count($result) > 0 )
    {
    foreach($result as $my_results)
    {
        $my_results = $result->value;
    }
    echo json_encode($my_results);
    }
     die();
}
add_action('wp_ajax_my_category', 'category_from_value');
add_action('wp_ajax_nopriv_my_category', 'category_from_value');

I can't understand where i am going wrong, any valuable comment is highly appreciable. Thanx

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745660854a4638827.html

相关推荐

  • php - autocomplete in wordpress using ajax with json-data

    The scenario is whenever client press the key, automatically the suggestion should come below the text box, and that sug

    22天前
    30

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信