HTML – WebDevLounge http://webdevlounge.com Design, development, SEO and wordpress Thu, 30 Aug 2018 12:49:53 +0000 en-US hourly 1 https://wordpress.org/?v=6.1.5 AJAX: Auto Suggest http://webdevlounge.com/ajax-auto-suggest/ Thu, 06 Jul 2017 02:30:59 +0000 http://webdevlounge.com/?p=85

If your a web developer looking to add some extra functionality to your clients website and look good while your at it, then than an auto suggest search bar is something you might consider. Ever since ‘Google Suggest‘ rolled out the labs, hundreds of clones have sprung up on a variety of websites, each with a slight twist on the original. This article is going to show you how to make your own ‘auto suggest’ search bar in three easy steps.

This article assumes you have a solid grounding in HTML, CSS, Javascript and PHP. It is showing technique, not teaching you the language.

Step 1 – Good Form

The first step towards making our finished product is to develop the front-end of the site. This is basically going to consist of a HTML form containing an text input dialog, a submit button and a placeholder for our suggestions. With that in mind, lets look at the code:

<html>

<head><title>Auto Suggest</title></head>

<body>

<form action="#" ><input type="text" id="inputtext" />
<input type="submit" name="submit" value="Search" />
<div id="suggestions"> </div>
</form>

</body>

</html>

As you can see we have our text box labeled ‘inputtext<input type=”text” id=”inputtext” /> and our placeholder labeled ’suggestions’ <div id=”suggestions”> </div>. When we come to write the Javascript we can use these id’s to access them. That’s all that’s needed for now, so lets move on to step 2.

Step 2 – Script Me

Right now our page is static and ultimately useless. However, with a little Javascript magic it will start to come alive. Before we right the code, lets take a step back and think about what we need to do. Every time a letter is entered into our form we want to send a HTTP request to the server and check if the string in the form matches any of the results from a preset list. If it does we want to write the results to our web page. So the first thing we need check if a letter has been entered into our text box. To do this we can use the onkeyup attribute to call a Javascript method every time a new letter is entered. So our HTML now looks like this:

<form action="#" >

<input type="text" id="inputtext" onkeyup="suggest(this.value)" />

<input type="submit" name="submit" value="Search" />

<div id="suggestions"> </div>

</form>

So now, every time a letter is entered the Javascript function ‘suggest‘ is called, passing the value in  the text box as a parameter. That’s all well and good, but the suggest function doesn’t exist yet, so lets create it.

var xmlHttp;

function suggest(input) {
        xmlHttp=GetXmlHttpObject();
    if (xmlHttp==null) {
        alert ("Browser does not support HTTP Request");
        return;
    }
var url="suggest.php";
    url=url+"?query="+input;
    xmlHttp.onreadystatechange=stateChanged;
    xmlHttp.open("GET",url,true);
    xmlHttp.send(null);
} 

function stateChanged() {
     if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete"){
         document.getElementById("suggestions").innerHTML=xmlHttp.responseText ;
    }
 }

function GetXmlHttpObject() {
    var xmlHttp=null;
    try{
        xmlHttp=new XMLHttpRequest();
    }catch (e){
        try {
            xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
        }catch (e){
            xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
        }
    }
    return xmlHttp;
}

Don’t be scared! Although it looks a lot it is in fact very simple. the GetXmlHttpObject() is our standard function to create an XMLHTTPRequest object that works across all browsers and the stateChanged() function simply receives text from the server and places it in our ‘suggestions‘ placeholder. The suggest function itself is also very simple to understand. Basically, it creates a new XMLHttpRequest object and stores in the variable xmlHttp. After some basic error checking, we tell our application to run the stateChanged() function when there is a change of state. The URL is then created from the text inputted in our text box and the HTTP request is opened and sent with this URL. Now we have all the client side code completed and functioning, the last thing we need to do is write our PHP file.

Step 3 – Server Side

All we need the server to do is check to see whether the query sent matches anything stored in a file, database or anything we want. In this example we are going to just fill an array with countries from around the world and then see if the query matches them. We can do this as follows:

<?php

$countries[] = "Afghanistan";
$countries[] = "Albania";
$countries[] = "Algeria";
$countries[] = "Azerbaijan";
$countries[] = "Bahrain";
$countries[] = "Barbados ";
$countries[] = "Belgium";
$countries[] = "Canada ";
$countries[] = "Chile";
$countries[] = "China";
$countries[] = "Egypt";
$countries[] = "Germany";
$countries[] = "India";
$countries[] = "Iraq";
$countries[] = "Ireland";
$countries[] = "Mexico";
$countries[] = "Pakistan";
$countries[] = "Poland";
$countries[] = "Sri Lanka";
$countries[] = "Sudan";
$countries[] = "Thailand";
$countries[] = "United Kingdom";
$countries[] = "United States of America";
$countries[] = "Zimbabwe";

$query=$_GET["query"];

if (strlen($query) > 0) {
    $suggestions="";
    for($i=0; $i<count($countries); $i++) {
            if (strtolower($query)==strtolower(substr($countries[$i],0,strlen($query)))) {
            if ($suggestions=="")
                $suggestions=$countries[$i];
            } else {
                $suggestions=$suggestions.", ".$countries[$i];
            }
        }
    }
}

echo $suggestions;

?>

