Thursday, June 12, 2008

Populate droplist dynamically through AJAX

Mechanism to make an ajax call from one drop list and populate another droplist


In JSP

Add a html select element as below

html:select name=somethingOne id=dropListOne onchange="retrieveDropTwoOptions()

html:select name=somethingTwo id=dropListTwo


function retrieveDropTwoOptions(){

dropListOne = document.getElementById('dropListOne');
if(dropListOne.selectedIndex==0){
document.getElementById('dropListTwo').options.length = 0;
document.getElementById('dropListTwo').options[i] = new Option("---", "", true);
return;
}
dropListOneCode = dropListOne.options[dropListOne.selectedIndex].value;
url='/MyServer/ajax.do?method=populateDropList' +
'&dropListOneCode=' + dropListOneCode ;


//Do the Ajax call
req = ajaxRequestSend(url, "GET", populateDropListTwoBox);

}

//Callback function
function populateDropListTwoBox(){

if (req.readyState == 4) { // Complete
if (req.status == 200) { // OK response
textToSplit = req.responseText;

myCode = document.getElementById('dropListTwo').value; // obtained from form
//Split the document
returnElements=textToSplit.split("\n")

//Process each of the elements
document.getElementById('dropListTwo').options.length = 0;
for ( var i=0; i valueLabelPair = returnElements[i].split(":")
if (myCode == valueLabelPair[0]) {
document.getElementById('dropListTwo').options[i] = new Option(valueLabelPair[1], valueLabelPair[0], true);
}
else {
document.getElementById('dropListTwo').options[i] = new Option(valueLabelPair[1], valueLabelPair[0]);
}
}
}
}


function ajaxRequestSend(url, method, callBackFunciton){
if (window.XMLHttpRequest) {
req = new XMLHttpRequest();
} else if (window.ActiveXObject) {
req = new ActiveXObject("Microsoft.XMLHTTP");
}
req.open(method, url, true);
req.onreadystatechange = callBackFunciton;
req.send(null);
return req;
}


In AjaxAction.java, we add a simple method to return a value

public class AjaxAction extends Action
{
//...

public void populateDropList()
{
StringBuffer body = new StringBuffer(":---\n");

//... get data from database

while (resultSet.next()) {
code = resultSet.getString("code") ;
desc = resultSet.getString("name") ;
body.append("\n").append(code).append(":").append(desc);

}

response.setContentType("text/plain");
response.setHeader("Cache-Control", "no-cache");
response.getWriter().write(body.toString());
response.getWriter().flush();

}

}

Simple AJAX

Method to get make a simple ajax call and get a response

function openTermsAndConditions()
{

var selectedIndex = document.getElementById("planOptions").selectedIndex;
var selectedText = document.getElementById("planOptions").options[selectedIndex].text;
if(selectedText)
{
retrievePlanTermsURL(selectedText);
}
}

function retrievePlanTermsURL(planId)
{
url = '/MyServer/ajax.do?method=getPlanTermsAndConditionsURL' +
'&planId=' + planId;

//Do the Ajax call
req = ajaxRequestSend(url, "GET", openURL);

}

//Callback function
function openURL()
{
var termsURL = "";
if (req.readyState == 4) // Complete
{
if (req.status == 200) // OK response
{
termsURL = req.responseText;
document.getElementById("termcondURL").value = termsURL;
if(termsURL)
{
window.open(termsURL, "windowTermsAndConditions", "width=500,height=500");
}
}
}
}

function ajaxRequestSend(url, method, callBackFunciton){
if (window.XMLHttpRequest) {
req = new XMLHttpRequest();
} else if (window.ActiveXObject) {
req = new ActiveXObject("Microsoft.XMLHTTP");
}
req.open(method, url, true);
req.onreadystatechange = callBackFunciton;
req.send(null);
return req;
}


In AjaxAction.java, we add a simple method to return a value

public class AjaxAction extends Action
{
//...

private void getPlanTermsAndConditionsURL() throws Exception
{
String returnValue = DatabaseHelper.getSomeData();
response.setContentType("text/plain");
response.setHeader("Cache-Control", "no-cache");
response.getWriter().write(returnValue);
response.getWriter().flush();
}


}

In JSP, add an html select element with id =planOptions

Nested Iterate tag

If you have a Collection in ActionForm and require to access them, we can use nested:iterate

<nested:iterate name="memberCustomerViewForm" property="addressList" >
<div>
<span class="leftBuffer"> </span>
<span class="generalInput">
<nested:text property="addressType" onblur="toUpper(this);" size="11" />
<nested:hidden property="addressId"/>
</span>
</nested:iterate>


Note
- do not use id=current in nested:iterate
- don't access like <nested:text name="current" property="addressType" />

Tuesday, May 27, 2008

Dynamically Add or Remove HTML elements

<HTML>
<HEAD>
<script type="text/javascript">

var sequence = 0;

function addTextBox()
{
var dynDiv = document.getElementById('dynamicDiv');
var newDiv = document.createElement("DIV");
var newDivIdName = 'Div'+sequence;
newDiv.setAttribute('id',newDivIdName);
var newSpan = document.createElement('SPAN');

addField(newSpan,{ type :"text", name :"test"+sequence, value:"test"+sequence , size:30 });
addField(newSpan,{ type :"button", name :"delete"+sequence, value:"delete", id:"delete"+sequence });

newDiv.appendChild(newSpan);
dynDiv.appendChild(newDiv);

var deleteButton = document.getElementById('delete'+sequence);
deleteButton.onclick=function()
{
removeTextBox(newDivIdName);
}

sequence++;
}



function addField(form,json)
{
var inp=document.createElement("input");
for(var i in json)
{
inp[i]=json[i];
}
form.appendChild(inp);
}


function removeTextBox(divNum)
{
var dynDiv = document.getElementById('dynamicDiv');
var obj = document.getElementById(divNum);
dynDiv.removeChild(obj);
}

</script>

</HEAD>


<BODY>
<form name="testForm">
<div id="dynamicDiv">
<span>

<input type="text" name="address1" value="test"/>
<input type="button" name="Add" value="Add" onclick="addTextBox();" />
</span>
</div>

</form>
</BODY>

</HTML>

Thursday, May 1, 2008

What Kevin says...

4 yrs

twinkle twinkle little star

how I wonder what you are
appa daddy world so high
like a diamond in the sky

5.5 yrs

shopkeeper: how old are you?
kevin: half and a five

kevin: mum do you eat cows? At school my friend said she ate a cow!

Working with collections

If we have to iterate a Collection in struts and were required to pass back the object values from the collection as hidden fields to be set in the form, we would get an ArrayIndexOutofBounds exception. This is because we cannot set the collection as is. We need a special handling to add the objects to the collection from the jsp to form like the example given below.

Create a class called CustomList as follows

public class CustomList extends ArrayList {

private Class elementType;
private int maximumGrowSize;

public CustomList(Class elementType, int maximumGrowSize) {
this.elementType = elementType;
this.maximumGrowSize = maximumGrowSize;
}

public Object get(int index) {
while(index >= size()) {
if (index > maximumGrowSize) {
throw new RuntimeException("Cannot allow list to automatically grow beyond " + maximumGrowSize);
}
try {
add(elementType.newInstance());
} catch (Exception e) {
throw new RuntimeException(e);
}
}
return super.get(index);
}
}

In struts Action Form, we add

private List records = new CustomList(Person.class, 1000);
where Person.java is our model object which is populated in the collection

Sometimes we may have to display checkboxes next to each record to give the user option to delete selected records.
In such a case we handle the code as below:

<logic:iterate property="records">
<tr class="<%=rowClass%>" style="text-align:center">
<td>
<logic:checkbox property="delete" />
</td>
<td>
<logic:hidden property="personName"/>
<logic:write property="personName"/>
</td>
<td>
<logic:hidden property="personAge"/>
<logic:write property="personAge"/>
</td>
</tr>
</logic:iterate>


In the form, we can add a wrapper class to our Person object as shown below

public class PersonForm extends ActionForm
{

private List records = new CustomList(PersonWrapper.class, 1000);

public List getRecords()
{
return records;
}

public void setRecords(List records)
{
this.records = records;
}


public static class PersonWrapper extends Person
{

private boolean delete;

public boolean isDelete()
{
return delete;
}

public void setDelete(boolean delete)
{
this.delete = delete;
}
}

//....

}

Then in our struts Action class, we can get

public class PersonAction extends Action
{

List myRecords = actionForm.getRecords(); //This would have the the delete checkbox value as well in each row of the collection

for (PersonForm.PersonWrapper record : myRecords)
{
if (record.isDelete())
{
// do delete from database....

}
}

//...


//How to populate this result collection for display is as shown below

List<Person> results = databaseHelper.getAllPersonRecords();

if (results.size() > 0)
{
for (int i = 0, n = results.size(); i < n; i++)
{
PersonForm.PersonWrapper rec = new PersonForm.PersonWrapper();
try
{
PropertyUtils.copyProperties(rec, results.get(i));
}
catch (Exception e)
{
logger.error("Error copying Person beans!", e);
}
results.set(i, rec);
}
}

Wednesday, April 2, 2008

Cures from food

Almonds
Rich in protein, zinc, calcium, magnesium, potassium, phosphorus, vitamin E and antioxidants.
Food for the brain,heart, nervous system, digestion and blood pressure.

Asian greens
A great source of folate, antioxidant-rich, no fat, high in fibre, calcium, beta-carotene, potassium and vitamin C.

Apricots
Fresh or dried, a high source of dietary fibre and low GI. Relieve constipation and balance the nervous system. Contain vitamins A, B and C, iron, potassium and magnesium.

Avocados
Rich in omega 3 and essential amino acids. Also contains vitamins B6, C, K and folate. Use as a spread instead of butter.

Bananas
A convenient snack and rich in iodine, iron, zinc, potassium and folate, as well as vitamins A, B and E. Good for
treating diarrhoea.

Blueberries
One of the best antioxidant food sources you can eat; very rich in vitamin C, with half a punnet supplying the recommended daily requirement. A good source of fibre, vitamins B6 and E, potassium and bioflavonoids that assist in absorption of other fruits. Great for eyesight, healthy kidneys, strong blood capillaries and diarrhoea. Eat half a cup
every day.

Brazil nuts
An excellent source of selenium for assisting with fertility. They also contain protein, fibre, essential fatty acids, calcium, zinc and B vitamins.

Carrots
Rich in beta-carotene for good eyesight, they also treat heartburn, constipation and flatulence and are good for circulation, immunity, skin, hair and nails. One of the few vegetables that is more nutritious when cooked. Raw carrots inhibit activity of listeria by reducing the risk of food poisoning.

Cheese (hard block varieties, especially parmesan and tasty)
Excellent source of protein, calcium, magnesium, zinc and vitamins D and A. High in saturated fat, so eat in moderation.

Chickpeas and lentils
Highly nutritious, great for digestion, hypertension and diabetes. Low in fat, high in protein and fibre, a low-GI carbohydrate that contains iron, calcium, magnesium, zinc, B vitamins and essential fatty acids.

Dairy products˜low fat
(milk and yoghurt best sources)
Most absorbable source of calcium and contain all essential amino acids. Good source of protein. Milk is almost a complete food. Yoghurt aids digestion. Both are rich in magnesium, phosphorus, potassium and vitamins A, B and D. Hard cheeses are recommended during pregnancy.

Dark green vegetables
(broccoli, spinach, rocket)
An excellent source of folate, calcium and vitamin C. Low in fat, rich in fibre and a useful source of beta-carotene,
iron, magnesium and potassium. Use minimal water when cooking to retain nutritional value.

Dried fruit
Contain vitamins A, B3 and C, calcium, iron, phosphorus and potassium. Great high-fibre snack, especially prunes, dried apricots and pears.

Eggs
Nature’s own vitamin capsule and close to being a complete food. Higher in protein than chicken.
A great source of iodine, omega 3, zinc and vitamin D, as well as folate, iron, calcium, selenium, phosphorus, potassium and vitamin A.

Fennel
Well-known for its healing powers. Aids nausea, vomiting, bloating, stomach cramps and digestion and prevents flatulence. Seeds are the riches source of the plant.

Flaxseed oil
Rich in omega 3 and other essential fatty acids. Contains protein, fibre, calcium, vitamins B1, B3 and B6, magnesium, selenium and potassium. Aids constipation. Do not cook as it can turn rancid. Use in salad dressings, over steamed vegetables or sprinkle on yoghurt or cereal. Store in the refrigerator.

Garlic
Antibacterial and healing properties. Strengthens immune system, good for blood circulation, colds and flu
and general good health.

Ginger
Remedy for nausea and digestion troubles. Boosts circulation, metabolism and energy. Contains calcium, vitamin B5, magnesium, zinc and potassium.

Herbs (fresh)
Packed with protein, fibre, antioxidants, folate, iron, beta-carotene, calcium, vitamins A, B2, C and K, magnesium, phosphorus and potassium. The healthiest way to flavour foods, especially parsley, basil, mint and rosemary.

Lean meat
(beef, lamb and chicken)
Most absorbable source of iron, containing all essential amino acids. A great source of protein, zinc and vitamin B12.

Oats
The wonder grain. Highly nutritious, a great alternative to wheat and a wise breakfast option. A low-GI complex carbohydrate, and high in fibre, protein and essential fatty acids.

Also a good source of calcium, magnesium, potassium and folate. Vital to a healthy nervous system and useful for treating diabetes and mild depression.

Pears
A fabulous food for pregnancy. Calms the digestive system, cleanses, heals and is a good aid for constipation. They are also low GI.

Seafood
(salmon, mussels, canned sardines and tuna)
Important food source during pregnancy. Has the lowest level of saturated fat of all animal proteins.

Good source of zinc, iodine, omega 3 and vitamin B12. Also contains iron, calcium, vitamin B, potassium and phosphorus.

Sesame seeds

Very rich source of calcium, protein, vitamin E and fibre.
Good for the liver, kidneys, circulation and fatigue.

Sunflower seeds
Rich in omega 3 and dietary fibre, with traces of folate, iron, zinc, calcium, magnesium and selenium.

Tofu
The only non-animal source of complete protein. Low in saturated fat and free of cholesterol. Great source of iron, calcium, magnesium, phosphorus, potassium, B-group vitamins and dietary fibre. Tofu and tofu products should be eaten in moderation (2–3 servings a week are advised).

Wheatgerm
A fantastic source of zinc. It also contains protein, fibre, folate, vitamin B6, potassium and magnesium, as well as iron, calcium and essential fatty acids. For optimal health, have a tablespoon in smoothies or on your breakfast cereal every day.

Wholegrains
One of the best sources of B-group vitamins and folate. A low-GI carbohydrate, useful source of protein and dietary fibre. Also contain calcium, magnesium, zinc, selenium and potassium.

The following herbs are not superfoods for pregnancy. They are herbs that may help relieve certain health problems.

Mint
Good for: digestion, nausea, vomiting, circulation, heart palpitations. Can relieve stomach cramps and induce sleep.

Used in:
Stir-fries, Indian dishes, salads, salsas, marinades, tea infusions; goes with lamb, tomatoes, chickpeas and yoghurt.

Nutmeg:
Good for: nausea.

Used in: fresh nutmeg grated over cooked spinach, backed pumpkin, rice puddings or desserts made with ginger and honey.

Oregano:
Good for: Ear, nose, throat and lung infections, stimulates digestion.

Used in: Italian dishes, complements fish, lamb, chicken and tomatoes; use fresh or dried.

Parsley:
Good for: Anaemia, digestion, fluid retention, constipation, poor appetite, cleansing lungs, liver function, boosting immune system, useful source of iron and vitamin A

Used in: Tabbouli, salads, soups, casseroles, juices, goes well with fish, beans, eggs, garlic, lemons, lentils, pasta; best eaten fresh.

Rosemary:
Good for: Heart, bloody clotting, digestion, relieving indigestion and wind, rich source of antioxidants.

Used in: Great with lamb, chicken, pork, bread and potatoes; use fresh rosemary when chargrilling meats to counteract cancer-causing substances.