Simple Javascript/XML based search

August 27th, 2009

This code uses javascript to search in a XML index based and it allows to do it without the need of server side code (like PHP+MySQL)

This code is based on the work of Wieland and mapmaker who publish their codes at Dzone Snippets but resolve a some search problems.

Error found: When a search is being done the code search for similar terms intead of the exact search term in the XML index resulting in fail info returned (example: searching for “1524″ can give us as results the content of the items  “1524, 11524, 21524, etc”)

My code has fixed this issue returning info of the exact seach term (code removed has been highlighted in red, added code in green)

Example XML

<?xml version=”1.0″ encoding=”utf-8″?>
<searchable_index>
<item meta1=”22″ meta2=”87″>0000</item>
<item meta1=”25″ meta2=”29″>0001</item>
<item meta1=”27″ meta2=”54″>0002</item>
<item meta1=”23″ meta2=”43″>0003</item>
</searchable_index>

The javascript code

<script type=”text/javascript”>

window.onload = loadIndex;

function loadIndex() { // load indexfile

// most current browsers support document.implementation

if (document.implementation && document.implementation.createDocument) {

xmlDoc = document.implementation.createDocument(”", “”, null);
xmlDoc.load(”index.xml”);
}
// MSIE uses ActiveX
else if (window.ActiveXObject) {
xmlDoc = new ActiveXObject(”Microsoft.XMLDOM”);
xmlDoc.async = “false”;
xmlDoc.load(”index.xml”);
}
}

function searchIndex() {

// search the index (duh!)
if (!xmlDoc) {
loadIndex();
}
// get the search term from a form field with id ’searchme’

var searchterm = document.getElementById(”searchme”).value;
var allitems = xmlDoc.getElementsByTagName(”item”);
results = new Array;
if (searchterm.length < 2) {
alert(”Ingrese al menos dos caracteres”);
} else {
for (var i=0;i<allitems.length;i++) {
// see if the XML entry matches the search term,
// and (if so) store it in an array
var name = allitems[i].lastChild.nodeValue;
//    var exp = new RegExp(searchterm,”i”);
if ( name == searchterm ) {
//    if ( name.match(exp) != null) {
results.push(allitems[i]);

}
}
// send the results to another function that displays them to the user
showResults(results, searchterm);
}
}

// Write search results to a table
function showResults(results, searchterm) {

if (results.length > 0) {

// if there are any results, write them to a table

for (var i=0;i<results.length;i++) {
var item = document.createTextNode(results[i].getAttribute(”name”));
var item1 = results[i].getAttribute(”meta1″);
var item2 = results[i].getAttribute(”meta2″);
var visitorname = document.getElementById(”visitorname”).value;
var visitormail = document.getElementById(”visitormail”).value;
}
//    alert(”codigo=” + searchterm + “name=” + visitorname + “mail=” + visitormail + “uno=” + item1 + “dos=” + item2);
window.location.href = “email_ex.php?codigo=” + searchterm + “&name=” + visitorname + “&mail=” + visitormail + “&uno=” + item1 + “&dos=” + item2;
return false;

} else {
// else tell the user no matches were found
var notfound = alert(’Código de cliente ‘+searchterm+’ no encontrado’);
}
}
</script>

Código

Busqueda simple basada en Javascript/XML

August 27th, 2009

Este código usa javascript para buscar en un indice basado en XML y provée la posibilidad de realizar búsquedas en un website sin necesidad de ejecutar código en el servidor (como es el caso de PHP+MySql)

Este código está basado en el trabajo de Wieland y mapmaker que publicaron sus códigos en Dzone Snippets y soluciona un error en la búsqueda.

Error encontrado: Al realizar la búsqueda de un término (palabra o número), el código busca términos parecidos y no uno exactamente igual en el índice del archivo XML, el resultado de esto es que el código puede devolver información erronea (ej: buscar “1524″ puede entregar como resultado los contenidos de los ítems “1524, 11524, 21524, etc”)

El siguiente código contiene contiene las actualizaciones necesarias para una búsqueda exacta (las líneas de código quitadas han sido resaltadas en rojo y la línea de código agregada ha sido resaltada en verde)

El archivo XML

<?xml version=”1.0″ encoding=”utf-8″?>
<searchable_index>
<item meta1=”22″ meta2=”87″>0000</item>
<item meta1=”25″ meta2=”29″>0001</item>
<item meta1=”27″ meta2=”54″>0002</item>
<item meta1=”23″ meta2=”43″>0003</item>
</searchable_index>

El código javascript

<script type=”text/javascript”>

window.onload = loadIndex;

function loadIndex() { // load indexfile

// most current browsers support document.implementation

if (document.implementation && document.implementation.createDocument) {

xmlDoc = document.implementation.createDocument(”", “”, null);
xmlDoc.load(”index.xml”);
}
// MSIE uses ActiveX
else if (window.ActiveXObject) {
xmlDoc = new ActiveXObject(”Microsoft.XMLDOM”);
xmlDoc.async = “false”;
xmlDoc.load(”index.xml”);
}
}

function searchIndex() {

// search the index (duh!)
if (!xmlDoc) {
loadIndex();
}
// get the search term from a form field with id ’searchme’

var searchterm = document.getElementById(”searchme”).value;
var allitems = xmlDoc.getElementsByTagName(”item”);
results = new Array;
if (searchterm.length < 2) {
alert(”Ingrese al menos dos caracteres”);
} else {
for (var i=0;i<allitems.length;i++) {
// see if the XML entry matches the search term,
// and (if so) store it in an array
var name = allitems[i].lastChild.nodeValue;
//    var exp = new RegExp(searchterm,”i”);
if ( name == searchterm ) {
//    if ( name.match(exp) != null) {
results.push(allitems[i]);

}
}
// send the results to another function that displays them to the user
showResults(results, searchterm);
}
}

// Write search results to a table
function showResults(results, searchterm) {

if (results.length > 0) {

// if there are any results, write them to a table

for (var i=0;i<results.length;i++) {
var item = document.createTextNode(results[i].getAttribute(”name”));
var item1 = results[i].getAttribute(”meta1″);
var item2 = results[i].getAttribute(”meta2″);
var visitorname = document.getElementById(”visitorname”).value;
var visitormail = document.getElementById(”visitormail”).value;
}
//    alert(”codigo=” + searchterm + “name=” + visitorname + “mail=” + visitormail + “uno=” + item1 + “dos=” + item2);
window.location.href = “email_ex.php?codigo=” + searchterm + “&name=” + visitorname + “&mail=” + visitormail + “&uno=” + item1 + “&dos=” + item2;
return false;

} else {
// else tell the user no matches were found
var notfound = alert(’Código de cliente ‘+searchterm+’ no encontrado’);
}
}
</script>

Código

Politica 2.0

November 24th, 2008

Politica 2.0?  ok.. que significa esto? Es una nueva aproximacion hacia la politica… es una forma de suplir problemas que enfrenta la actual politica y ademas, de llegar a ser candidato sin que usted lo sepa con anticipacion.

Problemas? Principalmente que es imposible saber que hace y como hace las cosas tu politico despreciado favorito, su forma de pensar, sus conocimientos, el como toma desiciones, saber si acaso realmente trabajan o no y por supuesto, saber si se justifica la cantidad de millones que ganan hacen bien su trabajo.

y eso de “llegar a ser candidado sin que yo lo sepa”? (lo explicare al final…)

Read more…

Reflexion, Tendencias

Como conseguir Google Picasa 3 si no eres Gringo

November 15th, 2008

Si sabes que es Picasa, eres fanatico de lo que Google hace y/o crees que es un buen software, esto te va a interesar.

En breve
Picasa
es un software desarrollado por Google que permite Organizar y ver toda tu colección de fotografías en un solo lugar, Editar fotografías, recortarlas, eliminar ojos rojos y más, Crear collages y presentaciones de diapositivas impactantes y Compartir en línea con parientes y amigos a través de los Álbumes web de Picasa.

Cual es el punto? Hace unos meses ya existe la nueva version, Google Picasa 3 con nuevas funciones, integracion directa con Windows, etc, etc, etc.

Peeeerooooo solo podras obtenerlo si eres de USA.   (…o no?)

Read more…

Trucos ,

Ni acentos ni eñes!

November 14th, 2008

ok… primero que nada. Porque no hay acentos ni enies?, pues porque llevo mas de 13 anos usando un teclados ingleses (sin áéíóóñ) desde que gracias a unas vacaciones en USA adquirimos un PC Pentium Multimedia (cuando aqui en Chile habian puros 486 DX4 100mhz) y claro traia teclado en ingles. Desde aquella epoca me acostumbre a usarlo con la distribucion de teclas inglesa, sobretodo por la facilidad de teclear codigos en MS-DOS que yo tambien usaba bastante.

Hey! puedes tener configurado tu OS (sistema operativo) para que maneje dos distribuciones de teclado y asi puedes elegir entre teclado ingles o espanol!

Lo se!, y siempre tengo configurado los dos, pero les voy a ser sincero, usualmente lo tengo en ingles y escribo todo tal cual se puede… sin acentos ni enies.. asi que.. les escribire de esta manera. les gusta? no? me da lo mismo!. igual comprenden el mensaje.

Aclaraciones ,