Ajax Autocomplete – Part 2 – with name and value

In the previous post Ajax Autocomplete – Jquery PHP Mysql Johnny and Tariq asked how to get the id. With some changes we can store the value in a hidden field.

Please refer the previous post before reading this…

HTML

Add a hidden field in the form.

<div id="content">
	<form autocomplete="off">
		<p>
			Course Name <label>:</label>
			<input type="text" name="course" id="course" />
			<input type="button" value="Get Value" />
			<input type="hidden" name="course_val" id="course_val" />
		</p>
		<input type="submit" value="Submit" />
	</form>
</div>

PHP

Pass both the id and course name in the result.

//filename: get_course_list.php
require_once "config.php";
$q = strtolower($_GET["q"]);
if (!$q) return;

$sql = "select DISTINCT course_name as course_name, course_id from course where course_name LIKE '%$q%'";
$rsd = mysql_query($sql);
while($rs = mysql_fetch_array($rsd)) {
	$cid = $rs['course_id'];
	$cname = $rs['course_name'];
	echo "$cname|$cid\n";
}

Javascript

Set the value in the hidden field after the selection. Here set the mustMatch option to true if you want to get only existing course name.

<script type="text/javascript" src="../lib/jquery.js"></script>
<script type='text/javascript' src='../jquery.autocomplete.js'></script>
<link rel="stylesheet" type="text/css" href="../jquery.autocomplete.css" />

<script type="text/javascript">
$().ready(function() {

	$("#course").autocomplete("get_course_list.php", {
		width: 260,
		matchContains: true,
		mustMatch: true,
		selectFirst: false
	});

	$("#course").result(function(event, data, formatted) {
		$("#course_val").val(data[1]);
	});
});
</script>

Demo & Download

DEMO Here
Download Source
Cheers!

Advertisements
This entry was posted in Ajax, Jquery, PHP, Tutorial and tagged , , , , , . Bookmark the permalink.

