0

I am using a simple jsp to populate a drop down box (with addresses as options) based on an input parameter (postcode) using ajax in javascript. The javascript code is able to pull the required data, and sets the options in the select element, but just after a fraction of second, all changes disappear and the jsp is back to its initial state. Can you help me in troubleshooting the cause of this behaviour? Thanks in advance.

main JSP code: testajx.jsp

    <form name="testform" method="POST" action="testajx.jsp" >
    <h1><%=a%> testing <b>Postcode Lookup</b></h1>

    <br>

    <br>
    <input type="text" name="ziporpostalcode" size="10" maxlength="7" value="<%=ziporpostalcode%>"/>
    <input type="text" name="ziporpostalcodetest" size="10" maxlength="7" value=""/>
    <input type="hidden" name="searchPostCodeHidden" value="">
    <input type="button" name="searchPostCode" value="Search" onclick="if(ziporpostalcode.value == ''){alert('enter postcode');}else {searchPostCodeHidden.value = 'TRUE'; this.form.submit();}">
    <input type="hidden" name="searchAddressHidden" value="">
    <input type="button" name="test" value="test" onclick="alert(userAddress.value);alert('<%=userAddress%>');">
    <input type=image name="op_xxx" value="Search Address xxx" src="\jsp\htdocs\assets\images2011\buttons\search_address.gif" alt="Search Address"         onclick="sendRequest('GET','testajax.jsp?ziporpostalcode='+ziporpostalcode.value)"href="#" />

    <select name="userAddress" value="<%=userAddress%>" onchange="searchAddressHidden.value =         userAddress.value; form.submit();">
        <option>--- Select ---</option>
        <%=addressOptions%>
    </select>
    <div id="ajax_res">a</div>
        </body>
    </form>

Results received from testajax.jsp:

    <body>
    <select name="userAddress">
        <option>--- Select ---</option>
    <%
    String addressOptions = new String();
    Picklist pl = new Picklist();
    addressOptions = "";
    String ziporpostalcode = request.getParameter("ziporpostalcode");
    pl = PostcodeHandler.getAddressList(ziporpostalcode);
    PicklistItem[] pli = pl.getItems();
    //Iterator li = sAddressList.values().iterator();
    for(int i=0; i<pl.getTotal(); i++)
        {
    addressOptions += "<option label=\""+pli[i].getPartialAddress()+"\" value=\""+pli[i].getMoniker()+"\">"+pli[i].getText()+"</option>";
    session.setAttribute("addressOptions", addressOptions);
    request.setAttribute("ziporpostalcode", ziporpostalcode);
    request.setAttribute("searchPostCodeHidden", ziporpostalcode);
    // addressOptions += "<option label='"+sAddressList.get(i).toString()+"'         value='"+sAddressList.get(i).toString()+"'>"+sAddressList.get(i).toString()+"</option>";
        }
    String str="This is JSP string loading from JSP page in ajax, loading time :";
    out.print(addressOptions);
    %>
    </select>


ajax javascript code is:

    <script language="Javascript" type="text/javascript">
    function createRequestObject(){
    var req; 
    try {

    // Firefox, Opera, Safari
    req = new XMLHttpRequest();
    } catch (e) {
    // Internet Explorer
    try {
    //For IE 6
    req = new ActiveXObject("Msxml2.XMLHTTP");
    } catch (e) {
    try {
    //For IE 5
    req = new ActiveXObject("Microsoft.XMLHTTP");
    } catch (e) {
    alert('Your browser is not IE 5 or higher, or Firefox or Safari or Opera');
    }
    }
    }
    return req;
    }
    //Make the XMLHttpRequest Object
    var http = createRequestObject();
    function sendRequest(method, url){
    if(method == 'get' || method == 'GET'){
    http.open(method,url,true); 
    http.onreadystatechange = handleResponse;
    http.send(null);
    }
    }
    function handleResponse(){
    if(http.readyState == 4 && http.status == 200){
    var response = http.responseText;
    if(response){
    document.getElementById("ajax_res").innerHTML = response;
    document.getElementById("ziporpostalcodetest").value = 'response';
    document.getElementById("testform").action = 'testajax.jsp';
    alert('received something from Ajax');
    }
    }
    }

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
Anshul Tiwari
  • 643
  • 9
  • 16

2 Answers2

1

You're sending an ajax request in the onclick of an <input type="image"> submit button. However, you're not blocking the button's default behaviour when the onclick is finished. The button's default behaviour is namely submitting the form where it is sitting in. You need to block the button's default behaviour by returning false in the onclick.

So, change

<input type=image ... onclick="sendRequest('GET','testajax.jsp?ziporpostalcode='+ziporpostalcode.value)"href="#" />

to

<input type=image ... onclick="sendRequest('GET','testajax.jsp?ziporpostalcode='+ziporpostalcode.value); return false;"href="#" />

Unrelated to the concrete problem, you've severe design problems with this all. I'm not sure where you've learnt HTML, JSP and Ajax, but this all looks very 90's. Make sure that you're reading up to date resources. This may be a good starting point: How to use Servlets and Ajax?

Community
  • 1
  • 1
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
0

Just tired to search an error in your code. Here is my (don't foget include jQuery core):

<div id="content"></div>

<script type="text/javascript">
    function updateDivContent() {
        var result = jQuery.ajax({
            url: "your url",
            type: "POST",
            async: true,
            cache: false,
            data: // your form data, can use serialize from jquery
        });
        jQuery("div#content").html(result.responseText)
    }
</script>
alexey28
  • 5,170
  • 1
  • 20
  • 25