Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
?
Solved

Ajax - changing static dropdow to dynamic

Posted on 2010-01-03
21
Medium Priority
?
594 Views
Last Modified: 2013-11-24
Thanks to kadaba, The code below utiliizes AJAX, which currently works for static values.  I am hoping that some one could look at my code and tell me how to alter is such that the select statement found in the "try" such that it would dynamically return values to the business dropdown. the business field would be populated onchange of company field.  Found below is the java, js, and html.

*.  Please note at this point I do realize that the return would have nothing to do with the company selected (saving that for the next step).

Specifically see the following lines of code:

/*
       * Example block of code which would be
       * derived from the Data base as above
 */

----------- The Servlet File:OrgDrillServlet.java ---------------
package com.testajax;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.sql.Statement;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class OrgDrillServlet
 */
public class OrgDrillServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public OrgDrillServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		String key = request.getParameter("DD_ORG_CO_KEY");
		String businessKey = request.getParameter("DD_ORG_BUS_KEY");
		
		System.out.println("DD_ORG_CO_KEY ID IS :::"+key);
		System.out.println("DD_ORG_BUS_KEY ID IS :::"+businessKey);
		
		/*
		Statement stmt= null;
		DBConnection DBConn =null;
		try{
			DBConn  = DBConnection.getInstance();
			stmt = DBConn.getStatement();
		}catch (SQLException exception){
			System.out.println("SQL Exception while connecting to DB!");    	
		} catch (InstantiationException exception) {
			System.out.println("Cannot create a DB connection!");    			
		} catch (IllegalAccessException exception) {
			System.out.println("Acess Denied to connect!");    			
		} catch (ClassNotFoundException exception) {
			System.out.println("Class not found!");    			
		}
		*/
		
		response.setContentType("text/xml");
		response.setHeader("Cache-Control", "no-cache");
		
		// If the key is null we will assume that this is a call to populate sub business names
	    if (key != null) 
	    {
	    	System.out.println("Populating the business names...");	
			String resp = "";
			resp = "<?xml version='1.0'?>";
			try {

				PrintWriter out = response.getWriter();
				
				/*
				 	resp = resp + "<Business>"; 
					String lsQuery = " (SELECT ORG_KEY , ORG_NAME  FROM ORG_TAB ORDER BY ORG_NAME ASC)";
					ResultSet rs=stmt.executeQuery(lsQuery);
				
					String BusinessId = "";
					String BusinessName ="";
			
					while (rs.next()) {
						BusinessId 		= rs.getString("ORG_KEY");
						BusinessName 	= rs.getString("ORG_NAME");
						resp = resp + "<BusinessName id='"+BusinessId+"'>"+BusinessName+"</BusinessName>";
	            	}
	            	resp = resp + "</Business>";	
	            */
				
				/*
				 * Example block of code which would be
				 * derived from the Data base as above
				 */
				resp = resp + "<Business>";
				resp = resp + "<BusinessName id='1'>Investment Banking</BusinessName>";
				resp = resp + "<BusinessName id='2'>Mortgage</BusinessName>";
				resp = resp + "<BusinessName id='3'>Small Scale Industries</BusinessName>";
				resp = resp + "</Business>";
				
				System.out.println("The XML data retrieved is:");
				System.out.println(resp);
				
				out.write(resp);
				out.flush();
			} catch (Exception exception) {
				System.out.println("Error occured when fecthing the business names:"
						+ exception);
			}
	    }
	    // request for displaying sub business names
	    else
	    {
	    	System.out.println("Populating the sub business names...");	
			String resp = "";
			resp = "<?xml version='1.0'?>";
			
			try {

				PrintWriter out = response.getWriter();
					
				/*
				 * Example block of code which would be
				 * derived from the Data base 
				 */
				resp = resp + "<Business>";
				resp = resp + "<SubBusinessName id='1'>Sub - Investment Banking</SubBusinessName>";
				resp = resp + "<SubBusinessName id='2'>Sub - Mortgage</SubBusinessName>";
				resp = resp + "<SubBusinessName id='3'>Sub - Small Scale Industries</SubBusinessName>";
				resp = resp + "</Business>";
				
				System.out.println("The XML data retrieved is:");
				System.out.println(resp);
				
				out.write(resp);
				out.flush();
			} catch (Exception exception) {
				System.out.println("Error occured when fecthing the sub business names:"
						+ exception);
			}
			
	    }
	}	

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

}
-------------End of the Servlet file -------------------

------------ The HTML File-------------------------------
<html> 
<head> 
<title>AJAX Drill Test</title>
<script type="text/javascript">
var xmlhttp;

/**
 * Function to return the reference to the object by passing the Id of the 
 * object
 */
function $(elementId){
	return document.getElementById(elementId);
}

/**
 * Function to initialize the http xml request object.
 * The function will return true if the object is valid else will
 * return false	
 */
function initHttpReqObject()
{
	if (window.XMLHttpRequest) {
		xmlhttp = new XMLHttpRequest();
	} else if (window.ActiveXObject) {
		xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
	}
	if (xmlhttp==null)
	{
		  alert ("Your browser does not support AJAX!");
		  return false;
	}
	return true;	
}

/**
 * Function to show the business name.
 * comanpyName - the name of the comapny for which the business needs to be 
 * shown.	
 */
function showBusinessName(companyName)
{
	if(!initHttpReqObject()){
		return;	
	}  	
	var url="T/Drill?DD_ORG_CO_KEY="+companyName;
	url=url+"&sid="+Math.random();

	/*
		Testing: Remove Later
		alert("The URL is:"+url);	
	*/
	
	xmlhttp.onreadystatechange=populateBusinessNamesAjaxHandler;
	xmlhttp.open("GET",url,true);
	xmlhttp.send(null);
}

function showSubBusinessName(businessName)
{
	if(!initHttpReqObject()){
		return;	
	}  	
	
	var url="T/Drill?DD_ORG_BUS_KEY="+businessName;
	url=url+"&sid="+Math.random();

	/*
		Testing: Remove Later
		alert("The URL is:"+url);	
	*/
	
	
	xmlhttp.onreadystatechange=populateSubBusinessNamesAjaxHandler;
	xmlhttp.open("GET",url,true);
	xmlhttp.send(null);
}


/**
 * Function to handle the post processing of the AJAX response
 * when the call is made to Function showBusinessName
 */
function populateBusinessNamesAjaxHandler()
{
	if (xmlhttp.readyState==4)
  	{
  	  	var xmlDoc=xmlhttp.responseXML;
	  	/*
			Testing: Remove Later
			alert("The response XML is:"+xmlhttp.responseText);	
		*/
  	  	PopulateBusinessList(xmlhttp.responseXML.documentElement);
  	}
}

/**
 * Function to handle the post processing of the AJAX response
 * when the call is made to Function showSubBusinessName
 */
function populateSubBusinessNamesAjaxHandler()
{
	if (xmlhttp.readyState==4)
  	{
	  	var xmlDoc=xmlhttp.responseXML;
	  	/*
			Testing: Remove Later
			alert("The response XML is:"+xmlhttp.responseText);	
	  	*/
	  	PopulateSubBusinessList(xmlhttp.responseXML.documentElement);
	}
}

/**
 * Function to populate the drop down with the Business Names
 */
