Search with jQuery

You can use AJAX through jQuery to search your MySQL database. It's as simple as setting up a php file to handle the search input, creating the input, and a space for the results to be returned. First, you'll need to set up the input box and the return data div.

Search: 
 

Next, you'll create your page with the search box and returned data. You'll need to set up the jQuery to take the data as you type.

$(document).ready(function () {
	$('#name-search').keyup(function(e){
		var pos = $(this).offset();//get position of input for dropdown style of returned data
		switch(e.keyCode) {
			case 38: // up
				e.preventDefault();
				moveSelect(-1);
				break;
			case 40: // down
				e.preventDefault();
				moveSelect(1);
				break;
			case 13: // return
				if(active==-1){ window.location='./?name='+$(this).val(); }//input
				else{ window.location=$("#result a.ac_over").attr('href'); }//goes to hovered selection
				break;
			default:
				active = -1;
		$.ajax({
			url	: "search.php",
			type	: "POST",
			data	: ({
				findthis	: $(this).val()
			}),
			success	: function(ret) { $('#result').css('left',pos.left).css('top',pos.top+20).show().html(ret); }
		});
				break;
		}
	});

	function moveSelect(step) {
		var lis = $("#result a");
		if (!lis) return;
		active += step;
		if (active == -1) {
			lis.removeClass("ac_over");
		} else if (active == -2) {
			active = lis.size()-1;
		} else if (active >= lis.size()) {
			active = -1;
		}
		lis.removeClass("ac_over");
		$(lis[active]).addClass("ac_over");
	};
});

Then you'll need to create the php page to search your MySQL database. You can figure out how to connect to the database in another tutorial.

if (strlen($_POST['findthis']) >= 2) {//search when 2 or more charaters
$namesearch = $_POST['findthis'];

	$sql1 = "SELECT * FROM table WHERE fname LIKE '".$namesearch."%' OR lname LIKE '".$namesearch."%' ORDER BY lname";
	$sql = mysql_query($sql1);

	$i = 0;
	while ($array = mysql_fetch_array($sql)) {
		if ($i%2) { $id = ''; } else { $id = 'class="odd"'; }//add class for css styling
		echo "".$array['fname']." ".$array['lname']."";
		$i++;
	}
}

There's more in the following zip. Inside you'll get all the files you need. Of course you'll need to set up the database yourself.

search.zip

Category: 
Tags: