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
Comments
107 discussions around jQuery PHP Ajax Autosuggest
Newer Comments
  1. Pingback: PhoneBook Search – No code required | End User SharePoint

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

  3. Pingback: LimeSpace – IT » Links der Woche im Regen

  4. Pingback: Twitted by nVitou

  5. Rocky says:

    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'];
    }

  6. Jamie Bicknell says:

    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

  7. Pingback: CSS Brigit | jQuery PHP Ajax Autosuggest

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

  9. 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.

  10. Felix says:

    Great!…realy easy way!..thanks

Newer Comments




Never miss an update from Papermashup

Get notified about the latest tutorials and downloads.

Subscribe by Email

Get alerts directly into your inbox after each post and stay updated.
Subscribe
OR

Subscribe by RSS

Add our RSS to your feedreader to get regular updates from us.
Subscribe

Get in contact

Please use the form below to get in contact. If your question is related to a free script download, please use the comments on the article page as community members are more likely to respond quicker than I can personally.

About Me

I'm Ashley Ford, Co-founder and Technical Director at Harkable.com London, UK. Previously I worked at InMobi, Spotify and MySpace. My interests include photography and making short videos I'm also an avid F1 fan. I'm always working on side projects. Here are a few: Easy Poll, We Deliver.



What do you specialise in?

I spend a lot of time coding in PHP and MySQL, as well as front end XHTML and CSS. I also specialise in javascript and the jQuery framework as well as being an avid designer. You can find me on dribbble

Interested in advertising?

If you'd like to advertise on Papermashup.com please get in touch via the contact link below for advertising opportunities.

How do I contact you

You can contact me here. and I'm available for consultation, freelance, programming book reviews.

Get on the mailing list

Join over 3000 people who have subscribed to the Papermashup inbox message, and be the first to find out about tutorial, competitions and giveaways.