使用jQuery-ui使用php和javascript自动完成文本框

使用jQuery-ui使用php和javascript自动完成文本框

问题描述:

I am trying to autocomplete a text box in my search.php code using autocomplete.php

I know that my php code works perfectly and echo's back exactly what is needed for the autocomplete function in jQuery.

Here is the html for the text box.

<input type="text" name='search' id="search" class="input-block-level" autocomplete="off" placeholder="search...">

Here is my script for the autocomplete function

<script>
  jQuery(document).ready(function($){
    $('#search').autocomplete({source:'autocomplete.php', minLength:2});
  });
</script>

Here is the php file

<?php


 if ( !isset($_GET['term']) )
exit;


$conn = odbc_connect('Abilis', 'infosysreader', 'Wilsons12'); 

$query = "SELECT TOP 10 [Del_ad1] FROM [Abilis].[dbo].[Customers] WHERE Del_ad1 LIKE    '%".$_GET['term']."%'";

$rs = odbc_exec($conn, $query);



$data = array();

for($i = 0; $i<odbc_num_rows($rs);$i++){
$row = odbc_fetch_array($rs, $i);

$data[] = array(
            'label' => $row['Del_ad1'],
            'value' => $row['Del_ad1']
);
}

// jQuery wants JSON data
echo json_encode($data);
flush();

Edit:

I found my error at the end of my html file. It was just a mistake on my part, the method I use above works fine.

Not sure what your problem is but since your PHP correctly returns json encoded string then problem is with autocomplete call. Try this and let me know if it makes any difference:

$('#search').autocomplete({
   minLength:2,
   source: function(request, response) {
       $.ajax({
         url: 'autocomplete.php', 
         dataType: 'json',
         data: { term : request.term },
         success: function(result) {
              response(result);
         }
       });
   }
});

Also try changing autocomplete="off" to autocomplete="on"

Remove the following from input element:

class="input-block-level" autocomplete="off" placeholder="search..."

and try with <input type="text" name='search' id="search" />