1

I'm using PHP, Smarty, MySQL, jQuery and AJAX for my website. Now the scenario is as follows: There are three fields present on my form. The code for these three fields from smarty template is as follows:

<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>
<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>
<label>Name</label>
    <div class="form-element">
        <input type="text" class="" name="user_name" id="user_name" value="{$user_name}" />
    </div>

Now from above code I want to make the field named user_name autopopulate. The values to be displayed as auto populated depends on the values selected from the other two select controls from above code. That is I want to pass the values of controls class_id and section_id into the AJAX request to fetch the autopopulate list of Usernames. For this I've written following code but it's not working for me. Can you help me in making the text field named user_name autocomplete enabled? Thanks in advance. My non-workable code is as follows:

{literal}
<script language="javascript" type="text/javascript">
$(function() { 

  $("#user_name").autocomplete({ 
    source: function( request, response ) { 
        $.ajax({ 
          url: "report_student_result.php",
          data: {'request_type':'ajax', 'op':'get_student_names', 'class_id':request.class_id, 'section_id':section_id },
          dataType: "json",
          success: function( data ) {
            response( $.map( data.myData, function( item ) {
              return {
                //How to access the jason response here and assign it in autopopulate?
              }
            }));
          }
        });
      }
  });

});
</script>
{/literal}

The PHP code from the file report_student_result.php is as follows(one of the the switch case):

<?php
    $request     = empty( $_GET ) ? $_POST : $_GET ;
    $op = $request['op'];
    global $gDb; 
     switch($op) {
         case'get_student_names':
         // escape your parameters to prevent sql injection
         $param   = mysql_real_escape_string($_GET['term']);
         $options = array();

         $sql  = " SELECT CONCAT(u.user_first_name, " ", u.user_last_name) as full_name FROM users as u JOIN  users_groups_subscribe as ugs ON u.user_id = ugs.subscribe_user_id WHERE ugs.subscribe_group_id=10 ";
         $this->mDb->Query( $sql);
         $data = $gDb->FetchArray();
         $data = json_encode($data);
         echo $data;
         die;
         break;
    }

?>

I'm also not getting how should I access the json response. After so much googling and all reasearch I've written above code.It may have many mistakes, please help me to make the field autocomplete workable.

Tim Nikischin
  • 368
  • 1
  • 18
PHPLover
  • 1
  • 51
  • 158
  • 311
  • I've had many problems with autocomplete, but over the last few weeks I've made progress and have a good handle on it. The most important thing is you must assure that the presented data are in json format. Run your php by itself, and take the screen dump and put it into http://jsonlint.com/. Then put the autocomplete into the success function. Multicolumn autocompletes are VERY complex if that is your goal. – TimSPQR Sep 27 '13 at 14:41
  • As I see 'ajax.success' function need to call 'response' function with array for autocomplete. Just return something from $.map function from 'item'. And your autcomplete should be working something. This is a similar example http://jqueryui.com/autocomplete/#remote-with-cache – maketest Sep 27 '13 at 14:48
  • I hope you don't use _usernames_ on top of emails here, [which is a bad practice](http://stackoverflow.com/questions/18356407/how-to-merge-user-data-after-login/18443311#18443311) – Dmitri Zaitsev Oct 06 '13 at 11:06

4 Answers4

4

Try this

 $("#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()
                 },
                 success: function(data) {
                     response(
                         $.map(data, function(item) {
                             return {
                                 label: item.full_name,
                                 value: item.full_name
                             }
                         })
                     );
                 }
             });
         },
         select: function(event, ui) {
             if(ui.item) {
                 $(event.target).val(ui.item.value);
             }
             return false;
         }
    });

Here the response from the server should be in the following form

[{"full_name":"Name 1"},{"full_name":"Name 2"},{"full_name":"Name 3"},.......]

Hope that helps!

Gurminder Singh
  • 1,755
  • 16
  • 19
4

You can do this in following manner. I've not tested the code thoroughly. Hope it will work for you.

<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>
0

Always test your PHP directly to make sure that the content you are sending to the client is what you expect. Also, I typically always send an ID along with the data so that I can send the ID back to the server if I want to do something with it. Also, no need to use CONCAT in your query as you can combine them on the client (nothing wrong on what you did, but good to have options).

I personally do not use Smarty templates. What would give you a greater audience of individuals providing answers would be to just show the resulting HTML.

Try the following jQuery script. I don't know what you want to do, and you wight not need the focus event or the blur() and preventDefault() in the select event.

$("#user_name").autocomplete({
    source: 'report_student_result.php?request_type=ajax&op=get_student_names&class_id='+$('#class_id').val()+'&section_id='+$('#section_id').val(),
    minLength: 2,
    focus: function( event, ui ) {event.preventDefault();$(this).val( ui.item.label );},
    select: function(event, ui) {
        $(this).val('').blur();
        event.preventDefault();
        //Access your returned data (in object "ui") however you want.
        console.log(ui);
        //Note that you could have sent multiple values such as ui.item.firstname, ui.item.lastname if you want
        alert(ui.item.full_name);
    }
})
user1032531
  • 24,767
  • 68
  • 217
  • 387
0

I had the same issue with response option of autocomplete widget. I upgraded my Autocomplete widget version from 1.8 to 1.9. Now it's working completely fine. Assuming that your code is correct and your using version lesser then 1.9, I recommend you to switch from 1.8 to 1.9. Hope it Works..

Joke_Sense10
  • 5,341
  • 2
  • 18
  • 22