function PopulateBusinessList(BusinessNode)
{
    var businessDropDownList = $('DD_ORG_BUS_KEY');
    // Make the drop down empty
    businessDropDownList.options.length = 0;
		
    /*
	When you say var BusinessNode = BusinessNode.getElementsByTagName('Business');
	you will be getting the root element only , instead you should look out for 
	BusinessName as this is the node that will repeat and will contain the data
	*/
	//var BusinessNode = BusinessNode.getElementsByTagName('Business'); -- OLD
	var BusinessNode = BusinessNode.getElementsByTagName('BusinessName');
	var idValue;
	var textValue; 
	var optionItem;

	/*
		Testing: Remove Later
		alert("The No of BusinessName Nodes found:"+BusinessNode.length);	
	*/
	
	// populate the dropdown list with data from the xml doc
	/*
		From the example taken here are three BusinessName elements
	*/
	for (var count = 0; count < BusinessNode.length; count++)
	{
		/*
		<BusinessName id='1'>Investment Banking</BusinessName> -- BusinessNode[0]
		GetInnerText -- should yield you : Investment Banking
		BusinessNode[count].getAttribute("id") -- should yield you 1
		
		<BusinessName id='2'>Mortgage</BusinessName> -- BusinessNode[1]
		GetInnerText -- should yield you : Mortgage
		BusinessNode[count].getAttribute("id") -- should yield you 2	
		
		<BusinessName id='3'>Small Scale Industries</BusinessName> -- BusinessNode[2]
		GetInnerText -- should yield you : Small Scale Industries
		BusinessNode[count].getAttribute("id") -- should yield you 3
		*/
		textValue = GetInnerText(BusinessNode[count]);
		idValue = BusinessNode[count].getAttribute("id");
		optionItem = new Option( textValue, idValue);
		businessDropDownList.options[businessDropDownList.options.length] = optionItem;
	}
}

function PopulateSubBusinessList(SubBusinessNode)
{
	var SubBusinessDropDownList = $("DD_ORG_BUS_SUB_KEY");
	 // Make the drop down empty
    SubBusinessDropDownList.options.length = 0;
	
	var SubBusinessNode = SubBusinessNode.getElementsByTagName('SubBusinessName');

	/*
		Testing: Remove Later
		alert("The No of SubBusinessName Nodes found:"+SubBusinessNode.length);	
	*/
	
	var idValue;
	var textValue; 
	var optionItem;
	// populate the dropdown list with data from the xml doc
	for (var count = 0; count < SubBusinessNode.length; count++)
	{
		textValue = GetInnerText(SubBusinessNode[count]);
		idValue = SubBusinessNode[count].getAttribute("id");
		optionItem = new Option( textValue, idValue);
		SubBusinessDropDownList.options[SubBusinessDropDownList.options.length] = optionItem;
	}
}


function GetInnerText(node)
{
	return node.childNodes[0].nodeValue;
}


</script>
</head> 
<body> 
<form method="post" action="" name="myForm"> 
<table width="600px">
	<tr>
    	<td class="faxtext" align="right">Company Name: 
			<select name="DD_ORG_CO_KEY" id="DD_ORG_CO_KEY" onchange="showBusinessName(this.value)">
        		<option value="Please Select">Please Select</option>
				<option value="BAXTER">Baxter</option>
		  		<option value="CARDINAL">Cardinal</option>
        	</select>
        </td>
     </tr>
	 <tr>
	<tr>
		<td class="faxtext" align="right">Business Name:
 			<select name="DD_ORG_BUS_KEY" id="DD_ORG_BUS_KEY" onchange="showSubBusinessName(this.value)">
        	</select> 
 		</td>
	</tr>
	<tr>
		<td class="faxtext" align="right">Sub Business Name:
 			<select name="DD_ORG_BUS_SUB_KEY" id="DD_ORG_BUS_SUB_KEY">
    		</select>
		</td>
	</tr>
</table>
</form>	 
</body> 
</html> 
----------------------- End of the HTML File--------------------

Open in new window

0
Comment
Question by:gazdzid
  • 12
  • 5
  • 4
21 Comments
 
LVL 19

Expert Comment

by:Kuldeepchaturvedi
ID: 26168679
that code is pretty complete in itself. you only need to remove the sample pieces and may be add a where clause to your query...

your modified code will look something like below.
----------- The Servlet File:OrgDrillServlet.java ---------------
package com.testajax;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.sql.Statement;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class OrgDrillServlet
 */
public class OrgDrillServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public OrgDrillServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		String key = request.getParameter("DD_ORG_CO_KEY");
		String businessKey = request.getParameter("DD_ORG_BUS_KEY");
		
		System.out.println("DD_ORG_CO_KEY ID IS :::"+key);
		System.out.println("DD_ORG_BUS_KEY ID IS :::"+businessKey);
		
		/*
		Statement stmt= null;
		DBConnection DBConn =null;
		try{
			DBConn  = DBConnection.getInstance();
			stmt = DBConn.getStatement();
		}catch (SQLException exception){
			System.out.println("SQL Exception while connecting to DB!");    	
		} catch (InstantiationException exception) {
			System.out.println("Cannot create a DB connection!");    			
		} catch (IllegalAccessException exception) {
			System.out.println("Acess Denied to connect!");    			
		} catch (ClassNotFoundException exception) {
			System.out.println("Class not found!");    			
		}
		*/
		
		response.setContentType("text/xml");
		response.setHeader("Cache-Control", "no-cache");
		
		// If the key is null we will assume that this is a call to populate sub business names
	    if (key != null) 
	    {
	    	System.out.println("Populating the business names...");	
			String resp = "";
			resp = "<?xml version='1.0'?>";
			try {

				PrintWriter out = response.getWriter();
				// in the query part you may have to add a where clause using the keys that you have recieved from client
				 	resp = resp + "<Business>"; 
					String lsQuery = " (SELECT ORG_KEY , ORG_NAME  FROM ORG_TAB ORDER BY ORG_NAME ASC)";
					ResultSet rs=stmt.executeQuery(lsQuery);
				
					String BusinessId = "";
					String BusinessName ="";
			
					while (rs.next()) {
						BusinessId 		= rs.getString("ORG_KEY");
						BusinessName 	= rs.getString("ORG_NAME");
						resp = resp + "<BusinessName id='"+BusinessId+"'>"+BusinessName+"</BusinessName>";
	            	}
	            	resp = resp + "</Business>";	
	            
				System.out.println("The XML data retrieved is:");
				System.out.println(resp);
				
				out.write(resp);
				out.flush();
			} catch (Exception exception) {
				System.out.println("Error occured when fecthing the business names:"
						+ exception);
			}
	    }
	    // request for displaying sub business names
	    else
	    {
	    	System.out.println("Populating the sub business names...");	
			String resp = "";
			resp = "<?xml version='1.0'?>";
			
			try {

				PrintWriter out = response.getWriter();
								// in the query part you may have to add a where clause using the keys that you have recieved from client	
				resp = resp + "<Business>"; 
					String lsQuery = " (SELECT ORG_KEY , ORG_NAME  FROM ORG_TAB ORDER BY ORG_NAME ASC)";
					ResultSet rs=stmt.executeQuery(lsQuery);
				
					String BusinessId = "";
					String BusinessName ="";
			
					while (rs.next()) {
						BusinessId 		= rs.getString("ORG_KEY");
						BusinessName 	= rs.getString("ORG_NAME");
						resp = resp + "<BusinessName id='"+BusinessId+"'>"+BusinessName+"</BusinessName>";
	            	}
	            	resp = resp + "</Business>";	
	            
				System.out.println("The XML data retrieved is:");
				System.out.println(resp);
				
				out.write(resp);
				out.flush();
			} catch (Exception exception) {
				System.out.println("Error occured when fecthing the sub business names:"
						+ exception);
			}
			
	    }
	}	

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

}
-------------End of the Servlet file -------------------

