Why the "jQueryUI autocomplete" is not showing json values received from PHP file in autocomplete enabled input field in following scenario?

StackOverflow https://stackoverflow.com/questions/19138102

Question

I'm using PHP, MySQL, Smarty, jQuery, AJAX, etc. for my website. Now I'm trying to make one input field(having id user_name) autocomplete enabled. I want to give the user suggestions when he starts typing into the input field. I'm passing the value typed in by user as an argument, fetching the suggestions from MySQL database based on the argument recieved, converting the fetched database records into json response and trying to show it as a suggestion to the user. But unfortunately I'm not able to show the suggestions I received in json format to the user as he types in. If I observe in firbug, the request is going properly, the json response is also receiving properly but not getting displayed below the textfield as a suggestion. Also there are no errors found in the firebug console. For your reference I'm putting the code below. The HTML(code from smarty) part:

<html>
<head>
<link rel="stylesheet" type="text/css" href="{$control_css_url}ui-lightness/jquery-ui-1.10.3.custom.css">  
<link rel="stylesheet" type="text/css" href="{$control_css_url}autocomplete.css">
<script src="{$control_js_url}vendor/jquery-1.9.1.min.js"></script>
<script type="text/javascript" src="{$control_js_url}jquery-ui/jquery-ui-1.10.3.custom.min.js"></script>
</head>
<body>
<form id="view-student_result-form" name="view_student_result" action="{$control_url}modules/reports/report_student_result.php" method="post">
  <input type="hidden" name="op" id="op" value="get_student_result" >   
        <div class="w50">              
          <ul>
            <li>
              <label>Class</label>
              <div class="form-element">
                <select name="class_id" id="class_id" onchange="get_section_by_class(this.value, 'get_section_by_class', '#section_id'); return false;">
                  <option value="">-Select Class-</option> 
                  {foreach from=$all_class item=class key=key} 
                  <option value="{$class.group_id}" {if $class_id == $class.group_id} selected="selected"{/if}>{$class.group_name}</option>
                  {/foreach}
                  </select>
                </div>
            </li>
             <li>
              <label>Name</label>
              <div class="form-element" id="friends" class="ui-helper-clearfix">
                <input type="text" class="" name="user_name" id="user_name" value="{$user_name}" />
              </div>
            </li> 
            <li>
              <label>Section</label>
              <div class="form-element">
                <select name="section_id" id="section_id">
                {if empty($section_id)}
                <option value="">-Select Section-</option> 
                {else}
                <option value="all">All</option>
                {/if}
                {foreach from=$all_section_by_class item=section key=key} 
                <option value="{$section.group_id}" {if $section_id==$section.group_id} selected="selected"{/if}>{$section.group_name}</option>
                {/foreach}
                </select>
              </div>
            </li>          
          </ul>
        </div>
      </form>
  </body>
</html>
{literal}
<script language="javascript" type="text/javascript">
$(function() {  
  //attach autocomplete  
  $("#user_name").autocomplete({  

  //define callback to format results  
    source: function(req, add) { 
    var class_id   = $('#class_id').val();
    var section_id = $('#section_id').val(); 

  //pass request to server  
      $.getJSON("report_student_result.php?callback=?&op=get_student_names&class_id="+class_id+"&section_id="+section_id, req, function(data) {  

        //create array for response objects  
        var suggestions = [[]];  

        //process response  
        $.each(data, function(i, val){                                
          suggestions.push(val.name);  
        });  

        //pass array to callback  
        add([suggestions]);  
      });  
    },  

    //define select handler  
    select: function(e, ui) {  

      //create formatted friend  
      var friend = ui.item.value,  
          span = $("<span>").text(friend),  
          a = $("<a>").addClass("remove").attr({  
            href: "javascript:",  
            title: "Remove " + friend  
    }).text("x").appendTo(span);  

    //add friend to friend div  
    span.insertBefore("#user_name");  
  },  

  //define select handler  
  change: function() {  

      //prevent 'user_name' field being updated and correct position  
      $("#user_name").val("").css("top", 2);  
    }  
  }); 
  //add click handler to friends div  
  $("#friends").click(function(){  
    //focus 'user_name' field  
    $("#user_name").focus();  
  });  

  //add live handler for clicks on remove links  
  $('#friends').on("click", ".remove", document.getElementById("friends"), function(){ 
  //$(".remove", document.getElementById("friends")).live("click", function(){                   
    //remove current friend  
    $(this).parent().remove();  

    //correct 'user_name' field position  
    if($("#friends span").length === 0) {  
      $("#user_name").css("top", 0);  
    }                 
  });                      
});
</script>
{/literal}

