Use your left/right keys to browse tutorials
jQuery PHP Ajax Autosuggest

jQuery PHP Ajax Autosuggest

1 Star2 Stars3 Stars4 Stars5 Stars
Posted on August 8, 2009

I’ve been working on a lot of JavaScript and PHP projects at work recently which is one of the reasons why I haven’t written a post for the last week. During my many projects i had the need to use an ‘autosuggest’ script that would, in my case, get a list of 10 schools based on the users input in a text field. I thought I’d share this with you as it’s probably easier than you think to do with JavaScript.

Lets run through the JavaScript.

There are two functions in the block of code below. the first one ‘suggest’ performs the ajax request based on the users input into the text field which is passed into the function when the function is run. We reference the input with the variable ‘inputString’.

the first section of code is a simple if statement to check if the length of the users input in the text box is more than 0. If it is we run the ajax request to get the list of suggestions from the database. #country refers to the id of the text input in our form. You can see that we’re adding the class ‘load’ to the text input. This is to display an animated loading gif to show the user that we’re getting data from the database.

We then use ‘$.post’ to post the users input text to the ‘autosuggest.php’ page for processing. The autosuggest.php page simple returns a result based on a LIKE % sql query.

Once we have data back from the ‘autosuggest.php’ file, we fade in the suggestion box and inject the contents into the ‘#suggestionsList’ div using ‘.html’. We finally remove the ‘load’ class which removes the animated loading gif.

The function ‘fill()’ populates the text input field with the users selection if they click in a country from the suggested list, it then fades out the ‘#suggestions’ div removing it from the page.

function suggest(inputString){
		if(inputString.length == 0) {
			$('#suggestions').fadeOut();
		} else {
		$('#country').addClass('load');
			$.post("autosuggest.php", {queryString: ""+inputString+""}, function(data){
				if(data.length >0) {
					$('#suggestions').fadeIn();
					$('#suggestionsList').html(data);
					$('#country').removeClass('load');
				}
			});
		}
	}

	function fill(thisValue) {
		$('#country').val(thisValue);
		setTimeout("$('#suggestions').fadeOut();", 600);
	}

The HTML.

This is the HTML needed to get the autosuggest feature working. Its a simple form, with a text input with an onKeyup and onBlur attribute. The suggestion box with arrow is situated below the form input and positioned absolutely relative to the div suggest.

<form id="form" action="#">
<div id="suggest">Start to type a country:

      <input id="country" onkeyup="suggest(this.value);" size="25" type="text" />
<div id="suggestions" class="suggestionsBox" style="display: none;">
 <img style="position: relative; top: -12px; left: 30px;" src="arrow.png" alt="upArrow" />
<div id="suggestionsList" class="suggestionList"></div>
</div>
</div>
</form>

Included in the download package is the database .sql file needed to create the table to search from. You could however modify the SQL query to point to a different table. The database connection details are also declared at the top of the autosuggest.php page however it is advised to abstract these from the page.

demodownload



More tutorials from Papermashup
  • Pingback: PhoneBook Search – No code required | End User SharePoint

  • Pingback: 30+ 新鲜惊奇的 jQuery 插件与教程

  • Pingback: LimeSpace – IT » Links der Woche im Regen

  • Pingback: Twitted by nVitou

  • http://www.massbase.com Rocky

    To check if there are any rows u need to pass the query to a associtve function IN PHP

    mysql_fetch_assoc();
    mysql_fetch_array();

    $q = “QUERY STRING”;
    $res = mysql_query($q);
    if(mysql_num_rows($res) == 0){
    // No Rows Found
    } else {
    // DISPLAY VALUES
    $row = mysql_fetch_assoc($res);
    echo $row['value'];
    }

    • http://www.papermashup.com Ashley

      @Rocky thanks for that ;)

  • Jamie Bicknell

    My only suggestion is that you turn auto-complete off for the text box, as it currently interferes with the auto suggest drop down.

    Also, I believe being able to select via the arrow keys is an important usability feature.

    Other than that, cracking job, very nice indeed

  • Pingback: CSS Brigit | jQuery PHP Ajax Autosuggest

  • http://www.visualsuspect.nl Visualsuspect

    Very clean and easy!
    Loving your posts! Keep em comming.

  • http://www.mee.la Sufian Hassan

    cool I like it
    why don’t you make an if message were it says no results found when their are no results rather then showing a blank box.

  • Felix

    Great!…realy easy way!..thanks