Open in new window

0
 
LVL 3

Author Comment

by:gazdzid
ID: 26174002
Hello Kuldeepchaturvedi:         (Java code and js code can be found inthe code section)

Thank you for your reply!!  I did insert the code as found below.  I do not believe that the passed varible has to be used ( I could be wrong).  I do plan to use it in the future in the where clause.  I am getting an error in my js, which states line 126 char 2 'null' is null or not an object.  My actions are as follows:

1.    Uncomment code found in the try (java db connect)
2.    Addedt import java.sql.Statement; (Java)
3.    Stop Start tomcat
4.    Opened new brouser to test
* can you tell me how I can eliminate the error in my js?

The code surronding the error is as follows:

function PopulateBusinessList(BusinessNode)
{
    var businessDropDownList = $('DD_ORG_BUS_KEY');
    // Make the drop down empty
    businessDropDownList.options.length = 0;
            
    /*
      When you say var BusinessNode = BusinessNode.getElementsByTagName('Business');
      you will be getting the root element only , instead you should look out for
      BusinessName as this is the node that will repeat and will contain the data
      */
      //var BusinessNode = BusinessNode.getElementsByTagName('Business'); -- OLD
      var BusinessNode = BusinessNode.getElementsByTagName('BusinessName');
      var idValue; //**********************  Line 126    ********************************
      var textValue;
      var optionItem;
package com.testajax;



import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.*;

import java.io.*;

import javax.servlet.*;
import javax.servlet.http.*;

import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;


/**
 * Servlet implementation class OrgDrillServlet
 */
public class OrgDrillServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public OrgDrillServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		String key = request.getParameter("DD_ORG_CO_KEY");
		String businessKey = request.getParameter("DD_ORG_BUS_KEY");
		
		System.out.println("DD_ORG_CO_KEY ID IS :::"+key);
		System.out.println("DD_ORG_BUS_KEY ID IS :::"+businessKey);
		
		
		Statement stmt= null;
		DBConnection DBConn =null;
		try{
			DBConn  = DBConnection.getInstance();
			stmt = DBConn.getStatement();
		}catch (SQLException exception){
			System.out.println("SQL Exception while connecting to DB!");    	
		} catch (InstantiationException exception) {
			System.out.println("Cannot create a DB connection!");    			
		} catch (IllegalAccessException exception) {
			System.out.println("Acess Denied to connect!");    			
		} catch (ClassNotFoundException exception) {
			System.out.println("Class not found!");    			
		}
		
		
		response.setContentType("text/xml");
		response.setHeader("Cache-Control", "no-cache");
		
		// If the key is null we will assume that this is a call to populate sub business names
	    if (key != null) 
	    {
	    	System.out.println("Populating the business names...");	
			String resp = "";
			resp = "<?xml version='1.0'?>";
			try {

				PrintWriter out = response.getWriter();
				// in the query part you may have to add a where clause using the keys that you have recieved from client
				 	resp = resp + "<Business>"; 
					String lsQuery = " (SELECT ORG_KEY , ORG_NAME  FROM ORG_TAB ORDER BY ORG_NAME ASC)";
					ResultSet rs=stmt.executeQuery(lsQuery);
				
					String BusinessId = "";
					String BusinessName ="";
			
					while (rs.next()) {
						BusinessId 		= rs.getString("ORG_KEY");
						BusinessName 	= rs.getString("ORG_NAME");
						resp = resp + "<BusinessName id='"+BusinessId+"'>"+BusinessName+"</BusinessName>";
	            	}
	            	resp = resp + "</Business>";	
	            
				System.out.println("The XML data retrieved is:");
				System.out.println(resp);
				
				out.write(resp);
				out.flush();
			} catch (Exception exception) {
				System.out.println("Error occured when fecthing the business names:"
						+ exception);
			}
	    }
	    // request for displaying sub business names
	    else
	    {
	    	System.out.println("Populating the sub business names...");	
			String resp = "";
			resp = "<?xml version='1.0'?>";
			
			try {

				PrintWriter out = response.getWriter();
								// in the query part you may have to add a where clause using the keys that you have recieved from client	
				resp = resp + "<Business>"; 
					String lsQuery = " (SELECT ORG_KEY , ORG_NAME  FROM ORG_TAB ORDER BY ORG_NAME ASC)";
					ResultSet rs=stmt.executeQuery(lsQuery);
				
					String BusinessId = "";
					String BusinessName ="";
			
					while (rs.next()) {
						BusinessId 		= rs.getString("ORG_KEY");
						BusinessName 	= rs.getString("ORG_NAME");
						resp = resp + "<BusinessName id='"+BusinessId+"'>"+BusinessName+"</BusinessName>";
	            	}
	            	resp = resp + "</Business>";	
	            
				System.out.println("The XML data retrieved is:");
				System.out.println(resp);
				
				out.write(resp);
				out.flush();
			} catch (Exception exception) {
				System.out.println("Error occured when fecthing the sub business names:"
						+ exception);
			}
			
	    }
	}	

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

}






var xmlhttp;

/**
 * Function to return the reference to the object by passing the Id of the 
 * object
 */
function $(elementId){
	return document.getElementById(elementId);
}

/**
 * Function to initialize the http xml request object.
 * The function will return true if the object is valid else will
 * return false	
 */
function initHttpReqObject()
{
	if (window.XMLHttpRequest) {
		xmlhttp = new XMLHttpRequest();
	} else if (window.ActiveXObject) {
		xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
	}
	if (xmlhttp==null)
	{
		  alert ("Your browser does not support AJAX!");
		  return false;
	}
	return true;	
}

/**
 * Function to show the business name.
 * comanpyName - the name of the comapny for which the business needs to be 
 * shown.	
 */
function showBusinessName(companyName)
{
	if(!initHttpReqObject()){
		return;	
	}  	
	var url="T/Drill?DD_ORG_CO_KEY="+companyName;
	url=url+"&sid="+Math.random();

	/*
		Testing: Remove Later
		alert("The URL is:"+url);	
	*/
	
	xmlhttp.onreadystatechange=populateBusinessNamesAjaxHandler;
	xmlhttp.open("GET",url,true);
	xmlhttp.send(null);
}

function showSubBusinessName(businessName)
{
	if(!initHttpReqObject()){
		return;	
	}  	
	
	var url="T/Drill?DD_ORG_BUS_KEY="+businessName;
	url=url+"&sid="+Math.random();

	/*
		Testing: Remove Later
		alert("The URL is:"+url);	
	*/
	
	
	xmlhttp.onreadystatechange=populateSubBusinessNamesAjaxHandler;
	xmlhttp.open("GET",url,true);
	xmlhttp.send(null);
}