Now the code from PHP file(one case from the file report_student_result.php):

<?php
global $gDb; 

  $op = $request['op'];
switch($op) {
case'get_student_names':
$param = $_GET["term"];
        $group_id = $request['class_id'];

        if($request['section_id'] !='all')
          $group_id = $request['section_id'];

        if ($group_id != '') {
          $sql  =" SELECT u.user_id, CONCAT(u.user_first_name, ' ', u.user_last_name) as full_name ";
          $sql .=" FROM ".TBL_USERS." as u JOIN ".TBL_USERS_GROUPS_SUBSCRIBE." as ugs ON u.user_id = ";
          $sql .=" ugs.subscribe_user_id WHERE ugs.subscribe_group_id = ".$group_id." AND (u.user_first_name ";
          $sql .=" REGEXP '^$param' OR  u.user_last_name REGEXP '^$param')";
        } else {
          $sql  =" SELECT user_id, CONCAT(user_first_name, ' ', user_last_name) as full_name ";
          $sql .=" FROM ".TBL_USERS." WHERE user_first_name REGEXP '^$param' OR user_last_name ";
          $sql .=" REGEXP '^$param'";    
        }

        $gDb->Query( $sql );
        $data = $gDb->FetchArray(); 

        $response = $_GET["callback"] . "(" . json_encode($data) . ")";
        echo $response;

        die;

  }
?>

If you want anything more information like the json response I'm receiving while user types in the text, I can provide you. The above code is working fine, the only issue is in displaying the suggestions received under the textfield having id user_name. Please help me to resolve this issue. Looking forward to your replies. Thanks in advance.

Was it helpful?

Solution

You can try this out. I think it will definitely solve your issue of displaying the json response values properly.

<script language="javascript" type="text/javascript">
$(function() {
  $( "#user_name" ).autocomplete({
  source: function( request, response ) {
    $.ajax({
      url: "report_student_result.php",
      dataType: "json",
      data: {
        request_type: "ajax",
        op: "get_student_names",
        class_id: $('#class_id').val(),
        section_id: $('#section_id').val(),
        name_startsWith: request.term
      },
      success: function( data ) {
        response(
          $.map(data, function(item) {
            return {
              label: item.full_name,
              value: item.full_name
            }
          })
        );
      }
    });
  },
  minLength: 2,
  select: function( event, ui ) {
    if(ui.item) { 
      $(event.target).val(ui.item.value);
    }
    return false;
  },
  open: function() {
    $( this ).removeClass( "ui-corner-all" ).addClass( "ui-corner-top" );
  },
  close: function() {
    $( this ).removeClass( "ui-corner-top" ).addClass( "ui-corner-all" );
  }
  });
});
</script>

OTHER TIPS

<!--For location search start-->
<link rel="stylesheet" href= "http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
<style>
  .ui-autocomplete-category {
  font-weight: bold;
  padding: .2em .4em;
  margin: .8em 0 .2em;
  line-height: 1.5;
 }
</style>
<script>
$.widget( "custom.catcomplete", $.ui.autocomplete, {
  _renderMenu: function( ul, items ) {
  var that = this,
  currentCategory = "";
  $.each( items, function( index, item ) {
   if ( item.category != currentCategory ) {
     ul.append( "<li class='ui-autocomplete-category'>" + item.category + "</li>" );
     currentCategory = item.category;
     }
   that._renderItemData( ul, item );
   });
}
});
</script>
<script>
$(function() {
var data = [
<?php
  $sql_all_location="SELECT LocationId,LocationName,ParentLocationId FROM wp_location_master WHERE LocationLevel<7";
  $query_all_location=mysql_query($sql_all_location);
  while($fetch_all_location=mysql_fetch_assoc($query_all_location))
   {
   $sql_parent_location="SELECT LocationName FROM wp_location_master WHERE LocationId='".$fetch_all_location['ParentLocationId']."'";
   $query_parent_location=mysql_query($sql_parent_location);
   $fetch_parent_location=mysql_fetch_assoc($query_parent_location);
?>
{ label: "<?php echo $fetch_all_location['LocationName'];?>", category: "<?php echo $fetch_parent_location['LocationName']; ?>" },
<?php
}
?>
];
$("#search").catcomplete({
  delay: 0,
  source: data
});
});
</script>
<!--For location search end-->
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top