jQuery: autocomplete AJAX per i prodotti di un e-commerce

jQuery: autocomplete AJAX per i prodotti di un e-commerce

Tempo fa ho trovato un'interessante caratteristica su un sito di e-commerce per prodotti industriali: l'utente inserisce il codice prodotto in un campo di testo ed immediatamente vengono visualizzati i dettagli del prodotto. Possiamo implementare anche noi questa caratteristica.

AJAX

Questa caratteristica richiede AJAX. Abbiamo bisogno di:

  1. uno script lato server che elabora la richiesta e restituisce un oggetto JSON contenente il nome del prodotto ed il suo prezzo
  2. uno script jQuery che intercetta gli eventi keyup e paste ed invia la richiesta AJAX usando come parametro il valore del campo di testo.

Lo script lato server

Il nostro script (in PHP ) esegue le seguenti operazioni:

  1. valida il parametro GET della richiesta AJAX
  2. esegue la query al database
  3. crea una stringa JSON come output.

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

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

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

// Validazione ridondante

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 );
	}
}
}

Il codice jQuery

Nella pagina è già presente una lista dei codici prodotto. jQuery legherà un listener agli eventi keyup e paste e validerà il valore inserito nel campo con i codici disponibili. Se il codice è valido, eseguiremo una richiesta AJAX ed inseriremo i risultati nella pagina.


(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

Codice

Potete trovare il codice completo su GitHub.

Torna su