/**
 * Function to handle the post processing of the AJAX response
 * when the call is made to Function showBusinessName
 */
function populateBusinessNamesAjaxHandler()
{
	if (xmlhttp.readyState==4)
  	{
  	  	var xmlDoc=xmlhttp.responseXML;
	  	/*
			Testing: Remove Later
			alert("The response XML is:"+xmlhttp.responseText);	
		*/
  	  	PopulateBusinessList(xmlhttp.responseXML.documentElement);
  	}
}

/**
 * Function to handle the post processing of the AJAX response
 * when the call is made to Function showSubBusinessName
 */
function populateSubBusinessNamesAjaxHandler()
{
	if (xmlhttp.readyState==4)
  	{
	  	var xmlDoc=xmlhttp.responseXML;
	  	/*
			Testing: Remove Later
			alert("The response XML is:"+xmlhttp.responseText);	
	  	*/
	  	PopulateSubBusinessList(xmlhttp.responseXML.documentElement);
	}
}

/**
 * Function to populate the drop down with the Business Names
 */
function PopulateBusinessList(BusinessNode)
{
    var businessDropDownList = $('DD_ORG_BUS_KEY');
    // Make the drop down empty
    businessDropDownList.options.length = 0;
		
    /*
	When you say var BusinessNode = BusinessNode.getElementsByTagName('Business');
	you will be getting the root element only , instead you should look out for 
	BusinessName as this is the node that will repeat and will contain the data
	*/
	//var BusinessNode = BusinessNode.getElementsByTagName('Business'); -- OLD
	var BusinessNode = BusinessNode.getElementsByTagName('BusinessName');
	var idValue; //**********************  Line 126    ********************************
	var textValue; 
	var optionItem;

	/*
		Testing: Remove Later
		alert("The No of BusinessName Nodes found:"+BusinessNode.length);	
	*/
	
	// populate the dropdown list with data from the xml doc
	/*
		From the example taken here are three BusinessName elements
	*/
	for (var count = 0; count < BusinessNode.length; count++)
	{
		/*
		<BusinessName id='1'>Investment Banking</BusinessName> -- BusinessNode[0]
		GetInnerText -- should yield you : Investment Banking
		BusinessNode[count].getAttribute("id") -- should yield you 1
		
		<BusinessName id='2'>Mortgage</BusinessName> -- BusinessNode[1]
		GetInnerText -- should yield you : Mortgage
		BusinessNode[count].getAttribute("id") -- should yield you 2	
		
		<BusinessName id='3'>Small Scale Industries</BusinessName> -- BusinessNode[2]
		GetInnerText -- should yield you : Small Scale Industries
		BusinessNode[count].getAttribute("id") -- should yield you 3
		*/
		textValue = GetInnerText(BusinessNode[count]);
		idValue = BusinessNode[count].getAttribute("id");
		optionItem = new Option( textValue, idValue);
		businessDropDownList.options[businessDropDownList.options.length] = optionItem;
	}
}

function PopulateSubBusinessList(SubBusinessNode)
{
	var SubBusinessDropDownList = $("DD_ORG_BUS_SUB_KEY");
	 // Make the drop down empty
    SubBusinessDropDownList.options.length = 0;
	
	var SubBusinessNode = SubBusinessNode.getElementsByTagName('SubBusinessName');

	/*
		Testing: Remove Later
		alert("The No of SubBusinessName Nodes found:"+SubBusinessNode.length);	
	*/
	
	var idValue;
	var textValue; 
	var optionItem;
	// populate the dropdown list with data from the xml doc
	for (var count = 0; count < SubBusinessNode.length; count++)
	{
		textValue = GetInnerText(SubBusinessNode[count]);
		idValue = SubBusinessNode[count].getAttribute("id");
		optionItem = new Option( textValue, idValue);
		SubBusinessDropDownList.options[SubBusinessDropDownList.options.length] = optionItem;
	}
}


function GetInnerText(node)
{
	return node.childNodes[0].nodeValue;
}

Open in new window

0
 
LVL 22

Expert Comment

by:kadaba
ID: 26174003
Sorry for the delay in reply.

Yes put your query in place and the rest should follow... and a point mentioned by kuldeep about the where clause which would include the company name/ business name as a condition.

let us know.
0
Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

 
LVL 22

Expert Comment

by:kadaba
ID: 26174050
In the console , did you see the xml being printed.. what does it look like.

The XML data retrieved is:.... ?
0
 
LVL 3

Author Comment

by:gazdzid
ID: 26174320

Hello kadaba and Kuldeepchaturvedi:
kadaba states:
Yes put your query in place and the rest should follow... and a point mentioned by kuldeep about the where clause which would include the company name/ business name as a condition.