106 Responses to Ajax Autocomplete – Part 2 – with name and value

  1. ivan says:

    when I try to type: …applied bla bla bla …. I found that the textbox can not retrieve the value from the database, is there a solution ? thanks

  2. ivan says:

    what if I want to display data fetched from the “id” as in the AutoComplete bassistance.de we can show with id = result, can you help me ?

  3. Johnny says:

    Thank you very much for taking the time in answering this…..

    How would one NOW clear the hidden value if the value changes or does not match ?

    I tried this however the hideen filed keeps getting reset:

    $().ready(function() {
    $(“#course”).autocomplete(“get_course_list.php”, {
    width: 260,
    matchContains: false,
    //mustMatch: true,
    //minChars: 0,
    //multiple: true,
    //highlight: true,
    //multipleSeparator: “,”,
    selectFirst: false,
    autofill:true
    });

    $(“#course”).blur(function() {
    $(this).search(function(result) {
    if (!result) {
    $(“#course_val”).val(”); // no match found, do something, eg. clearing other fields
    }
    });
    });

    $(“#course”).result(function(event, data, formatted) {
    if (data)
    $(“#course_val”).val(data[1]);

    });
    });

  4. dada says:

    merci pour cette exemple

  5. denny says:

    i have many record from database, but it just display 10 record.. i can’t solve dis.. thx 🙂

  6. bozape says:

    Hi!
    This is a really great script.
    I am using in a text field named “nombre” and it is working perfect, but…
    I have my own keyboard made it on screen with pictures, so if the user has a touch screen monitor he can type into the “nombre” textbox with just clicking on the image letter. The problem is that if I use that way the script don’t work because of course I doesn’t have the focus in the “nombre” textbox.
    Is there a way to activate the autocomplete when I have an “onchange” or change the “value” of the “nombre” textbox?
    Thanks!

  7. Christian says:

    Thank you for this excellent script!
    I have one question, what should I change to search and display in the input text field, also the “course_id” and “course_name”

  8. will says:

    Hi, I Can I dynamically change the form attribute action? For example: After I type “fa” and choose “Fashion”, I would like put “207” (id of fashion) into form action attribute. Then after sumbit go to url “/207.html” Thank you

    • beski says:

      Yes, you can.

      First add an id to the form

      form autocomplete="off" id="myForm" action=""

      then add some lines in the javascript

      $("#course").result(function(event, data, formatted) {
      courseId = data[1];
      $("#course_val").val(courseId);
      $("#myForm").attr('action', courseId+'.html');
      });

      Thanks.

      • Billie Bell says:

        this does now work;

        $(“#autocomplete”).result(function(event, data, formatted) {
        courseId = data[1];
        $(“#course_val”).val(courseId);
        $(“#searchbar”).attr(‘action’, ‘index.php?page=profile&id=’+courseId);
        });

        It will display correctly, but will not redirect when clicked. All CSS ID’s are correct, and I don’t see a problem with the code. Help?

      • Billie Bell says:

        data[1] returns undefined when something is selected?

      • HI Beski

        Thanks for this tutorial, but i have question, how to pass value that is captured on autocomplete + other user input to other php file. for example i have the html file as below :
        The probem is, i have successfully shown and choosen autocomplete list, but when i click button that go to inserttodb.php, parameter prelated is not shown.

        ===HTML File : AddProduct.html====

        ….
        Related Product

        $(document).ready(function(){
        $(“#myAutocomplete”).autocomplete({
        source:’datapopulation.php’,
        multiselect: true,
        minLength:2,
        matchContains: true,
        mustMatch: true,
        selectFirst: false
        });

        $(“#myAutocomplete”).result(function(event, data, formatted) {
        $(“#prelated”).val(data[1]);
        });
        });

        ==========================

        ====here my inserttodb.php line ====
        <?php
        $xpath=$_REQUEST["path"];
        $product_name=$_REQUEST["product_name"];
        $product_desc=trim($_REQUEST["product_desc"]);
        $product_attr=urldecode($_REQUEST["product_attr"]);
        $model=$_REQUEST["model"];
        $price=$_REQUEST["price"];
        $width=$_REQUEST["width"];
        $height=$_REQUEST["height"];
        $order_no=$_REQUEST["order_no"];
        $relatedproduct=$_REQUEST["prelated"];
        $relatedproduct=serialize($relatedproduct);
        ….
        echo "”;
        echo “B $relatedproduct”;
        echo “C $prelated”;
        ========================================

        thanks

  9. hameeda says:

    i want to search by company name and product options when i am select option enter text in textbox query exucution compare company option also how to get option in get_course_list.php

  10. Terry says:

    First off, allow me to say that I learned about your tutorials & samples from the Jquery UI forum and I am most impressed with everything that you have going on here at your website. Thank you for your hard work.

    I am working with a database where the name is ‘Industry’ and the value is ‘123456’ (SIC Code).

    Because of where I get my data, I may have 6 different codes for, let’s say, Restaurants.

    I get how to query and sort, but what I would really like to do is to display both the name and value in two different columns, but still allow the user to type in Restau… (etc) to find Restaurants.

    Thank you again

    • beski says:

      In get_course_list.php you can add any word/value with the variable $cname.
      You can add the id in front of the text like $cname = $rs[‘course_id’]. ” – “. $rs[‘course_name’];

  11. Terry says:

    The code that I am using is:

    And I get the error code:
    Warning: mysql_fetch_array(): supplied argument is not a valid MySQL result resource in get_course_list2.php on line 8

    Did I do something wrong ?
    Any help would be greatly appreciated.

  12. Terry says:

    require_once “config.php”;
    $q = strtolower($_GET[“q”]);
    if (!$q) return;

    $sql = “SELECT combined_sic,sic_code FROM smf_sictable WHERE combined_sic LIKE ‘%$q%'”;
    Sorry, this is the code:

    $rsd = mysql_query($sql);
    while($rs = mysql_fetch_array($rsd)) {
    $cid = $rs[‘sic_code’];
    $cname = $rs[‘combined_sic’];
    echo “$cname|$cid\n”;
    }

  13. Marcus says:

    Good Day,
    How do I search either by course_id or by course_name in the input text field?

    I tried with the following but no luck:

    $sql = “select DISTINCT course_name as course_name, course_id from course where course_name LIKE ‘%$q%'”;
    $rsd = mysql_query($sql);
    while($rs = mysql_fetch_array($rsd)) {
    $cid = $rs[‘course_id’];
    $cname = $rs[‘course_id’]. ” – “. $rs[‘course_name’];
    echo “$cname|$cid\n”;
    }

    What else should I change? An help will be very appreciated. Thank you.

    • beski says:

      Hi Marcus,
      change the query like this:
      $sql = “select DISTINCT course_name as course_name, course_id from course where course_name LIKE ‘%$q%’ OR course_id LIKE ‘%$q%’”;
      This will work.

  14. narobe says:

    Hi, first of all thanks, the code works great for me, what I’m trying out is to add an image to its correspondent column and it works just as you see the code below, the problem is when one of the options listed is selecten the also show up in the input box, any ideas how to hide or filter the tags.

    while($rs = mysql_fetch_array($rsd)) {

    $cname = $rs[“row1”];

    $name = $rs[“row2”];

    echo “$cname \n”;
    echo “$name \n “;

  15. vmarket says:

    I am using mysql_query(“SET NAMES utf8”); in the get_course_list.php in a database with English and Greek characters.
    When I type greek characters in the field, nothing happens. With English the auto complete works fine.
    The test.php file begins with the next lines:

    Any ideas ?

    • vmarket says:

      I tried setlocale, mb_detect_encoding and other functions in php trying to deal with the encoding. When I was pressing English chars it was ASCII (!!!!! with meta … utf-8 !!!!!!). When I was pressing greek chars it was utf-8 but when the script that queried the database was receiving them (either GET or POST method) they were like funny question marks.
      *** SOLUTION *** Removed the strtolower function and after that had no problem with either greek or english characters.

      Thanks a lot Beschi

  16. My script generates multiple fields autocomplete fields, but need to show additional values, for the dynamic fields back to call the script, but the fields are duplicated. I need help please.

    Example:
    div1 = is OK!
    div2 = is Wrong!

  17. Example:

    div1 = Is OK
    div2 = Is Wrong

  18. Dean Oakes says:

    This is a real great example

    and I have a problem here…. It only displays the first value in the dropdown list.

    when I do

    $val1=$rs[0];
    $val2=$rs[1];

    echo “$val1|val2\n”;

    it shows only $val1

    when i do

    echo “$val2|val1\n”;

    it shows only $val2;

    do you have any idea what the problem could be?

    • Beschi says:

      Thanks for your comment.

      Thanks for the comment.

      Try anyone:
      1. Remove strtolower:
      $q = $_GET[“q”];

      OR

      2. Use trim:
      $val1=trim($rs[0]);
      $val2=trim($rs[1]);

      Tell me the result.

    • Dean Oakes says:

      ok… I found the problem and solved

      Instead of using | , I changed it to the :
      It works perfectly now

      Thank you

  19. Alex says:

    Your script is very nice, but i have no idea to make it work perfect like this
    http://www.auto-suggest.com/ext-demo-standard/std_green.html

    I have bought it, but it´s very stupid, they stoped to sell product and will refund money for me. :((

  20. Thomas Bjerre says:

    Hi! Great script! Is there somehow i can pass another value into my get_course_list.php? I need to pass and ID from the first hidden input to my second search, because i need to (WHERE ‘name’ like %q% AND id = ‘$id’) Thank you so much saved me a ton of time

  21. Danny says:

    Hi … In this example (file: test2.php) I receive always error:
    Object doesn’t support this property ot method
    at this row
    $(“#course”).result(function(event, data, formatted) {
    Can you help me ?

  22. Danny says:

    I solved the problem … I download a new version of jquery.autocomplete.js file

  23. TonyP says:

    Hi,
    THE best script for auto fill, thanks.
    I have two quick questions,
    1, Is there anyway to submit form by selecting the item in the dropdown, or at least loosing the first button?

    2, I am passing a page name to the form, can I use the as the target on submit?

    Thanks again
    Tony

  24. aarondas says:

    Hello,

    I was wondering, how can I have the input field fill in for both the course name and the instructors name, so in the input field we would have

    coursename

    coursename

    coursename

    instructors naem

    instructors naem

    instructors naem

    Thanks,

    Aaron

  25. Dimitris says:

    Hi, I used your script and all info – really great !
    I have a small problem :
    I have a text field “name” and a hidden field “id” and autocomplete works great while typing and selecting in “name” – field “id” gets the right value.
    But, the problem is if I select a name (and id gets a value), if I delete the name then value of id remains. I tried to add an onChange method for “name” field so that to check when it’s empty to also empty the “id” value but did not work.
    like :
    function func1 {
    if (document.getElementById(‘name’).value == ”) {
    document.getElementById(‘id’) = ”;
    }
    }
    and for “name” field :

    But does not work.
    Any ideas ?
    Thank you in advance

    • Beschi says:

      Try…

      document.getElementById(‘id’).value = ”;

      or in Jquery way
      $(‘#id’).attr(‘value’, ”);
      or
      $(‘#id’).val(”);

      dont use id, name and the built in attribute names as values…

      Thanks.

  26. Mike says:

    Hi beski

    Very good work 🙂

    It’s possible to have two fields and use Autocomplete in one field and get two result, I mean, for example, in the first field type ‘Hom’, get Homer in the first field and automatically pass simpson in the secound field…

    Do you think that is possible?

  27. mikesanchezph says:

    Hey beski,

    Fairly new with web dev. What should I change so that it only passes the ID when I click on Submit? The names in my database are real long and I don’t need them to be passed and displayed on the address bar. Just the ID would do.

    Thanks,

    • mikesanchezph says:

      Also, beski. I am going to use two input forms in one page (one for Origin and one for Destination) How do I update the script so both will have different variables for each.

      Thanks,

      • mikesanchezph says:

        Currently what I did was to remove the input name for course and gave the 2nd form input id’s of course2 and course_val2. In the javascript part, I copied and pasted the whole code and changed the second ones to #course2 and #course_val2.

        I know there’s a better way of doing this. Anyone willing to help a newbie?

  28. Hello Beski!
    Great Job! Well, i have a problem, when i submit my form using “multiple: true”, the additional hidden input post only one result! Anybody can help me?

  29. Steve Ball says:

    After weeks of searching I stumbled across this and finally it gave me the answers to passing an id that I was looking for!

    However, I do have one question. Is it possible to have 2 fields display in the input box?

    For example, if a database stores first names and surnames in different fields, you would want to see both in the autocomplete to make sure you were making the correct selection before passing the id to any scripts.
    Also, there may be occasions when you want to allow someone to search both first names or surnames but there may be times that you just want it to search the surnames but show both surnames and first names in the list.

    Is any of this possible?

    Thanks for an excellent tutorial.
    Steve

  30. Gaurav Shah says:

    Hi,
    Great tutorial and found very easy and useful for my website. I have trouble solving following:
    1) How to clear cache? in my form i have two field and second field have narrowed result based on first selection. When i go to second field, it still shows old result. when i refresh page, then it works perfect.
    2) how to make selection using keyboard and update hidden field. When i tried making selection using key board,it doesn’t update hidden field.
    3) once user make selection, i want to make field background to be green

    Your feedback will be appreicated.

    • Beschi says:

      Hi Gaurav,
      here some quick answers…
      1) Refer the options here: http://docs.jquery.com/Plugins/Autocomplete/autocomplete (options tab) – Set cacheLength to 1
      2) I tried selecting by keyboard, it works, let me know the browser you are using.
      3) in result function you can add like $(this).css(‘background’, ‘green’)…

      Thanks.

      • Gaurav Shah says:

        Hi Beschi,

        Thanks for prompt reply. Tonight i tried various ways to flush cache including your suggestion flushCache, but none of them are working except unbind. When i use as follow it works, but this solution causes items to be skipped over on down key. I am using Mozilla firefox 6.0.2 & also tested on IE 9, but down key or tab key doesnt make selection.

        $(“#DeliveryDestinationName”+thisKey).unbind(‘.autocomplete’).autocomplete(“getDeliveryDestinationList.php?subDealerNo=”+$(“#SubDealerNo”+thisKey).val(), {
        width: 265,
        matchContains: true,
        selectFirst: true,
        cacheLength: 1,
        autoFill: true
        });

  31. Justin Buchanan says:

    Hello,

    I’m sure this is a very amateur question.. But what should be in the config.php file? I did not see one included with the source.

    I’m guessing I need to declare certain variables to setup my database connection?

    Thank you!

  32. Jason says:

    Hello,

    Great script!!, having a little trouble and hope you can help.
    I select data from a list of addresses in my database, if the user enters for example a postcode or an address not in my database. I want to call another script I have that does address postcode lookups via a pay per click website. I have the following issues.

    1.) When you enter a postcode that is not in the DB then press return key, from automatically submits back to the same page (have set mustMatch: false)
    1a.) Need to stop if submitting back to itself
    1b.) Call my function only when no auto complete selection was made and return key was pressed.

    2.) is there a way to blur focus away from current field once a selection from dropdown is made?

    3.) How do I use this script with two address fields and two hidden fields.
    i.e. From_Address, From_Address_ID and To_Address, To_Address_ID
    Thanks in advance

    • Jason says:

      Hi,
      Sorry scratch point 3 above, I was being a bit slow this morning.
      Still can’t remove focus from field tried all types of blur $(‘#course’).blur(); this.blue(); etc with no joy.
      Also still cant stop return submitting form while field is in focus 🙂
      Thanks again

  33. Jason says:

    Hi,
    Got everything above working in the end, had to select focus on a different element on page though. would not let me blur the elements with the autocomplete. (non autocomplete form objects blur just fine)
    Thanks

  34. Milan says:

    Hi,
    How to make this script Unicode (utf-8).
    I do not use only English text in DB.
    Thanks.

  35. Aaron says:

    Great script. However, whenever I try this I cannot select some of the values. For example, when I type in “a” I get a bunch of courses such as applied tech, etc. However I cannot select anything until about the 3rd choice down. If I try to choose some of the “bad” courses, it just blanks out the input box. Any ideas whats doing this? Tested this with IE and Firefox.

    Great script anyways.

  36. Prabhas says:

    i love you buddy!.
    got result within 2 minutes.
    i was trying it for more than 2 days.
    thank you buddy

  37. Great script
    However i’ve a problem.
    i must search 2 value on my db, name e surname.
    how i can find it?
    test.php

    Paziente:

    get_course.php

    $query=” select Campo24,Campo25,Campo27,Campo28 from fass where Campo24 LIKE ‘”.$q.”%’ “;

    $cname = $data->Campo24. ” – “. $data->Campo25.” – “.$data->Campo27.” – “.$data->Campo28;
    $cid = $data->Campo2;
    echo “$cname\n”;

  38. zia says:

    how to make the suggestion clickable…i used anchor part in mysql query so that i m getting the
    course name as test
    in suggestion dropdown it shows nicely with hyperlink… but when i click it nothing happens. Infact when i do right click open new window site opens…
    I want it to be clicked if particular suggestion is having anchor tag to it…
    please help me out…
    thanks

  39. Anthony says:

    Thanks for the script.

    The only problem I encounter is the first two values “Applied Computing and Information Technology” and “Applied Linguistics”, when selecting those, it does not keep the values in the text field or the hidden field (which I had converted to text to ensure the ID was being placed there). All other entries in the DB fill in the fields.

    Any ideas?

  40. Claudio Triviño S. says:

    Hola :
    he modificado unas lineas de codigo para dirigirse a un link , haciendo click sobre una opcion del menu desplegable, pasando tambien la variable url
    $().ready(function() {

    $(“input#course”).autocomplete(“get_course_list2.php”, {
    width: 260,
    matchContains: true,
    mustMatch: true,
    //minChars: 0,
    //multiple: true,
    //highlight: false,
    //multipleSeparator: “,”,
    selectFirst: false
    });

    $(“#course”).result(function(event, data, formatted) {

    if (data)
    location.href=’pagina.php?id=’+data[1];

    });
    });

    Muchas Gracias por tu excelente aporte !! me ha sido muy útil
    Saludos desde Chile

  41. lefty says:

    hello sir, how to make the suggestion show the existing results….
    example if the max = 10 and the result is 15 or more than… the user will be able to scroll down the other existing results until the end of the suggestion.
    Thanks in advance…

  42. lefty says:

    thank you for suggestions…

    • lefty says:

      hello sir,

      its working well right now thanks a lot…
      your great!!!

      but i need to implement a combobox to allow the users,
      select an option to be search….
      Can you help me to work it out?.

      here is the code:
      HTML

      Course Name :

      Course
      Description

      PHP

      require_once “config.php”;
      $filters = $_GET[‘filters’];
      $q = strtolower($_GET[“q”]);
      if (!$q) return;

      if($filters == $_GET[‘value1’]){
      $sql = “select DISTINCT course_name as course_name, course_id from course where course_name LIKE ‘%$q%'”;

      $rsd = mysql_query($sql);
      while($rs = mysql_fetch_array($rsd)) {
      $cid = $rs[‘course_id’];
      $cname = $rs[‘course_name’];
      echo “$cname|$cid\n”;
      }

      }else if($filters == $_GET[‘value2’]){
      $sql = “select DISTINCT course_description as course_description, course_id from course where course_description LIKE ‘%$q%'”;

      $rsd = mysql_query($sql);
      while($rs = mysql_fetch_array($rsd)) {
      $cid = $rs[‘course_id’];
      $cdesc = $rs[‘course_description’];
      echo “$cdesc|$cid\n”;
      }
      }

      in this code when i select the value1 in the combobox, it works perfectly and show the
      data from the course_name field of the database course in the suggestions….
      but when i select value2 of the combobox, still the data from the course_name field of the database course in the suggestions….
      How can i get the data from the course_description field when i select the value2 in the combobox??? is there something wrong in my code….
      Please help me to work it out….i really really need this.
      Thanks much in advance…

      • Beschi says:

        Hi,

        I can’t see the complete code in your comment. But, I can give a hint. You need to send the combobox value along with the ajax request. (use extraParams)

        $(“#course”).autocomplete(“get_course_list.php”, { width: 260, selectFirst: true, extraParams: {course_option: function(){ return $(‘#combo_id’).attr(‘value’); }} });

        This will send extra parameter “course_option” – the selected value in the combo box.

        In PHP check the “course_option” value like, if ($_GET[‘course_option’] = ‘something) { // do this }

  43. mirzatash13 says:

    Hi Beschi,
    So I’m trying to filter the auto complete results by adding certain criteria – there are some check boxes the user can check to narrow down the results. After the user makes his choices and clicks on the field to start typing – I am calling a JavaScript function to send the information regarding the choices he made and post the values to a file similar to get_course_list.php. Those information are correctly being obtained by my variables when the first time the .php file is called. However as soon as the user types anything it goes away and that’s a problem because my queries depend on the results of the check boxes. Anything beyond this line gets erased –>

    $q = strtolower($_GET[“q”]);
    if (!$q) return;

    Please any help would be appreciated. Thanks in advance!

    • Beschi says:

      Hi,
      You need to send the checkboxes value along with the ajax request.
      The previous comment is similar like this, in some way send the other values like,
      $(“#course”).autocomplete(“get_course_list.php”, {
      width: 260,
      selectFirst: true,
      extraParams: {course_option: function(){ return $(‘#combo_id’).attr(‘value’); }}
      });

      Instead of “$(‘#combo_id’).attr(‘value’)” get the checkboxes value and send
      in PHP GET the checkbox value and process it.

      • mirzatash13 says:

        Hi Beschi,
        Thanks a lot for your reply. Passing values by using the extraParams did the trick! I would like to mention to you one other observation and maybe you can indicate why that is happening—>
        Say for example I have 2 check-boxes under the search bar (ALL and ACTIVE). Checking ALL should refer to a query that selects * from db and checking ACTIVE should only return results of person where active= true. Say the searched person’s name is ‘nonactive’. Say now I select ALL and type in ‘n’ or t’ or ‘a’ then everyone’s name in the list including nonactive shows up. Then without refreshing the page I select ACTIVE and type in ‘c’ or ‘i’ then everyone’s name containing those letters show up except for the person ‘nonactive’. This is good! However, if I erase the letters and type ‘n’ or ‘t’ or ‘a’ then I again see the person ‘nonactive’ in the list like the way I saw it when ALL was selected. However ALL is not selected anymore ACTIVE is selected, but then why is his name showing up? Observation was typing other letters refreshes the checked selections, but when retyping the same letter, the checked boxes behaves as though they were not changed. Can you tell me why? Thanks in advance.

        Tash.

  44. lefty says:

    Thanks much in your suggestions sir.
    i will try and i will tell the outcome…

    • mirzatash13 says:

      Hi Lefty,
      The above suggestion worked for me. Let me know if you need any help with passing parameters.

      Tash

      • Beschi says:

        Hi Tash,

        There is a parameter cacheLength – which stores the results in cache. The default value is 10. So it stores last 10 results in cache to reduce the server hit.
        In this case if you type the same word again, it will not send an ajax request. It will get the previous result from the cache. So you are getting old results even after changing the checkboxes value.

        So set cacheLength: 0 in the options. You will get latest results. (no results will be stored in the cache, ajax request will be sent for every letter typed in the text box)

        – Beschi.

      • lefty says:

        Hi tash,

        thanks tash, its work perfectly for me too…

  45. lefty says:

    hello sir,

    thank you so much for your reply and time to help us…
    Passing values using extraParams did the trick! and work
    perfectly right now…your great sir!!!

    but i need also to implement a “did you mean” function in my
    search engine project. And i found your tutorial
    PHP – similar did you mean script – Part 1 i’m trying to download the
    source script but its not working…can you send me the script in my e-mail account
    here’s my email lefty_man@ymail.com

    Thank you sir in advance…

  46. mirzatash13 says:

    Beschi,
    You have been an amazing source of help. Thank you for implementing this script and helping us understand it better. There is a lot to learn from you. Thank you again!

    Tash

  47. Martyn Bell says:

    Just came across this great piece of code – I got it all working in demo mode on my server but just neede to know how to send the result of the drop down list to another php program

    course_result.php?”value from drop downlist”

    Martyn

    • Beschi says:

      Hi,

      After selecting one value in the dropdown, the id will be stored in a hidden value. By submitting the form, we can get the values in targeted page.

      -Beschi.

  48. Lynn says:

    This is exactly what I was looking for…

    I am working on a database to hold addresses and if the address isn’t found then the user would continue to fill out the boxes and have a “add” button appear. How could i do this using your script.

    Thanks.

  49. Chris says:

    First of all thank you all for this helpful thread !
    I am trying to create a form with a number ($k) of textboxes (the number is dynamically determined by a previous POST from another form), and i need to use the autocomplete function to pass a name and an id (like in test2.php from https://docs.google.com/open?id=0BzB2od8c0umkZGE2ZDA2MzctMjA3Mi00YmJlLWExNTMtMzY5OGVhNDAxNzlh) for every textbox in my form.
    My idea was to use “class=” for my inputs, instead of “id=”, and it’s ok for the name, but my issue is related to the id of the names. When I submit the form, all my ids are equal to the last one and I can not see what am i doing wrong.
    Example:
    My table looks like this:
    Name ID
    Chris 1
    Bill 2
    John 3
    If I use two textboxes with autocomplete in my form named name1 and name2 (together with two hidden id1 and id2) and I select Chris in the first one and John in the second, click Submit, then I get name1=”Chris”, name2=”John”, id1=3 and id2=3.

    My code:

    $().ready(function() {
    $(“.nameauto”).autocomplete(“get_names.php”, {
    width: 260,
    matchContains: true,
    mustMatch: false,
    selectFirst: false
    });
    $(“.nameauto”).result(function(event, data, formatted) {
    $(“.nameauto_id”).val(data[1]);
    });

    });

    ……………………
    for ($i=0;$i<$k;$i++)
    {
    echo '’;
    echo ”;
    }

    My get_names.php file:

    require_once “config.php”;
    $q = strtolower($_GET[“q”]);
    $cname_id=0;
    if (!$q)
    {
    echo ‘””|0\n’;
    return;
    }

    $sql = “select DISTINCT name,id from names_table where name LIKE ‘%$q%'”;
    $rsd = mysql_query($sql);
    while($rs = mysql_fetch_array($rsd)) {
    $cname = $rs[‘name’];
    $cname_id = $rs[‘id’];
    echo “$cname|$cname_id\n”;
    }

    Can you help me with a solution to have my ids submitted correctly (name1=”Chris”, name2=”John”, id1=1, id2=3)?
    Thank you.

    • Chris says:

      Correction: those two echo-s under the “for” loop are like this (this time I stripped characters “greater than” and “lower than”, it seems they are not posted well on this page):
      input type=text name=name’.$i.’ class=”nameauto”
      input type=hidden name=name_id’.$i.’ class=”nameauto_id”

  50. Gustavo says:

    i am creating the text boxes dynamically, but the autocomplete just work on the first one, can you help me?

    thank you

  51. Jamie says:

    Hi Beshi, nice script thanks.
    have a question mind, am trying to filter the suggestion via session id, so that only suggestions are provided that the user has entered.
    yet when I add:

    $colname_user = “-1”;
    if (isset($_SESSION[‘UserID’])) {
    $colname_user = $_SESSION[‘UserID’];
    }

    $sql = “select DISTINCT CName as CName from ccn where CName LIKE ‘%$q%’ WHERE userid = ‘.$colname_user.'”;

    I get no results…..
    Any chance of a solution please?
    Thanks in advance

  52. Bub says:

    Beshi,

    Is there a way you can clear the value out of that hidden field when a result is not found?

  53. Kim Torvanger says:

    Ive been looking for an answer to a question I have for a long time but cannot figure it out from looking at the code or searching Google.

    Is it possible to have the value from the result printed like this in the URL field?:
    http://www.example.com/thevalue

    Thank you!

  54. faizan says:

    what should i have to do if i want onselect event

  55. planner says:

    Hi – really great script thank you very much. However, I have noticed an error that occurs if you click into the form field, and type nothing (or select no records) and then click back to the web page….

    Webpage error details

    User Agent: Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; WOW64; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; InfoPath.3; .NET4.0C; .NET4.0E)
    Timestamp: Mon, 5 Aug 2013 12:32:27 UTC

    Message: ‘1’ is null or not an object
    Line: 25
    Char: 3
    Code: 0
    URI: http://www.mix26.com/demo/ajax-autocomplete/test2.php

    Any idea how to fix please?
    Thanks.

  56. david says:

    how to make the suggestion clickable…i used anchor part in mysql query so that i m getting the
    course name as test
    in suggestion dropdown it shows nicely with hyperlink… but when i click it nothing happens. Infact when i do right click open new window site opens…
    I want it to be clicked if particular suggestion is having anchor tag to it…
    please help me out…
    thanks

  57. david says:

    i’ve done it already, but now i need when i press keydown and focus on result. after that on keypress Return i want to it click on result (redirect me to results link) instead of submitting form or doing nohting.
    thanks

  58. Apostolos Panagos says:

    Beshi.
    First of all congratulations on this amazing article. It really helped me a lot.
    I do have one question though.
    While all seems to be working great using latin characters, the problem arises when you want to call upon greek characters. Eventhough the mysql table is in unicode general ci, the php is utf-8 and all goes well (f.e. inserting data in mysql, requesting and printing data from mysql to php) the autocomplete text field doesn’t work with greek charactes.
    Is there anything you can tell me to overcome this silly problem????

  59. I got this website from my pal who told me concerning this website and now this time I am browsing this web page and
    reading very informative articles or reviews at this place.

  60. ANN says:

    THANK YOU!!

  61. Assylkhan says:

    How can we search two columns together, for ex: name and surname, in customer list?

    • Beschi says:

      we need to change the sql query accordingly.
      $sql = “select DISTINCT first_name, last_name from table_name where first_name LIKE ‘%$q%’ OR last_name LIKE ‘%$q%'”;

  62. Marky says:

    Hi Beschi! Thanks for the autocomplete code.. Got an issue.. why it only works in localhost but when I tried it in live site its not workin ? help please..

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s