jQuery: AJAX autocomplete for e-commerce products

jQuery: AJAX autocomplete for e-commerce products

An AJAX autocomplete feature implemented in jQuery that allows users to see the product's details by entering their code.

A couple of days ago I found an interesting feature on an e-commerce site: by pasting or typing the product's code into a text field you could see instantly the name of the product and its price. Interesting. Let's build our implementation of this feature.

AJAX?

Yes, this feature requires AJAX. What we need is basically:

  1. a server-side script that processes the request and returns a JSON object containing the product's name and its price
  2. a jQuery script that listens to the keyup and paste events and sends the AJAX request by using the field's value as the sole parameter.

The server-side script

Our script (written in PHP ) performs the following actions:

  1. validates the GET parameter of the AJAX request
  2. runs a query against the database
  3. outputs the results as a JSON object.

<?php
require_once( 'DB.php' );
$db = new DB( 'host', 'username', 'password', 'database' );

if( isset( $_GET['code'] ) ) {
$taintedCode = $_GET['code'];

header( 'Content-Type: application/json' );

if( preg_match( '/^\d{4}$/', $taintedCode ) && strlen( $taintedCode ) == 4 ) {
	$rawIntCode = intval( $taintedCode );
	$strCode = '';
	if( filter_var( $rawIntCode, FILTER_VALIDATE_INT ) ) {
		$strCode = $rawIntCode;
		$query = "SELECT product_name, product_price FROM products WHERE product_code = '$strCode'";
		$results = $db->getResults( $query );
		$output = array();
		
		foreach( $results as $result ) {
			$output['name'] = $result['product_name'];
			$output['price'] = $result['product_price'];
		}
		
		echo json_encode( $output );
	}
}
}

The jQuery code

For the sake of the example, I've inserted within the page the complete list of the available product's codes. jQuery will simply bind a listener to the keyup and paste events and compare the value of the text field with the available codes.

If a user inserts an available code, jQuery will perform an AJAX request and insert the results into the current form.


(function( $ ) {
	$.AutoProducts = function( element ) {
		this.$element = $( element );
		this.init();
	}
	
	$.AutoProducts.prototype = {
		init: function() {
			this.$code = this.$element.find( "#code" );
			this.$name = this.$element.find( "#name" );
			this.$price = this.$element.find( "#price" );
			this.$codeList = this.$element.find( "#codes" );
			this.codes = [];
			
			this.getCodes();
			this.handleInput();
		},
		_getData: function( value ) {
			var self = this;
			$.getJSON( "ajax.php", { code: value }, function( data ) {
				var name = data.name;
				var price = data.price;
				if( typeof name !== "undefined" && typeof price !== "undefined" ) {	
					self.$name.html( "<strong>" + name + "</strong>" );
					self.$price.html( "&euro; " + price );
				}
				
			});
		},
		getCodes: function() {
			var self = this;
			self.$codeList.find( "li" ).each(function() {
				var code = $.trim( $( this ).text() );
				self.codes.push( code );
			});
		},
		handleInput: function() {
			var self = this;
			self.$code.on( "keyup paste", function() {
				var value = $.trim( $( this ).val() );
				if( $.inArray( value, self.codes ) != -1 ) {
					self._getData( value );
				}
			});
		}
	};
	
	$(function() {
		var $auto = new $.AutoProducts( "#cart" );
	
	});

})( jQuery );

Demo

Code

You can find the complete code on GitHub.