You both seem to agree that the value passed neesds to be used as a result of both comments, I did open a new question, which can be found below (but please continue to help me with this question.  Thanks!!

http://www.experts-exchange.com/Programming/Languages/Java/J2EE/JSP/Q_25018587.html
0
 
LVL 3

Author Comment

by:gazdzid
ID: 26174533
kadaba:You stated:
in the console , did you see the xml being printed.. what does it look like.The XML data retrieved is:.... ?

I am testing my code through brouser using localhost.  I am not sure how to configure my ide such that I can view results on the console.  I am using application server toolkit, V6.0
0
 
LVL 22

Expert Comment

by:kadaba
ID: 26174681
There would be an option in your IDE where you can see the console

Blind shot :

You will have a bunch of options at the top of the IDE, In that
Window >> Show View >> Console

You will be able to see the console. Run your application and check the console for the output.

If the above fails then

alert("The response XML is:"+xmlhttp.responseText);
PopulateSubBusinessList(xmlhttp.responseXML.documentElement);

      and check the content of the alert

0
 
LVL 3

Author Comment

by:gazdzid
ID: 26174766
Hello Kadaba,

based on your response >>does the value have to be used? - NO not necessarily, If you agree with the above logic you will use it. Else all business Names and Sub Business Names will be populated.
and code provided in previous question.

My select statent should not be the issue.  How do I get the dynamic return for business dropdown currently I am receiving a null value.  i do believe that this should not be to difficult based on your assistance from previous question.  It seems as though instead of static values I need to incorporate the select statement but I am not sure how to do that.  Can you help?  Thanks in advance!!
0
 
LVL 3

Author Comment

by:gazdzid
ID: 26174891
Hello Kadaba,

lets separate the consolwe question see new question below

http://www.experts-exchange.com/Programming/Languages/Java/J2EE/JSP/Q_25018817.html
0
 
LVL 3

Author Comment

by:gazdzid
ID: 26175135
Kadaba:
can we keep test using alerts on the browser?
Wen using:
alert("The response XML is:"+xmlhttp.responseText);
popup is
"browser response is"
0
 
LVL 22

Expert Comment

by:kadaba
ID: 26175182
Yes we can but it will take time to find out the cause of issue if any in the java code as we cant get hold of errors in the java layer.like connection to DB failed , execution of query failed, run time errors etc

Have you tested connecting to the database and retrieving the records etc?
0
 
LVL 3

Author Comment

by:gazdzid
ID: 26175626
Hello Kadaba:
You wrote:
Have you tested connecting to the database and retrieving the records etc?
I opened a new question:
http://www.experts-exchange.com/Programming/Languages/Java/J2EE/JSP/Q_25018981.html

Could you look at the response that you provided and tell me how to change it such that if the connection strings are corect then the select statement would work?
The solution you provided for static dropdowns is as follows:
----------- The Servlet File:OrgDrillServlet.java ---------------
package com.testajax;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.sql.Statement;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class OrgDrillServlet
 */
public class OrgDrillServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public OrgDrillServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		String key = request.getParameter("DD_ORG_CO_KEY");
		String businessKey = request.getParameter("DD_ORG_BUS_KEY");
		
		System.out.println("DD_ORG_CO_KEY ID IS :::"+key);
		System.out.println("DD_ORG_BUS_KEY ID IS :::"+businessKey);
		
		/*
		Statement stmt= null;
		DBConnection DBConn =null;
		try{
			DBConn  = DBConnection.getInstance();
			stmt = DBConn.getStatement();
		}catch (SQLException exception){
			System.out.println("SQL Exception while connecting to DB!");    	
		} catch (InstantiationException exception) {
			System.out.println("Cannot create a DB connection!");    			
		} catch (IllegalAccessException exception) {
			System.out.println("Acess Denied to connect!");    			
		} catch (ClassNotFoundException exception) {
			System.out.println("Class not found!");    			
		}
		*/
		
		response.setContentType("text/xml");
		response.setHeader("Cache-Control", "no-cache");
		
		// If the key is null we will assume that this is a call to populate sub business names
	    if (key != null) 
	    {
	    	System.out.println("Populating the business names...");	
			String resp = "";
			resp = "<?xml version='1.0'?>";
			try {

				PrintWriter out = response.getWriter();
				
				/*
				 	resp = resp + "<Business>"; 
					String lsQuery = " (SELECT ORG_KEY , ORG_NAME  FROM ORG_TAB ORDER BY ORG_NAME ASC)";
					ResultSet rs=stmt.executeQuery(lsQuery);
				
					String BusinessId = "";
					String BusinessName ="";
			
					while (rs.next()) {
						BusinessId 		= rs.getString("ORG_KEY");
						BusinessName 	= rs.getString("ORG_NAME");
						resp = resp + "<BusinessName id='"+BusinessId+"'>"+BusinessName+"</BusinessName>";
	            	}
	            	resp = resp + "</Business>";	
	            */
				
				/*
				 * Example block of code which would be
				 * derived from the Data base as above
				 */
				resp = resp + "<Business>";
				resp = resp + "<BusinessName id='1'>Investment Banking</BusinessName>";
				resp = resp + "<BusinessName id='2'>Mortgage</BusinessName>";
				resp = resp + "<BusinessName id='3'>Small Scale Industries</BusinessName>";
				resp = resp + "</Business>";
				
				System.out.println("The XML data retrieved is:");
				System.out.println(resp);
				
				out.write(resp);
				out.flush();
			} catch (Exception exception) {
				System.out.println("Error occured when fecthing the business names:"
						+ exception);
			}
	    }
	    // request for displaying sub business names
	    else
	    {
	    	System.out.println("Populating the sub business names...");	
			String resp = "";
			resp = "<?xml version='1.0'?>";
			
			try {

				PrintWriter out = response.getWriter();
					
				/*
				 * Example block of code which would be
				 * derived from the Data base 
				 */
				resp = resp + "<Business>";
				resp = resp + "<SubBusinessName id='1'>Sub - Investment Banking</SubBusinessName>";
				resp = resp + "<SubBusinessName id='2'>Sub - Mortgage</SubBusinessName>";
				resp = resp + "<SubBusinessName id='3'>Sub - Small Scale Industries</SubBusinessName>";
				resp = resp + "</Business>";
				
				System.out.println("The XML data retrieved is:");
				System.out.println(resp);
				
				out.write(resp);
				out.flush();
			} catch (Exception exception) {
				System.out.println("Error occured when fecthing the sub business names:"
						+ exception);
			}
			
	    }
	}	

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

}
-------------End of the Servlet file -------------------

------------ The HTML File-------------------------------
<html> 
<head> 
<title>AJAX Drill Test</title>
<script type="text/javascript">
var xmlhttp;

/**
 * Function to return the reference to the object by passing the Id of the 
 * object
 */
function $(elementId){
	return document.getElementById(elementId);
}

/**
 * Function to initialize the http xml request object.
 * The function will return true if the object is valid else will
 * return false	
 */
function initHttpReqObject()
{
	if (window.XMLHttpRequest) {
		xmlhttp = new XMLHttpRequest();
	} else if (window.ActiveXObject) {
		xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
	}
	if (xmlhttp==null)
	{
		  alert ("Your browser does not support AJAX!");
		  return false;
	}
	return true;	
}

/**
 * Function to show the business name.
 * comanpyName - the name of the comapny for which the business needs to be 
 * shown.	
 */
function showBusinessName(companyName)
{
	if(!initHttpReqObject()){
		return;	
	}  	
	var url="T/Drill?DD_ORG_CO_KEY="+companyName;
	url=url+"&sid="+Math.random();

	/*
		Testing: Remove Later
		alert("The URL is:"+url);	
	*/
	
	xmlhttp.onreadystatechange=populateBusinessNamesAjaxHandler;
	xmlhttp.open("GET",url,true);
	xmlhttp.send(null);
}

function showSubBusinessName(businessName)
{
	if(!initHttpReqObject()){
		return;	
	}  	
	
	var url="T/Drill?DD_ORG_BUS_KEY="+businessName;
	url=url+"&sid="+Math.random();

	/*
		Testing: Remove Later
		alert("The URL is:"+url);	
	*/
	
	
	xmlhttp.onreadystatechange=populateSubBusinessNamesAjaxHandler;
	xmlhttp.open("GET",url,true);
	xmlhttp.send(null);
}


/**
 * Function to handle the post processing of the AJAX response
 * when the call is made to Function showBusinessName
 */
function populateBusinessNamesAjaxHandler()
{
	if (xmlhttp.readyState==4)
  	{
  	  	var xmlDoc=xmlhttp.responseXML;
	  	/*
			Testing: Remove Later
			alert("The response XML is:"+xmlhttp.responseText);	
		*/
  	  	PopulateBusinessList(xmlhttp.responseXML.documentElement);
  	}
}

/**
 * Function to handle the post processing of the AJAX response
 * when the call is made to Function showSubBusinessName
 */
function populateSubBusinessNamesAjaxHandler()
{
	if (xmlhttp.readyState==4)
  	{
	  	var xmlDoc=xmlhttp.responseXML;
	  	/*
			Testing: Remove Later
			alert("The response XML is:"+xmlhttp.responseText);	
	  	*/
	  	PopulateSubBusinessList(xmlhttp.responseXML.documentElement);
	}
}

/**
 * Function to populate the drop down with the Business Names
 */