All this does is populates an array with a variety of countries (of course, in a real world application this would be populated from a database or text file) then gets the query that was passed to it. The code following this simply checks to see whether the query passed matches anything in the array and adds it to the ‘suggestions‘ string. At the end of the script the suggestions are outputted and received by the Javascript.

Finished… nearly

So now we have a fully functioning auto-suggest feature. Right now it looks a little bland but with a little CSS and imagination we can create something that really looks the part. By slight modifying the code and adding some styling I came up with this example. Give it a try yourself and post your results in the comments, we would love to see them!

]]>
Tables: Friend or foe? http://webdevlounge.com/tables-friend-or-foe/ Fri, 22 Apr 2011 12:39:43 +0000 http://webdevlounge.com/?p=53

With the recent move towards semantic, clean, tableless, and beautiful code, there have been people who have gone overboard trying to perfect their code by leaving tables out completely. Many swear that they are bad, shouldn’t be used, and are just a sign of bad, outdated coding. This is not the case however, and tables are a semantic, and useful tool in many situations.

When they should be used?

Even with the abundance of such people who curse tables, there are some people who use tables from time to time. The clear majority of these people use them for one purpose, and that is for tabular data. This sounds like a broad term, however, tabular data includes anything that should be represented with rows and columns, which includes, but is not limited to the following:

  • Hosting plan information
  • Invoices
  • Shopping carts

The aforementioned information is what uses tables, as no other way of coding them makes sense, however there are people who will do whatever they can to avoid tables and still present this information how they need to. If you have to convince yourself that you should use something else since a table makes most sense, then chances are, a table is right for the job.

Here is an example of a properly used table via the amazon.com shopping cart:

When shouldn’t they be used?

This is a rather obvious question, even for people who don’t code but just stay on the design side of the spectrum. The main thing that a table should not be used for, is of course, an entire layout. There was once a time where it was okay, and even encouraged to use a table for an entire site, however as browsers have become better, they have been better suited to handle use of tableless layouts along with the implementation of CSS. In addition to using them for layouts, tables shouldn’t be used for any purpose other than for data, tabular data that is. To use them for any other purpose would be considered outdated.

Common ways to get around tables

Over the years, coders have come up with many ways to get around having to use tables. Some use lists, both <ul> lists and definition lists, <div>’s, and any other tag they could use. All of these ways are considered wrong, and for many reasons.

The following code is an example of how someone may code a pseudo-table using lists:

<ul id=”headings”>
	<li>ID</li>
	<li>Name</li>
	<li>Qty</li>
	<li>Remove</li>
</ul>
<ul id=”item”>
	<li>1</li>
	<li>Tables using lists</li>
	<li>3</li>
	<li>Yes / No</li>
</ul>

Take that code, and imagine that there is one list for the heading, and another one for each item in the example shopping cart. While it will result in the same amount of markup, a list isn’t the correct way to represent a single item in a shopping cart.

This next example is the same pseudo-table, but by using <div>’s in place of lists.

<div id=”headings”>
	<div>ID</div>
	<div>Name</div>
	<div>Qty</div>
	<div>Remove</div>
</div>
<div id=”item”>
	<div>1</div>
	<div>Tables using divsts</div>
	<div>3</div>
	<div>Yes / No</div>
</div>

As you can see, this code is remarkably similar to using lists, however it is far less semantic than using a list, while lists still aren’t semantic. For example, if you wanted to have bold text on a page, you wouldn’t use the <span> tag with an inline style to bold the text, you would just use the <strong> tag because it makes more and it was made strictly for that purpose.

How do you make a proper table?

Here I am going to show a quick code example of what a simple, yet proper table, should look like, using code. I’ll use the same example as I did earlier, with a pseudo-shopping cart.

ID Name Qty Remove
1 A proper table 3 Yes / No

You can view the source of the table here:

<table border=”1” cellspacing=”0” cellpadding=”4” summary=”Shopping cart for user”>
	<thead>
		<tr>
			<th>ID</th>
			<th>Name</th>
			<th>Qty</th>
			<th>Remove</th>
		</tr>
	</thead>
	<tbody>
		<tr>
			<td>1</td>
			<td>A proper table</td>
			<td>3</td>
			<td>Yes / No</td>
		</tr>
	</tbody>
</table>

Now to go over each part of the tables code. Of course, you have the opening tag, which includes any declarations that can’t be done using CSS, which includes cellspacing, and others which include the border and cellpadding. However, there is a new one in the opening tag that you may have never seen before, which is summary. This attribute is rather self explanatory, and it includes a brief summary of what the table is for and what it is used for.

There is also two other tags which are rarely used, which are <thead> and <tbody>. Again, these tags are self-explanatory, however, in addition to these, there is also <tfooter>. The purpose of these three tags, is to define a header section, which includes table headings, a body section, which includes all of the items (inside a shopping cart, for example), ad a footer section which would include items such as a checkout button, subtotal, tax, etc. While these are not 100% necessary, they do combine to create a proper table using correct markup techniques.

Lastly, are the most common tags, as they are used in every single table, which are the <td> and <th> tags, which create a “table detail” cell, and a “table heading” cell inside the table. The <td> tag should be used for all cells, except when they are a table header, such as the ID, Name, Qty, and Remove headings in the above table example.

Here is an example of a properly coded table, making use of the caption tag as well: (click for live view)

Have fun coding your tabular data!

]]>