最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

php - autocomplete in wordpress using ajax with json-data

programmeradmin2浏览0评论

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

发布评论

评论列表(0)

  1. 暂无评论