function PopulateBusinessList(BusinessNode)
{
    var businessDropDownList = $('DD_ORG_BUS_KEY');
    // Make the drop down empty
    businessDropDownList.options.length = 0;
		
    /*
	When you say var BusinessNode = BusinessNode.getElementsByTagName('Business');
	you will be getting the root element only , instead you should look out for 
	BusinessName as this is the node that will repeat and will contain the data
	*/
	//var BusinessNode = BusinessNode.getElementsByTagName('Business'); -- OLD
	var BusinessNode = BusinessNode.getElementsByTagName('BusinessName');
	var idValue;
	var textValue; 
	var optionItem;

	/*
		Testing: Remove Later
		alert("The No of BusinessName Nodes found:"+BusinessNode.length);	
	*/
	
	// populate the dropdown list with data from the xml doc
	/*
		From the example taken here are three BusinessName elements
	*/
	for (var count = 0; count < BusinessNode.length; count++)
	{
		/*
		<BusinessName id='1'>Investment Banking</BusinessName> -- BusinessNode[0]
		GetInnerText -- should yield you : Investment Banking
		BusinessNode[count].getAttribute("id") -- should yield you 1
		
		<BusinessName id='2'>Mortgage</BusinessName> -- BusinessNode[1]
		GetInnerText -- should yield you : Mortgage
		BusinessNode[count].getAttribute("id") -- should yield you 2	
		
		<BusinessName id='3'>Small Scale Industries</BusinessName> -- BusinessNode[2]
		GetInnerText -- should yield you : Small Scale Industries
		BusinessNode[count].getAttribute("id") -- should yield you 3
		*/
		textValue = GetInnerText(BusinessNode[count]);
		idValue = BusinessNode[count].getAttribute("id");
		optionItem = new Option( textValue, idValue);
		businessDropDownList.options[businessDropDownList.options.length] = optionItem;
	}
}

function PopulateSubBusinessList(SubBusinessNode)
{
	var SubBusinessDropDownList = $("DD_ORG_BUS_SUB_KEY");
	 // Make the drop down empty
    SubBusinessDropDownList.options.length = 0;
	
	var SubBusinessNode = SubBusinessNode.getElementsByTagName('SubBusinessName');

	/*
		Testing: Remove Later
		alert("The No of SubBusinessName Nodes found:"+SubBusinessNode.length);	
	*/
	
	var idValue;
	var textValue; 
	var optionItem;
	// populate the dropdown list with data from the xml doc
	for (var count = 0; count < SubBusinessNode.length; count++)
	{
		textValue = GetInnerText(SubBusinessNode[count]);
		idValue = SubBusinessNode[count].getAttribute("id");
		optionItem = new Option( textValue, idValue);
		SubBusinessDropDownList.options[SubBusinessDropDownList.options.length] = optionItem;
	}
}


function GetInnerText(node)
{
	return node.childNodes[0].nodeValue;
}


</script>
</head> 
<body> 
<form method="post" action="" name="myForm"> 
<table width="600px">
	<tr>
    	<td class="faxtext" align="right">Company Name: 
			<select name="DD_ORG_CO_KEY" id="DD_ORG_CO_KEY" onchange="showBusinessName(this.value)">
        		<option value="Please Select">Please Select</option>
				<option value="BAXTER">Baxter</option>
		  		<option value="CARDINAL">Cardinal</option>
        	</select>
        </td>
     </tr>
	 <tr>
	<tr>
		<td class="faxtext" align="right">Business Name:
 			<select name="DD_ORG_BUS_KEY" id="DD_ORG_BUS_KEY" onchange="showSubBusinessName(this.value)">
        	</select> 
 		</td>
	</tr>
	<tr>
		<td class="faxtext" align="right">Sub Business Name:
 			<select name="DD_ORG_BUS_SUB_KEY" id="DD_ORG_BUS_SUB_KEY">
    		</select>
		</td>
	</tr>
</table>
</form>	 
</body> 
</html> 
----------------------- End of the HTML File--------------------
 
    

    

A 
    
Author Comments:

Open in new window

0
 
LVL 3

Author Comment

by:gazdzid
ID: 26175665
This question was opened as I have attempted to alter the js and java sections that create the static dropdowns and uncomment the sections that appear to create the dynamic but still resulting in a 'null'
0
 
LVL 19

Expert Comment

by:Kuldeepchaturvedi
ID: 26177437
Sorry for delayed response, but I guess we are in diff time zones..

Anyway, as Kadaba is saying were you able to look at the console ? if you are using tomcat , you can find it in log directory, your filename would be stdout.log or stdout.txt there. ( there will be other files also with name stderr look at them also)..

your js is getting null values because that servlet is failing somewhere ( either in database connection or in xml creation). look at these two files and let us know what you find.
0
 
LVL 22

Accepted Solution

by:
kadaba earned 1000 total points
ID: 26178128
I have replied in the other post, once you will be able to connect to the DB it should work fine.
I will be monitoring the posts.
0
 
LVL 3

Author Comment

by:gazdzid
ID: 26204535
Kuldeepchaturvedi: and Kadaba:

Using the code found below my Netbeans console appears show that my DBUtil.java compiles and execute correctly.  The out put is as follows:

run:
entering getDBConnection
Connection *a* establised!
oracle.jdbc.driver.T4CConnection@xxxxxx
exiting getDBConnection
Connection *b* establised!
BUILD SUCCESSFUL (total time: 1 second)

I am still receiving a js error of  "Line 128 Char 2 Error 'null' is null or not an object.  
Can help me figure out why?  Thanks!!
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package com.testajax;
 import java.sql.Connection;
import java.sql.DriverManager;

/**
 *
 * @author gazdzid
 */
public class DBUtil {



    /**
     * This method will establish a connection to the DB
     *
     * @return <tt>Connection</tt> object which will hold an active connection
     */
    public static Connection getDBConnection()
    {
	System.out.println("entering getDBConnection");

	Connection conn = null;
	
	try
	{
            Class.forName("oracle.jdbc.driver.OracleDriver").newInstance();
            conn = DriverManager.getConnection("jdbc:oracle:thin:@XXXXXXXXXX:XXXXX","XXXXXX","XXXXXXXXXx");


	    System.out.println("Connection *a* establised!");
            System.out.println(conn);

	} catch (Exception exception)
	{

	    System.out.println("Could *a* not connect!");
	    System.out.println("Error:"+exception);

	   conn = null;
	} finally
	{

	}

	System.out.println("exiting getDBConnection");

	return conn;
    }

    /**
     * This is a test method to test the connection to the DB
     *
     * @return nothing
     */
    public static void main(String args[])
    {
	Connection conn =DBUtil.getDBConnection();

	if (null == conn)
	{
           
	    System.out.println("Could *b* not connect!");
	} else
	{
	    System.out.println("Connection *b* establised!");
	}
    }
}

Open in new window

0
 
LVL 19

Expert Comment

by:Kuldeepchaturvedi
ID: 26207374
did you get a chance to look into the stderr and stdout files ? ( i.e. console and error log on the server side)...  

Also can you post your full code as it stands now?
Now we know that the DBUtil works, We know that the JS and JSP also works ( because we tested it with static values)..
Only thing left to check is the servlet..

0
 
LVL 3

Author Comment

by:gazdzid
ID: 26239198
Kuldeepchaturvedi:You stated
Now we know that the DBUtil works, We know that the JS and JSP also works ( because we tested it with static values)..
Only thing left to check is the servlet..

