Monthly Archives: December 2010

Sending radio and checkbox options to the server asynchronously

In usually every web application checkbox and radio button play a major role in getting the information from the user. In this article, we will learn to send the asynchronous messages of the selected checkboxes and radio boxes to the server.

For this article, we will be creating three files:

  • checkboxradioajax.php – PHP script that will display three radio buttons and three checkboxes for the user to select from.
  • checkboxradioajax.js – JavaScript file that create XMLHttpReqest object and that send the information of the selected checkboxes and radio buttons to the server asynchronously
  • checkboxradiodata.php – Server side PHP script that displays information about the selected checkboxes and radio buttons to the client as a server response

Coding for “Sending radio and checkbox options to the server asynchronously”

The code in checkboxradioajax.php file is as under :

checkboxradioajax.php

<html>

<head>

<script type=”text/JavaScript” src=”checkboxradioajax.js”></script>

</head>

<body>

Choose one : <br>

<input name=”drink” value =”Hot Coffee” onClick=’display()’> Hot Coffee  <br>

<input name=”drink” value =”Cold Coffee” onClick=’display()’> Cold Coffee <br>

<input name=”drink” value =”Soft Drink” onClick=’display()’> Soft Drink <br><br>

Choose all the options that you want to have : <br>

<input name=”food” value =”Hot Dog” onClick=’display()’> Hot Dog  <br>

<input name=”food” value=”Pizza” onClick=’display()’>Pizza   <br>

<input name=”food” value=”Noodles” onClick=’display()’>Noodles  <br>

<input name=”food” value=”Chips” onClick=’display()’>Chips  <br><br>

<div></div>

</body>

</html>

Above program defines three radio buttons with options : Hot Coffee, Cold Coffee and Soft Drink  and four checkboxes with options : Hot Dog, Pizza, Noodles and Chips. The name assigned to the radio buttons is “drink” and if any of the radio button is selected, display() method will be invoked. Similarly the checkboxes are named : “food” and if any of the checkbox is selected, same display() method will be invoked. Beside this,  a <div> element is defined with id : “info”  for displaying the server response. Remember, that we can select only one radio button in a group whereas any number of checkboxes can be selected in a group.

The code in JavaScript file, checkboxradioajax.js file is as under :

checkboxradioajax.js

1.        function makeRequestObject(){

2.        var xmlhttp=false;

3.        try {

4.        xmlhttp = new ActiveXObject(‘Msxml2.XMLHTTP’);

5.        } catch (e) {

6.        try {

7.        xmlhttp = new

8.        ActiveXObject(‘Microsoft.XMLHTTP’);

9.        } catch (E) {

10.      xmlhttp = false;

11.      }

12.      }

13.      if (!xmlhttp && typeof XMLHttpRequest!=’undefined’) {

14.      xmlhttp = new XMLHttpRequest();

15.      }

16.      return xmlhttp;

17.      }

18.      function display()

19.      {

20.      var xmlhttp=makeRequestObject();

21.      ControlsArray=document.getElementsByTagName(‘input’);

22.      var fooditms=”";

23.      var drinkitms=”";

24.      for(var i=0; i< ControlsArray.length; i++)

25.      {

26.      if(ControlsArray[i].type==”checkbox” && ControlsArray[i].checked)

27.      {

28.      fooditms+=ControlsArray[i].value + ” “;

29.      }

30.      if(ControlsArray[i].type==”radio” && ControlsArray[i].checked)

31.      {

32.      drinkitms+=ControlsArray[i].value + ” “;

33.      }

34.      }

35.  xmlhttp.open(‘GET’, ‘checkradiodata.php SelectedDrink=’+drinkitms+’&SelectedFood=’+fooditms, true);

36.      xmlhttp.onreadystatechange=function() {

37.      if (xmlhttp.readyState==4 && xmlhttp.status == 200) {

38.      var content = xmlhttp.responseText;

39.      if( content ){

40.      document.getElementById(‘info’).innerHTML = content;

41.      }

42.      }

43.      }

44.      xmlhttp.send(null)

45.      }

Explanation of the above program

Statements from 1-17 are making an XMLHttpRequest object.

21.   ControlsArray=document.getElementsByTagName(‘input’);

The elements in the web page with name : “input” (usually all the elements in a web page come under this category) are searched and all the items with this name are assigned to an array : ControlsArray.

22.   var fooditms=”";

23.   var drinkitms=”";

24.   for(var i=0; i< ControlsArray.length; i++)

25.   {

26.   if(ControlsArray[i].type==”checkbox” && ControlsArray[i].checked)

27.   {

28.   fooditms+=ControlsArray[i].value + ” “;

29.   }

30.   if(ControlsArray[i].type==”radio” && ControlsArray[i].checked)

31.   {

32.   drinkitms+=ControlsArray[i].value + ” “;

33.   }

34.   }

With the help of a loop, all the elements in the ControlsArray are checked one by one and the value of all the elements in the array which are of type “checkbox” and are checked (selected) are stored in a variable fooditms. Similarly, all of the elements of type “radio” and are checked, their values is assigned to variable drinkitms

