0

Hi,

I am ajax in following concept.
In jsp page have 2 div.

first div contaion one dropdownlist for selection city onChange event send data to servlet
and other div contain another dropdownlist for displaying cities
which are come from servlet.

Here problem is after selecting city through 1st dropdownlist
first div is stable but bellow that displayed content of fiat
div also and second div.

so please help me.

output is as follows-

without selecting city

AJAX
<first dropdownlist>
This is myDiv null

After selecting city

AJAX 1
<first dropdownlist with selected city> 2
AJAX 3
<first dropdownlist> 4
This is myDiv Pune <second dropdownlist> 5

in above line number 3 and 4 unwanted displayed.

Thanks in advance.

jsp code.

<html>
<head>
<script type="text/javascript">
function loadXMLDoc()
{
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
     
    document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
    }
  }
                    // document.frmIndex.listFrom.options[document.frmIndex.listFrom.selectedIndex].value
  var selectedCity = document.frmAjaxDemo.listFrom.options[document.frmAjaxDemo.listFrom.selectedIndex].value
  alert("Selected city is "+selectedCity)

xmlhttp.open("GET","TrialServlet?city="+selectedCity+"&cityto=selectCity",true);
xmlhttp.send();
}
</script>
</head>
<body>
    <form name="frmAjaxDemo">
        <div id="fis">
<h2>AJAX</h2>
<div id="myDiv1">
    <select name="listFrom" id="listFromId" onchange="loadXMLDoc()">
        <option>SelectCity</option>
        <option>Pune</option>
        <option>Karad</option>
    </select>
</div>
        </div>
<div id="myDiv">This is myDiv
    <%
    String getcity=null;
    Iterator itr=null;
    getcity = (String) request.getAttribute("sndcity");
    if(getcity!=null)
        {
     //getcity = (String) request.getAttribute("sndcity");
    List list = (List)request.getAttribute("sndlistDest");
     itr = list.iterator();
   /*  while(itr.hasNext())
         {
            out.println(itr.next());
         }*/
     }
    %>
    <%=getcity%>
    

    <select name="lsitTo" id="listToId">
        <option>SelectDest</option>
        <%if(getcity!=null)
            {
             while(itr.hasNext())
            {%>
        <option><%=itr.next()%></option>
          <%}
        }%>
    </select>
</div>

    </form>
</body>
</html>

Servlet code.

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


import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.RequestDispatcher;
import java.util.ArrayList;
import java.util.Iterator;

/**
 *
 * @author node4
 */
public class TrialServlet extends HttpServlet {
   
    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();

        String str = request.getParameter("city");
        String str1 = request.getParameter("cityto");

         ArrayList listDest = new ArrayList();
        
        try {
            out.println("Selected city is "+str);
            out.println("City to is "+str1);
            out.println("This is servlet");

            listDest.add("Solapur");
            listDest.add("Mumbai");
            listDest.add("Kolhapur");
            listDest.add("Shimala");

            Iterator itr = listDest.iterator();
            while(itr.hasNext())
            {
                out.println(itr.next());
            }
            request.setAttribute("sndlistDest", listDest);
            request.setAttribute("sndcity", str);
            RequestDispatcher dispatcher = request.getRequestDispatcher("AjaxDemo.jsp");
        if(dispatcher != null)
       {
            dispatcher.forward(request, response);
        }
        } catch(Exception e) {
            out.println(e);
        }

        
    } 

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    } 

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

}
2
Contributors
7
Replies
8
Views
6 Years
Discussion Span
Last Post by Airshow
0

Himmat,

First, the options need values:

<select name="listFrom" id="listFromId" onchange="loadXMLDoc()">
      <option value="">SelectCity</option>
      <option value="Pune">Pune</option>
      <option value="Karad">Karad</option>
    </select>

Then, myDiv can be initially empty:

<div id="myDiv"></div>

The "lsitTo" menu will be overwritten with response from the servlet.

If you want a "lsitTo" menu populated with destinations, then you need to build the entire <select ....> ..... </select> structure, complete with options, in the servlet.

You can also simplify your code with:

<select name="listFrom" id="listFromId" onchange="loadXMLDoc(this)">

and

function loadXMLDoc(menu) {
  if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
    xmlhttp = new XMLHttpRequest();
  }
  else {// code for IE6, IE5
    xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
  }
  xmlhttp.onreadystatechange=function() {
    if (xmlhttp.readyState==4 && xmlhttp.status==200) {
      document.getElementById("myDiv").innerHTML = xmlhttp.responseText;
    }
  }
  var selectedCity = menu[menu.selectedIndex].value;
  alert("Selected city is " + selectedCity);
  xmlhttp.open("GET","TrialServlet?city=" + selectedCity + "&cityto=selectCity", true);
  xmlhttp.send();
}

This makes the javascript easier to read without changing its behaviour.

Airshow

0

Hi,

My problem is which div I want to reflect in that div whole page displayed.
For better understanding please see written output which is before in above code.

solve this problem.

Thanks for replay.

Edited by himmat.m4: some mistaks

0

I find that too hard to follow.

Maybe you can post a screenshot showing the resulting page.

Airshow

0

This is displaying page after first time run page.
[IMG]/home/node4/Desktop/First_time_display_page.png[/IMG]

This is displaying page after selecting city.
[IMG]/home/node4/Desktop/After_city_selecting_page.png[/IMG]

I tried to send screenshots like above.
tell me how to send screenshots by using this

Edited by himmat.m4: fail to dispalyed images

0

Himmat, you need to upload the screenshots to somewhere on the web (eg photobucket.com), then use the uploaded image's absolute url

[IMG]http:...[/IMG]

Airshow

Edited by Airshow: n/a

0

Himmat,

OK, I can see now.

It appears that the original page is being re-served, so the problem must be server-side, in the JSP.

I'm afriad my JSP is very rusty so I'm not in a good position to help you with the code, but I can tell you that you have a choice of two strategies:

  1. Use one servlet and use test to see whether the original page should be served or just the "cityto" menu.
  2. Use two separate servlets (ie two .jsp files); one for serving the original page and the second for serving the "cityto" menu in response to an ajax request. This approach is probably easier.

As it stands, I guess you have just one servlet with no branching.

Airshow

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.