My reply
What I can say is the DBUtil does work
I believe that my js may need some review
Next I may need help working on my OrgDrillServlet.java

============================================================
Kuldeepchaturvedi:You stated

did you get a chance to look into the stderr and stdout files ? ( i.e. console and error log on the server side)...  
stderr file is blank

stdout file shows:
DD_ORG_CO_KEY ID IS :::CARDINAL
DD_ORG_BUS_KEY ID IS :::null
entering getDBConnection
Connection *a* establised!
oracle.jdbc.driver.T4CConnection@e35bb7
exiting getDBConnection
Populating the business names...
Error occured when fecthing the business names:java.lang.NullPointerException

===========================================================================
Alert #1 shows - The URL is::::T/Drill?DD_ORG_CO_KEY=BAXTER
Alert#2 shows - ReadyState is equal to:::: 4
Alert#3 shows - The response XML is::::
Alert#4 shows - The response XML is::::
JS - error shows -Line 132 char 2 'null' is null or not an object

Found in the code section is js, html, OrgDrillServlet.java, DBUtil.java
============JS File  OrgDrill.js=======================


var xmlhttp;

/**
 * Function to return the reference to the object by passing the Id of the 
 * object
 */
function $(elementId){
	return document.getElementById(elementId);
}

/**
 * Function to initialize the http xml request object.
 * The function will return true if the object is valid else will
 * return false	
 */
function initHttpReqObject()
{
	if (window.XMLHttpRequest) {
		xmlhttp = new XMLHttpRequest();
	} else if (window.ActiveXObject) {
		xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
	}
	if (xmlhttp==null)
	{
		  alert ("Your browser does not support AJAX!");
		  return false;
	}
	return true;	
}

/**
 * Function to show the business name.
 * comanpyName - the name of the comapny for which the business needs to be 
 * shown.	
 */
function showBusinessName(companyName)
{
	if(!initHttpReqObject()){
		return;	
	}  	
	var url="T/Drill?DD_ORG_CO_KEY="+companyName;
	//url=url+"&sid="+Math.random();


		//Testing: Remove Later
		alert("(1) - The URL is:::::  "+url);	

	
	xmlhttp.onreadystatechange=populateBusinessNamesAjaxHandler;
	xmlhttp.open("GET",url,true);
	xmlhttp.send(null);
}

function showSubBusinessName(businessName)
{
	if(!initHttpReqObject()){
		return;	
	}  	
	
	var url="T/Drill?DD_ORG_BUS_KEY="+businessName;
	url=url+"&sid="+Math.random();

	/*
		Testing: Remove Later
		alert("The URL is:"+url);	
	*/
	
	
	xmlhttp.onreadystatechange=populateSubBusinessNamesAjaxHandler;
	xmlhttp.open("GET",url,true);
	xmlhttp.send(null);
}


/**
 * Function to handle the post processing of the AJAX response
 * when the call is made to Function showBusinessName
 */
function populateBusinessNamesAjaxHandler()
{
	if (xmlhttp.readyState==4)
	alert("(2) - Ready State is equal to ::::   " + xmlhttp.readyState)
	
  	{
  	  	var xmlDoc=xmlhttp.responseXML;
	  
			//Testing: Remove Later
			//alert("(2) - Ready State is equal to ::::   " + xmlhttp.readyState)
			alert("(3) - The response XML is::::   "+xmlhttp.responseText);	
			//alert("(3.1) - The response XML is::::   "+xmlDoc);	
		
  	  	PopulateBusinessList(xmlhttp.responseXML.documentElement);
  	}
}

/**
 * Function to handle the post processing of the AJAX response
 * when the call is made to Function showSubBusinessName
 */
function populateSubBusinessNamesAjaxHandler()
{
	if (xmlhttp.readyState==4)
  	{
	  	var xmlDoc=xmlhttp.responseXML;
	
			//Testing: Remove Later
			alert("The response XML is:"+xmlhttp.responseText);	
	
	  	PopulateSubBusinessList(xmlhttp.responseXML.documentElement);
	}
}

/**
 * Function to populate the drop down with the Business Names
 */
function PopulateBusinessList(BusinessNode)
{
alert("(4) - The response XML is:::: "+xmlhttp.responseText);  

    var businessDropDownList = $('DD_ORG_BUS_KEY');
    // Make the drop down empty
    businessDropDownList.options.length = 0;
		
    /*
	When you say var BusinessNode = BusinessNode.getElementsByTagName('Business');
	you will be getting the root element only , instead you should look out for 
	BusinessName as this is the node that will repeat and will contain the data
	*/
	//var BusinessNode = BusinessNode.getElementsByTagName('Business'); -- OLD
	var BusinessNode = BusinessNode.getElementsByTagName('BusinessName');
	var idValue; //**********************  Line 126    ********************************
	var textValue; 
	var optionItem;

	/*
		Testing: Remove Later
		alert("The No of BusinessName Nodes found:"+BusinessNode.length);	
	*/
	
	// populate the dropdown list with data from the xml doc
	/*
		From the example taken here are three BusinessName elements
	*/
	for (var count = 0; count < BusinessNode.length; count++)
	{
		/*
		<BusinessName id='1'>Investment Banking</BusinessName> -- BusinessNode[0]
		GetInnerText -- should yield you : Investment Banking
		BusinessNode[count].getAttribute("id") -- should yield you 1
		
		<BusinessName id='2'>Mortgage</BusinessName> -- BusinessNode[1]
		GetInnerText -- should yield you : Mortgage
		BusinessNode[count].getAttribute("id") -- should yield you 2	
		
		<BusinessName id='3'>Small Scale Industries</BusinessName> -- BusinessNode[2]
		GetInnerText -- should yield you : Small Scale Industries
		BusinessNode[count].getAttribute("id") -- should yield you 3
		*/
		textValue = GetInnerText(BusinessNode[count]);
		idValue = BusinessNode[count].getAttribute("id");
		optionItem = new Option( textValue, idValue);
		businessDropDownList.options[businessDropDownList.options.length] = optionItem;
	}
}

function PopulateSubBusinessList(SubBusinessNode)
{
	var SubBusinessDropDownList = $("DD_ORG_BUS_SUB_KEY");
	 // Make the drop down empty
    SubBusinessDropDownList.options.length = 0;
	
	var SubBusinessNode = SubBusinessNode.getElementsByTagName('SubBusinessName');

	/*
		Testing: Remove Later
		alert("The No of SubBusinessName Nodes found:"+SubBusinessNode.length);	
	*/
	
	var idValue;
	var textValue; 
	var optionItem;
	// populate the dropdown list with data from the xml doc
	for (var count = 0; count < SubBusinessNode.length; count++)
	{
		textValue = GetInnerText(SubBusinessNode[count]);
		idValue = SubBusinessNode[count].getAttribute("id");
		optionItem = new Option( textValue, idValue);
		SubBusinessDropDownList.options[SubBusinessDropDownList.options.length] = optionItem;
	}
}


function GetInnerText(node)
{
	return node.childNodes[0].nodeValue;
}
==================end of JS===========================

==================OrgDrill.html=======================

<html> 
<head> 
<script src="OrgDrill.js"></script> 
<title>Hello World</title> 
</head> 
<body> 
 