35. xmlhttp.open(‘GET’, ‘checkradiodata.php?SelectedDrink=’+drinkitms+’&SelectedFood=’+fooditms, true);

36.  xmlhttp.onreadystatechange=function() {

37.  if (xmlhttp.readyState==4 && xmlhttp.status == 200) {

38.  var content = xmlhttp.responseText;

39.  if( content ){

40.  document.getElementById(‘info’).innerHTML = content;

41.  }

42.  }

43.  }

44.  xmlhttp.send(null)

45.  }

XMLHttp request is made to the  server (by GET method) for the file checkboxradiodata.php, sending all the selected drink items and selected food items (stored in variables drinkitms and fooditms respectively) to it.

The state and the response to asynchronous request are checked. If the value of readyState property becomes 4 and the value of the status of the HTTP Request is 200, the response is then retrieved from the response stream and is assigned to variable : content which is then applied to the innerHTML property of the element with id : “info” to display the response from the server (i.e. to display all the items selected from the checkbox and radio buttons).

The instruction : xmlhttp.send(null) is used to actually send the request to the server. And if we don’t want to pass any query string with the requested file,  the argument passed to this method is null or else it contains the query string.

Remember, the response generated by the server is based on the execution of the file : checkboxradiodata.php. Lets analyze what it returns

checkboxradiodata.php

<?php

$food=$_GET['SelectedFood'];

$drink=$_GET['SelectedDrink'];

