Navigation Bar

Sunday, February 28, 2010

Jakarta Struts Ajax example 2

In the previous example Jakarta Struts : Using AJAX to populate form data we replace the entire span element with the new span element having the stock name populated.
<span id="stockName"><input type="text" name="stock_name" id="sname" value="" readonly></span>
is replaced with
<span id="stockName"><input type="text" name="stock_name" id="sname" value="Google any Alphabet" readonly></span>
Such a call may be requried when we want to change the HTML page design or structure based on an input value. In this example we are only replacing the value element for the span element "stockName" with the value fetched from the database based on the Stock Code. 

var stockNameInput = document.getElementById('sname');
and in the response we replace it with the value with the req.responseText
var stockNameInput = document.getElementById('sname');

Thus we use a more simplified Ajax call as given in the example below.

 index.jsp

<select name="symbol" onchange="retrieveURL('/getquoteAjax2/stockname.do?','lookupForm',this);">

StockNameAction.java

package org;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.Statement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.io.*;

import org.apache.log4j.Logger;

public class StockNameAction extends Action {
    protected final Logger log = Logger.getLogger(getClass());
    protected String getStockName ( HttpServletRequest request, String symbol) {
        String stockName = null;
        Connection conn = null;
        Statement stmt = null;
        ResultSet rs = null;
        DataSource dataSource = null;
        try {
            dataSource = getDataSource(request);
            conn = dataSource.getConnection();
            stmt = conn.createStatement();
            rs = stmt.executeQuery ("select stock_name from stocks where symbol = '" + symbol + "'");
            if (rs.next()){
                String tmp = "";
                tmp = rs.getString("stock_name");
                stockName = new String(tmp);
                System.err.println ("stockName : " + stockName);
            } //end rs.next
            else {
                System.err.println("Symbol not found returning null [" + symbol);
            }   
        }    //end try
        catch (SQLException sqle) {
                    System.err.println (sqle.getMessage());
        }
        finally {
            if (rs != null) {
                try {
                    rs.close();
                }
                catch (SQLException sqle) {
                    System.err.println (sqle.getMessage());
                }
                rs = null;   
            }
            if (stmt != null) {
                try {
                    stmt.close();
                } //end try
                catch (SQLException sqle) {
                    System.err.println (sqle.getMessage());
                }
                stmt = null;   
            } // end stmt not null
            if (conn != null) {
                try {
                    conn.close();
                } //end try
                catch (SQLException sqle) {
                    System.err.println (sqle.getMessage());
                }
                conn = null;   
            } // end conn not null
        } //end finally   
        if ( symbol.equalsIgnoreCase ("SUNWWWW") ) {
            return new String ("SUNWWWW");
        }
        return stockName;
    } //end Action
    
    public ActionForward execute (ActionMapping mapping,
            ActionForm form,
            HttpServletRequest request,
            HttpServletResponse response )
                throws IOException, ServletException {
            String stockName = null;
           
            String target = new String ("success");
            if (form != null ) {
                //Use the LookupForm to get the request parameters
                LookupForm lookupForm = (LookupForm) form;
                String symbol = lookupForm.getSymbol();
            //    request.getParameter(symbol);
            //    System.err.println("In execute Symbol " + symbol);
                log.debug("StockNameAction " + symbol);
                stockName = getStockName(request, symbol);
                
               
                System.out.println("response stockname: " + stockName);
               
                // Write directly to response
                response.setContentType("text/html;charset=UTF-8");
                response.setHeader("Cache-Control", "no-cache");
               
                PrintWriter out = response.getWriter();
                out.print(stockName);
                out.flush();
                out.close();
               
                System.out.println("=== getStockName END ===");
       
           
            }
            
            return null; // Important: return null when writing directly to response
    } //execute
}

Ajax.js 

   /*** Get the contents of the URL via an Ajax call
   * url - to get content from (e.g. /struts-ajax/sampleajax.do?ask=COMMAND_NAME_1)
   * nodeToOverWrite - when callback is made
   * nameOfFormToPost - which form values will be posted up to the server as part
   *                    of the request (can be null)
   */
function retrieveURL(url, nameOfFormToPost, selectElement) {
    // Get symbol value from the select element
    var symbolValue = selectElement.value;
    
    console.log("retrieveURL called: ", selectElement);
    console.log("Symbol value:", symbolValue);
    console.log("Base URL:", url);
    
    // Validate selection
    if (!symbolValue || symbolValue === "-1" || symbolValue === "") {
        alert("Please select a valid stock symbol");
        return;
    }
    
    // Build final URL with symbol parameter
    // Since url already ends with '?', just append the parameter
    var finalUrl = url + "symbol=" + encodeURIComponent(symbolValue);
    
    console.log("Final URL:", finalUrl);
    
    // Create XMLHttpRequest
    var req;
    
    if (window.XMLHttpRequest) { // Non-IE browsers
        req = new XMLHttpRequest();
        
        req.onreadystatechange = function() {
            processStateChange(req);
        };
        
        try {
            req.open("GET", finalUrl, true);
            req.send(null);
        } catch (e) {
            alert("Problem Communicating with Server\n" + e);
        }
        
    } else if (window.ActiveXObject) { // IE
        req = new ActiveXObject("Microsoft.XMLHTTP");
        if (req) {
            req.onreadystatechange = function() {
                processStateChange(req);
            };
            req.open("GET", finalUrl, true);
            req.send();
        }
    }
}


function processStateChange(req) {
	console.log("ReadyState:", req.readyState);
	console.log("Status:", req.status);
	if (req.readyState == 4) { // Complete
		if (req.status == 200) { // OK response
			console.log("Processing response..........");
			console.log("Ajax response:", req.responseText);
			// Directly set the input field value
			var stockNameInput = document.getElementById('sname');
			if (stockNameInput) {
				stockNameInput.value = req.responseText;
				console.log("Stock name updated to:", req.responseText);
			} else {
				console.error("Input field 'sname' not found!");
			}
		} else {
			alert("Problem with server response:\n " + req.statusText);
		}
	}
}


God's Word for the day


Proverbial Sayings
The wise person advances himself by his words,
  And one who is sensible pleases the great.
Those who cultivate their soil heap up their harvest.
  And those who please the great atone for injustice.
Sirach 20:27-28

Gospel teachings of Jesus
A tree and its fruit 
Either make the tree good, and its fruit good;
  or make the tree bad and its fruit bad
For the tree is known by its fruit.
You brood of vipers, how can you speak good things, when you are evil?
For out of the abundance of the heart the mouth speaks.
The good person brings good things out of a good treasure,
And the evil person brings evil things out of an evil treasure.
I tell you, on the day of judgement, you will have to give an account
for every careless word you utter;
For by your words you will be justified, 
And by your words you will be condemned.
Mathew 12:33-37

No comments:

Post a Comment