<form method="post" action="" name="myForm"> 
<table width="600px">
	<tr>
    	<td class="faxtext" align="right">Company Name: 
			<select name="DD_ORG_CO_KEY" id="DD_ORG_CO_KEY" onchange="showBusinessName(this.value)">
        		<option value="Please Select">Please Select</option>
				<option value="BAXTER">Baxter</option>
		  		<option value="CARDINAL">Cardinal</option>
        	</select>
        </td>
     </tr>
	 <tr>
	<tr>
		<td class="faxtext" align="right">Business Name:
 			<select name="DD_ORG_BUS_KEY" id="DD_ORG_BUS_KEY" onchange="showSubBusinessName(this.value)">
        	</select> 
 		</td>
	</tr>
	<tr>
		<td class="faxtext" align="right">Sub Business Name:
 			<select name="DD_ORG_BUS_SUB_KEY" id="DD_ORG_BUS_SUB_KEY">
    		</select>
		</td>
	</tr>
</table>
</form>	 
</body> 
</html> 
=========================end of html======================

=========================OrgDrillServlet.java===============

package com.testajax;



import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.*;

import java.io.*;

import javax.servlet.*;
import javax.servlet.http.*;

import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;


/**
 * Servlet implementation class OrgDrillServlet
 */
public class OrgDrillServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public OrgDrillServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		String key = request.getParameter("DD_ORG_CO_KEY");
		String businessKey = request.getParameter("DD_ORG_BUS_KEY");
		
		System.out.println("DD_ORG_CO_KEY ID IS :::"+key);
		System.out.println("DD_ORG_BUS_KEY ID IS :::"+businessKey);
		//Connection conn =DBUtil.getDBConnection();
		
		Statement stmt= null;
		//DBConnection Conn =null;
		DBUtil Conn = null;
		try{
			Connection conn =DBUtil.getDBConnection();
			
		}catch (Exception exception){
			System.out.println("SQL Exception while connecting to DB!");    	
		}
		
		
		response.setContentType("text/xml");
		response.setHeader("Cache-Control", "no-cache");
		
		// If the key is null we will assume that this is a call to populate sub business names
		//Initially key will not be null
	    if (key != null) 
	    {
	    	System.out.println("Populating the business names...");	
			String resp = "";
			resp = "<?xml version='1.0'?>";
			try {

				PrintWriter out = response.getWriter();
				// in the query part you may have to add a where clause using the keys that you have recieved from client
				 	resp = resp + "<Business>"; 
					String lsQuery = " (SELECT ORG_KEY , ORG_NAME  FROM ORG_TAB ORDER BY ORG_NAME ASC)";
					ResultSet rs=stmt.executeQuery(lsQuery);
				
					String BusinessId = "";
					String BusinessName ="";
			
					while (rs.next()) {
						BusinessId 		= rs.getString("ORG_KEY");
						BusinessName 	= rs.getString("ORG_NAME");
						resp = resp + "<BusinessName id='"+BusinessId+"'>"+BusinessName+"</BusinessName>";
	            	}
	            	resp = resp + "</Business>";	
	            
				System.out.println("The XML data retrieved is:");
				System.out.println(resp);
				
				out.write(resp);
				out.flush();
				
			} catch (Exception exception) {
				System.out.println("Error occured when fecthing the business names:"
						+ exception);
			}
	    }
	    // request for displaying sub business names
	    else
	    {
	    	
			
	    }
	}	

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

}
=========================end ods.java======================


========================DBUtil.java========================


/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package com.testajax;
 import java.sql.Connection;
import java.sql.DriverManager;

/**
 *
 * @author gazdzid
 */
public class DBUtil {



    /**
     * This method will establish a connection to the DB
     *
     * @return <tt>Connection</tt> object which will hold an active connection
     */
    public static Connection getDBConnection()
    {
	System.out.println("entering getDBConnection");

	Connection conn = null;
	
	try
	{
            Class.forName("oracle.jdbc.driver.OracleDriver").newInstance();
            conn = DriverManager.getConnection("jdbc:oracle:thin:@xxxx:xxx","xxx","xxxx");


	    System.out.println("Connection *a* establised!");
            System.out.println(conn);

	} catch (Exception exception)
	{

	    System.out.println("Could *a* not connect!");
	    System.out.println("Error:"+exception);

	   conn = null;
	} finally
	{

	}

	System.out.println("exiting getDBConnection");

	return conn;
    }

    /**
     * This is a test method to test the connection to the DB
     *
     * @return nothing
     */
    public static void main(String args[])
    {
	Connection conn =DBUtil.getDBConnection();

	if (null == conn)
	{
           
	    System.out.println("Could *b* not connect!");
	} else
	{
	    System.out.println("Connection *b* establised!");
	}
    }
}

Open in new window

0
 
LVL 19

Assisted Solution

by:Kuldeepchaturvedi
Kuldeepchaturvedi earned 1000 total points
ID: 26263738
I see whats wrong here..

we have created the connection and then never created the statement before using it..

you are missing only one line in your servlet.

Statement stmt= null;
            //DBConnection Conn =null;
            DBUtil Conn = null;
            try{
                  Connection conn =DBUtil.getDBConnection();
                        stmt = conn.createStatement(); //this is the added line rest of the code remains the same.
                  
            }catch (Exception exception){
                  System.out.println("SQL Exception while connecting to DB!");          
            }


make this change and look at the console log again. it should be working.
0
 
LVL 3

Author Comment

by:gazdzid
ID: 26273051
Hello  Kuldeepchaturvedi:
you stated:
Add the followin line of code
 stmt = conn.createStatement(); //this

I did add the line of code and found within the stdout file.  
DD_ORG_CO_KEY ID IS :::CARDINAL
DD_ORG_BUS_KEY ID IS :::null
entering getDBConnection
Connection *a* establised!
oracle.jdbc.driver.T4CConnection@4ee70b
exiting getDBConnection
Populating the business names...
Error occured when fecthing the business names:java.sql.SQLException: ORA-00907: missing right parenthesis

After reviewing OrgDrillServlet.java and DBUtil.java, I did net see a missing parenparenthesis. I wiil continue yo llok for issues.


0
 
LVL 3

Author Closing Comment

by:gazdzid
ID: 31674989
Hello Kuldeepchaturvedi: and Kadaba:

I want to thank the both for you time, assistace and expertise!!  It appears that I did get it to work after adding

stmt = conn.createStatement(); //this is the added line rest of the code remains the same.

                  and also

String lsQuery = " (SELECT ORG_KEY , ORG_NAME  FROM ORG_TAB ORDER BY ORG_NAME ASC)";
 
                        was changed to

String lsQuery = "(SELECT ORG_KEY , ORG_NAME  FROM ORG_TAB)";
0

Featured Post

Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

The Confluence of Individual Knowledge and the Collective Intelligence At this writing (summer 2013) the term API (http://dictionary.reference.com/browse/API?s=t) has made its way into the popular lexicon of the English language.  A few years ago, …
I found this questions asking how to do this in many different forums, so I will describe here how to implement a solution using PHP and AJAX. The logical flow for the problem should be: Write an event handler for the first drop down box to get …
The viewer will learn how to implement Singleton Design Pattern in Java.
This tutorial covers a practical example of lazy loading technique and early loading technique in a Singleton Design Pattern.

564 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question