if($drink==”")

{

echo “You have not selected any drink <br><br>”;

}

else

{

echo “The drink selected is : ” . $drink . “<br><br>”;

}

if($food==”")

{

echo “You have not selected food <br><br>”;

}

else

{

echo “The types of Food selected are : ” . $food . “<br><br>”;

}

?>

The selected food items and selected drink items are retrieved from $_GET array and stored in variables $food, and $drink respectively. The list of items selected from checkboxes and radio buttons are passed to this file  while making the XMLHttp request for the file using following command :

35.    xmlhttp.open(‘GET’, ‘checkradiodata.php?SelectedDrink=’+drinkitms+’&SelectedFood=’+fooditms, true);

We can see in above instruction that selected drink item and the selected food items are passed to the checkboxradiodata.php file. The retrieved items in $food and $drink variables are displayed on the screen (in case the contents of the variable are non blank or else the message : “You have not selected” food or dink is displayed).

Output of “Sending radio and checkbox options to the server asynchronously”

If both drink as well as food items are selected, the output may appear as shown below :

Output if both drink and food items are selected

This finishes my article on “Sending radio and checkbox options to the server asynchronously”

For more information, refer my book: “Developing Web Applications in PHP and AJAX” available at: http://www.amazon.com/Developing-Web-Applications-PHP-AJAX/dp/0070707103/ref=ntt_at_ep_dpt_4

Frequently Used HTML Properties

In this article, we will learn about few HTML properties like, Color, Font and Margin :

Color

The color property is used for setting the color of text.

Syntax:

color: value;

The value can be specified in any of the following ways:

* We can specify colors by their English names. The standard color names are: aqua, black, blue, fuchsia, gray, green, lime, maroon, navy, olive, purple, red, silver, teal, white, and yellow.

* Colors can also be defined as an RGB triplet in hexadecimal format i.e. the combination of Red, Green, and Blue color values. The lowest value is 0 (hex 00) and t highest value is 255 (hex FF)

Example:

“#00FF00″

It represents colors as hexadecimal numbers for red, green and blue. The first two characters following the # give the number for red, the next two for green and the last two for blue. These numbers are always in the range 0 to 255 decimal. Above example designates dark green color

Font

The font property is used for setting the font family, size, style and weight of the desired element. The font property includes the following properties:

Font-Family

The font-family property is for setting the font to be displayed in an element.

Example:

font-family: Verdana;

The element to which this property is applied will appear in Verdana font

The value of this property can be any font like verdana, sans-serif, arial, courier etc;

Font-Size

The font-size property is for setting the size of the text used in an element.

Syntax:

font-size: value;

where the value can be any of the following:

* xx-large

* x-large

* larger

* large

* medium

* small

* smaller

* x-small

* xx-small

* length

* % (percent)

Examples:

font-size: xx-large;

font-size: small;

Out of the above font size values, length and % (percent) needs explanation. Both are used for specifying the font size in units.  CSS provides us four different units to specify the font size:

* “Ems” (em) The “em” is a scalable unit that is equal to the current font-size. That is, if the if the current font-size of the document is 12pt, then 1em is equal to 12pt. Ems are scalable in nature, so 2em would equal 24pt, .5em would equal 6pt, etc.

* Pixels (px) – Pixels are fixed-size units used to define the resolution of the computer screen One pixel is equal to one dot (smallest unit) on the computer screen. The size in pixels cannot be scaled up or down.

* Points (pt) – Points are usually used for defining size of printable documents. One point is equal to 1/72 of an inch.

* Percent (%) – The percent unit is much like the “em” unit. If the current font-size of the document is 12 pt, then font size of 100% means 12pt. The benefit of using the percent unit is that the text can be scaled up as well as down.

Note: Both the em and percent units get larger as the base font-size increases, but pixels and points do not.

Examples:

font-size:12px;

font-size:120%;

Font-Style

The font-style property is for setting the style of the text in a desired element.

Syntax:

font-style: value;

where values can be any of following:

* normal

* italic

* oblique

Font Weight

The font-weight property is for specifying the weight of text in a desired element.

Syntax:

font-weight: value;

where value can be any of the following:

* lighter

* normal

* 100 .. 900

* bold

* bolder

Examples:

font-weight:bold;

font-weight:300;

font-weight:lighter;

Margin

The margin property declares the margin between an HTML element and the elements around it. This property can be set for the top, left, right and bottom of an element. It includes the following four properties: margin-top, margin-left, margin-right and margin-bottom to specifying the margins for the top, left, right and bottom of the element respectively.

Syntax:

margin-(top/left/right/bottom): value;

where value can be specified in terms of length, percentage or auto. The length can be specified in terms of px (pixels), pt (points), in(inches) etc.

Examples:

margin-top:10px;

margin-top:.3in;

We can also specify all the four margins of an element in a single property: margin

With margin property, we can specify the top, left, right and bottom margin of an elements simultaneously. The sequence of specifying the four margins is as follows: top, right, bottom and left.

Example:

margin: 10px 10px 10px 10px;

If we want to specify the same margin on all sides, we can even specify a single value to be applied for all sides.

Example:

margin: 10px;

First Step to learn CSS Styles

In this article you will learn the application of Internal style sheets for giving dynamic appearance to the web pages. The Style sheets are a collection of styles popularly used for applying uniform formatting to the web site.

Styles is a term that denotes the combination of different fonts, colors, back-grounds etc. that can be applied to the web contents to highlight some important information and to make the web site as a whole more attractive.

The Style Sheets properly known as Cascading Style Sheets (CSS) is a style language developed and maintained by World Wide Web Consortium (W3C). Its main purpose is to apply dynamic layout and appearance to the documents written in a markup language. As said earlier, a style sheet contains several styles. Cascade here means application of more than one style onto an HTML element simultaneously.

In the Style sheet, the styles are written in the form of rules where every rule is a combination of a selector and declaration.

Let us see one rule:

H1{color:red;font-family:arial;margin:1.0in}

Above rule is a combination of a selector and declaration. The selector is the name of the HTML element to which declaration is applied i.e. H1 element in above rule is a selector. The declaration is a collection of property and value pairs separated by colons. Like in above rule, color is a property and red is its value. If there is more than one declaration in a rule, they are separated by ; (semi colon). The list of style properties in declaration are bracketed by { and }.

Syntax of rule:

selector { attribute: value, value…. attribute: value, value… etc.}.

Note: In the HTML file, we can define our own selectors with the help of ID and Classes.

The Cascade Style Sheets (CSS) can be used either internally or externally i.e. they can be either embedded inside an HTML file or can be written in a separate file that is then inked to the HTML file.

Using Internal Style Sheet to apply style to H1 element

The style sheet can be written internally within the HTML file or externally in a separate file. The styles written in internal Style sheet can be applied to only the same HTML file in which it is included. For internal Style Sheet, you need to simply place the CSS code (rules) within the <head></head> tags of the HTML file to which we want to apply the styles as shown below :

<style/css>

H1{color:red;font-family:arial;margin:1.0in}

</style>

The rule is a collection of property and value pairs and we can use any number of properties in a rule. In above example we have used three properties: color, font-family and margin but we may use any. We will just see the usage of these properties.

We see that the style rules are written between the <style> and </style> tags in case of internal style sheet. In above statement, we have used a single rule consisting of combination of selector and declaration. The selector is H1 as we want to apply style to this element(s) of the HTML file  and the declaration is color:red;font-family:arial;margin:1.0in. The declaration consists of three sets of properties and their values though we can use any number of property and value pairs. The color property will make the H1 element to appear in red color, font-family property will set the font of the H1 element to arial font and the margin property will make the H1 element to appear at the distance of 1 inch from the top and left border of browser window .

A compete HTML file with the internal Style Sheet that applies style to H1 element may appear as :

<html>

<head>

<style type=text/css>

H1{color:red;font-family:arial;margin:1.0in}

</style>

<title>Styles Examples</title>

</head>

<body>

<H1>Believe in God</H1>

</body>

</html>

The thing to remember is that the style rules have to be written between  <style> and </style> tags. To see how H1 element appears on application of style, we need to open the HTML file with the help of a browser and we will see that the text enclosed in between <H1> and </H1> tags appears as shown in Figure 1 with all the properties: color, font-family and margin applied to it.

Style applied on H1 tag

Figure 1 Style applied on H1 tag