AJAX in JSP

how to use AJAX in JSP
Thanks&Regards
Vipin

This is an example ajax in jsp you work out it
<HTML>
<HEAD>
<TITLE>
AJAX DEMO : Getting JavaReference Author Profile using Ajax interaction
</TITLE>
</HEAD>
<%@ page import="java.util.*" %>
<jsp:useBean id="AuthorsBean" scope="session" class="C:\Program Files (x86)\Apache Software Foundation\Tomcat 5.5\webapps\eg\WEB-INF\classes\AuthorsBean" />
<script type="text/javascript">
var httpRequest;
* This method is called when the author is selected
* It creates XMLHttpRequest object to communicate with the
* servlet
function getProfile(authorSelected)
var url = "http://localhost:8080/eg/GetAuthorsProfile?author=" + authorSelected;
if (window.ActiveXObject)
httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
else if (window.XMLHttpRequest)
httpRequest = new XMLHttpRequest();
httpRequest.open("GET", url, true);
httpRequest.onreadystatechange = function() {processRequest(); } ;
httpRequest.send(null);
* This is the call back method
* If the call is completed when the readyState is 4
* and if the HTTP is successfull when the status is 200
* update the profileSection DIV
function processRequest()
if (httpRequest.readyState == 4)
if(httpRequest.status == 200)
//get the XML send by the servlet
var profileXML = httpRequest.responseXML.getElementsByTagName("Profile")[0];
//Update the HTML
updateHTML(profileXML);
else
alert("Error loading page\n"+ httpRequest.status +":"+ httpRequest.statusText);
* This function parses the XML and updates the
* HTML DOM by creating a new text node is not present
* or replacing the existing text node.
function updateHTML(profileXML)
//The node valuse will give actual data
var profileText = profileXML.childNodes[0].nodeValue;
//Create the Text Node with the data received
var profileBody = document.createTextNode(profileText);
//Get the reference of the DIV in the HTML DOM by passing the ID
var profileSection = document.getElementById("profileSection");
//Check if the TextNode already exist
if(profileSection.childNodes[0])
//If yes then replace the existing node with the new one
profileSection.replaceChild(profileBody, profileSection.childNodes[0]);
else
//If not then append the new Text node
profileSection.appendChild(profileBody);
</script>
<BODY>
<%
//get author list
List authors = AuthorsBean.getAllAuthors();
%>
<TABLE align=left border=0 cellPadding=3 cellSpacing=1 width="100%" >
<TR>
<TD align="center">
<STRONG>Getting JavaReference Author Profile using Ajax interaction.</STRONG>
<br>
</TD>
</TR>
<TR bgColor="#C6D3E7">
<TD>
<SELECT id=authors name=authorComboBox ONCHANGE="getProfile(this.options[this.selectedIndex].value)">
<% Iterator it = authors.iterator();
while(it.hasNext())
String authorName = (String)(it.next()); %>
<OPTION value='<%=authorName%>' ><%=authorName%></OPTION>
<%
}%>
</SELECT>
   <<< Select Author
</TD>
</TR>
<TR bgColor="#FFD0B1">
<TD>
<div id="profileSection">
<br><br>
<div>
<script type="text/javascript">
getProfile(authorComboBox.options[authorComboBox.selectedIndex].value);
</script>
</TD>
</TR>
</TABLE>
</BODY>
</HTML>

Similar Messages

  • Ajax and JSP/Struts ... help

    I am using AJAX in my jsp pages .... I got a problem ........
    my jsp page is like that ....
    <html:html>
    //javascript for ajax ..code
    <body>
    <table id="inside_table">
    <logic:present name="companyList" scope="session">
    <html:select property="companyId" styleId="category" style="width:190px"
    onchange="show();"> *
    <html:options collection="companyList" labelProperty="companyName"
    property="companyId"/>
    </html:select>
    </logic:present>
    <html:form action"/xyz">
    <%
    ArrayList companyList=Session.getAttribute("companyList");
    if(companyList!=null) {
    %>
    //here i have a table of data where i want to show the datas in text boxes .... and if required user can update the valus in the text boxes ... by cliking the uodate button
    <html:sybmit>UPDATE</html:submit>
    <%
    %>
    </html:form>
    </body>
    </html:html>
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    Now in the 1st select box ... when i select one company onchange a javascript show() method will call . Using
    the Ajax technique from this show() method I called a struts action ... then from there I retrieve the datas for that company from database and stored in a arraylist and kept in session as "companyList" , then I used return null at Action class .
    Now when Ajax got the response from the server ... I want to collect the Arraylist "companyList" from session , and now scince companyList is not null , It should show the datas in the table .
    I did all the thing successfully , but only problem is that i am unable to show the datas in the table .
    Actually, onreadystatechange when I got the response from the server I am unable to execute the required portion of the JSP page .....

    You can't use the Java-based HttpSession in this scenario. Your JSP-Scriptlets are executed on the server-side before the page is rendered, so you can't use it directly from the JSP. AJAX (as the name suggests) is all about JavaScript and XML. I recommend you write the data you are interested in to the OutputStream of your HttpResponse object (which is available in the Struts action method).
    E.g.
    response.getOutputStream().write(/* here comes the data */);
    response.flush;
    return null;Most AJAX frameworks allow you to choose wether how you want to serialize your data, available options typically include XML, JSON and HTML. If you use handcrafted AJAX requests I'd suggest you use JSON, as its very easy to read, understand and construct in Java code.

  • Calling managed bean method using ajax on jsp page loading

    Hello,
    I am using jsf1.1 i want to call managed bean method when page gets loaded using ajax.
    Thanks
    K.Ramu

    Use an ajaxical JSF framework, for example Ajax4jsf (part of RichFaces).
    But why don´t you just use the constructor of the bean class to do some stuff prior to page loading?

  • JSP compilation issue

    Hello,
    When we use the exploded war format we are getting some issues in JSP precompilation.
    The issue comes only when we do some local changes to the JSPs in the domain directly and refresh the webpage without restarting the server.
    A sample error is given below.
    Compilation of JSP File '/en/abc/xyz.jsp' failed:
    xyz.jsp:19:5: The page failed validation from validator: "Illegal scope attribute without var in "c:set" tag.".
    <c:set var="targetContentEnabled" value="${tmpTargetContentEnabled}" scope="session" />
    ^-------------------------------------------------------------------------------------^
    xyz.jsp:27:1: The page failed validation from validator: "Illegal scope attribute without var in "c:set" tag.".
    <c:set target="${sessionScope.WDSContext}" property="site" value="${requestScope.SITENAME}" scope="session"/>
    ^-----------------------------------------------------------------------------------------------------------^
    xyz.jsp:28:1: The page failed validation from validator: "Illegal scope attribute without var in "c:set" tag.".
    <c:set target="${sessionScope.WDSContext}" property="market" value="${requestScope.MARKET}" scope="session"/>
    Can any one shed some light in to the issue ?
    You help is greatly appreciated.
    Thanks.

    Hello,
    Here is the error details.
    <Jun 8, 2012 12:32:30 PM GMT> <Info> <HTTP> <BEA-101344> <frontendapp: Attempting to precompile /en/Admin/localization/includes/actions/ajax/SM.jsp,
    since the class file associated with it was not found in the webapp classpath.>
    <Jun 8, 2012 12:32:40 PM GMT> <Warning> <HTTP> <BEA-101212> <frontendapp:online Failure while Precompiling JSPs: weblogic.servlet.jsp.CompilationException:
    BKGD.jsp:12:18: The page failed validation from validator: "Illegal scope attribute without var in "c:set" tag.".
    <%@ include file="Panels/MiniRuleLink.jsi" %>
    ^-----------------------^
    BKGD.jsp:12:18: The page failed validation from validator: "Illegal scope attribute without var in "c:set" tag.".
    <%@ include file="Panels/MiniRuleLink.jsi" %>
    ^-----------------------^
    BKGD.jsp:12:18: The page failed validation from validator: "Illegal scope attribute without var in "c:set" tag.".
    <%@ include file="Panels/MiniRuleLink.jsi" %>
    ^-----------------------^
    BKGD.jsp:12:18: The page failed validation from validator: "Illegal scope attribute without var in "c:set" tag.".
    <%@ include file="Panels/MiniRuleLink.jsi" %>
    Edited by: 939426 on Jun 12, 2012 5:17 AM

  • Problem if i use ajax in struts

    hi,
    i am working on struts, now i got one problem if i use ajax in jsp.
    In my jsp page i have two dropdown lists, according to the first dropdown value second dropdown result will getting from the database by calling an action class.
    but my requirement is for getting the second dropdown result page should not be refresh for this i am using ajax.
    in ajax how can we call one action class what should we return in actionmapping.
    If any one already written some code for this please send it to me.
    please can anyone help on this its very urgent for me.

    Hi
    First of all you have to write on fnRetrieveURL which will be responsible for getting the connection and XML communication.
                   function fnRetrieveURL(strURL, strFnProcessStateChange)
                        if(window.XMLHttpRequest)
                             varXMLrequest = new XMLHttpRequest();
                             varXMLrequest.onreadystatechange = eval(strFnProcessStateChange);
                             try
                                  varXMLrequest.open("POST",strURL,true);
                             catch(Exception)
                                  alert("Problem in Getting data ");
                             varXMLrequest.send(null);
                        else if(window.ActiveXObject)
                             varXMLrequest = new ActiveXObject("Microsoft.XMLHTTP");
                             if(varXMLrequest)
                                  varXMLrequest.onreadystatechange =eval(strFnProcessStateChange);
                                  varXMLrequest.open("POST",strURL,true);
                                  varXMLrequest.send();
                   }This method will be called in user written method in which request will be submitted to action class.
                   function fnGetAreaForRegion()
                        var iRegion = document.getElementById("region").value;
                        var strURL = "../getAreaForRegion.do"
                        strURL = strURL+"?methodName="+"getAreaForRegion";
                        strURL = strURL+"&controlName="+"area";
                        strURL = strURL+"&iRegion="+iRegion ;
                        fnRetrieveURL(strURL,"fnOnReturnFromRegion");
                   }Then there will be one on Return method i.e the method which will be called when the response will come back to JSP from fnGetAreaforRegion.
                   function fnOnReturnFromRegion()
                        if (varXMLrequest.readyState == 4)
                             if(varXMLrequest.status == 200)
                                  var strSubClassValue = varXMLrequest.responseText;
                                  if(strSubClassValue != '')
                                    var strArray = strSubClassValue.split(",");
                                       var iLength = strArray.length;
                                       var strName = new Array();
                                       var strID = new Array();
                                       var j=0;
                                       for(var i =0 ; i< iLength;i=i+2)
                                            strName[j] = strArray;
                                            j++;
                                       var k=0;
                                       for(var i =1 ; i< iLength;i=i+2)
                                            strID[k] = strArray[i];
                                            k++;
                                       var iNewLength = strID.length;
                                       var optnSelect = document.createElement("OPTION");
                                       optnSelect.text = 'Select';
                                       optnSelect.value = '';
                                       document.getElementById("area").options.add(optnSelect);
                                       for(var i =0 ; i< iNewLength;i++)
                                            var optn = document.createElement("OPTION");
                                            optn.text = strName[i];
                                            optn.value = parseInt(strID[i]);
                                            document.getElementById("area").options.add(optn);
    Rest modification in struts-config, you can do by urself. and also you have to write one action class which will take care of parameters and all business logic.
    Above code you can reuse by bit modification. Action class you have to write by your own.
    let me know if you still face any issues

  • Jsp scripting issue

    <html>
    <head>
    <script language="javascript">
    function ajaxfun()
         var z=form1.state.value;
         alert(z);
         var req=initRequest();
         var url="ajax2.jsp?state="+z);
         req.onreadystatechange= function()
    if (req.readyState == 4)
    if (req.status == 200)
    parseMessages(req.responseXML);
                             else if (req.status == 204)
    clearTable();
    req.open("GET","http://localhost:8080/ajax/ajax2.jsp?state="+z,true);
    req.send(null);
              function parseMessages(responseXML)
    var messages = responseXML.getElementsByTagName("messages")[0];
              for (loop = 0; loop < messages.childNodes.length; loop++)
              var message = messages.childNodes[loop];
              var value1 = message.childNodes[0].nodeValue;
              var optn = document.createElement("OPTION");
                             optn.text = value1;
                             optn.value = value1;
                        document.getElementById("dist").options.add(optn);
    function initRequest()
    if (window.XMLHttpRequest)
    return new XMLHttpRequest();
    else if (window.ActiveXObject)
    isIE = true;
    return new ActiveXObject("Microsoft.XMLHTTP");
    </script>
    </head>
    <body>
    <!-- TemplateBeginRepeat name="RepeatRegion1" -->RepeatRegion1<!-- TemplateEndRepeat -->
    <form name="form1" action=" ">
    <pre>
    State:<select name="state" id="state" onChange="return ajaxfun()">
    <option>select</option>
    <option value="a.p">a.p</option>
    <option value="m.p">m.p</option>
    <option value="u.p">u.p</option>
    <option value="h.m">h.m</option>
    </select>
    <div id="dis">
    District:<select name="dist" id="dist">
    </select>
    </div>
    </pre>
    </form>
    </body>
    </html>
    This is my page, it is working fine but the problem when i selecting a.p for first time it is displaying good and again the list is holding the old values as well as new values

    try deleting options from the select before adding a new set
    while(document.getElementById("dist").options.length=0){
         document.getElementById("dist").remove(document.getElementById("dist").options.length);
    }add this to parseMessages method

  • Customize AJAX Blueprint Autocomplete component ?

    Customize AJAX Blueprint Autocomplete component ?
    Can you control the size of the result box generated ?
    Can you control what happens when you click on a result row in the result box ?
    I would like to specify the size of the result box, and possible also the placement/position.
    I would also like to use the result and replace that result with another result, or for example populate a different listfield with it..
    Anybody got any ideas on this ?
    As usual, I have searched with google and on *.sun.com without any luck in finding this information, read articles, documentation and blogs etc....
    Kind Regards,
    Roger

    It looks like you would have to build your own custom AutoComplete component and bring it into Creator. You may have found these links already, but you'd want to start with the API spec for custom components:
    http://developers.sun.com/ajax/index.jsp
    http://java.sun.com/blueprints/ajax.html
    Creator Design-time API info:
    http://developers.sun.com/prodtech/javatools/jscreator/reference/docs/apis/

  • Help me in writing ajax string search from database

    {noformat}*hi everybody,
    please send me a ajax with jsp application
    suppose i enter a word in text area ajax will populate/suggest all string from database ,who started
    from that entering character(s).like a google string search.
    please send full source code
    *{noformat}

    shadab_think_globally wrote:
    {noformat}*hi everybody,
    please send me a ajax with jsp application
    suppose i enter a word in text area ajax will populate/suggest all string from database ,who started
    from that entering character(s).like a google string search.
    please send full source code
    *{noformat}how about you do it yourself?

  • Ajax in NWDS

    hi
           i have a application where i need to use 
           Ajax  , and will NWDS support the ajax coding 
            for Webdynpro perspective

    Hi,
    Not from Webdynpro.
    You can use ajax in jsp/servlet based web applications.
    Regards
    Ayyapparaj

  • Help required in writing And Reading Xml From Database

    Hi
    i m new to java.
    i m facing problem while writing Xml file from Mysql Database in java i m using the WebRowSet
    and also for Reading WebRowSet
    after reading the Xml i have to save this in Database
    (required source code)
    is there any one to help me in this way
    regards
    aamir

    shadab_think_globally wrote:
    {noformat}*hi everybody,
    please send me a ajax with jsp application
    suppose i enter a word in text area ajax will populate/suggest all string from database ,who started
    from that entering character(s).like a google string search.
    please send full source code
    *{noformat}how about you do it yourself?

  • Integrating ADF with Tiles - Facing some problem with ViewHandler

    Hi,
    I am trying to integrate ADF with Tiles. I am able to use tiles and display one or more JSF files using ADF components on a single tile using this thread, ADF Faces Access Denied But the issue is, the functionality of the pages are not getting included, for example, I have an action on click of a command link in one of the tiles, which is not working, its not even refreshing the page. When I tried using plain jsp:include, it works.
    I doubt its b'coz of Tiles - committing the response and forwarding the page, rather than including the page. Does anybody tried on this and have some work around?
    -Manju

    The example for AJAX and JSP with database is
    http://jspcodes.elementfx.com/forums/viewquestion.php?question=11&category=7&name=AJAX
    It works for me. Plz correct the + operator

  • Tomcat 6 - apache problem

    Hello,
    this is my first post, and I hop that someone here can help me.
    I want to create ajp connection.
    server.xml:
    <Connector port="8010" protocol="AJP/1.3" redirectPort="8444" />
    httpd.conf:
    LoadModule jk_module /usr/lib/apache2/modules/mod_jk.so
    JkWorkersFile /etc/libapache2-mod-jk/workers.properties
    JkLogFile /var/log/apache2/mod_jk.log
    JkLogLevel info
    JkMount /test/. test_worker
    JkMount /test/* test_worker
    JkMount /test test_worker
    JkOptions ForwardKeySize ForwardURICompat -ForwardDirectories -ForwardLocalAddress
    JkRequestLogFormat "%w %V %T"
    workers.properties:
    workers.tomcat_home=/etc/apache-tomcat-6.0.24
    workers.java_home=/home/sloba/jdk1.6.0_18/jre/
    ps=/
    worker.list=test_worker
    worker.test_worker.port=8010
    worker.test_worker.host=localhost
    worker.test_worker.type=ajp13
    worker.test_worker.lbfactor=1
    worker.loadbalancer.type=lb
    worker.loadbalancer.balance_workers=test_worker
    problem is that I have servlet jAjax, and I cannot get to him thru apache
    I can manage this
    localhost:8081/test
    localhost:8081/test/jAjax
    localhost/test
    I cannot manage this
    localhost/test/jAjax
    tomcat 6.0.24
    apache 2.0
    ubuntu 9.10
    if you need more info just ask,
    ps. sorry for my poor English.

    Thanks for replay.
    I found problem.
    I use ajax with jsp, and problem is that I need to change path of servlet in my request method
    from
    localhost:8081/test/jAjaxto
    localhost/test/jAjaxThank you.
    Best regards ..

  • Problem in getting data into the child window.

    Hi.
    problem description:
    I have a jsp(lets say parent.jsp). On click of a button in parent.jsp, a showmodal dialogue opens(say child.jsp).
    child.jsp has several fields and a 'search' button.
    On click of the 'search' button in child.jsp, data should be fetched from Database and should be populated in child.jsp, without submitting parent.jsp.
    I am able to fetch the data from DB. But unable to populate it in the same child window.
    How to achieve this?
    thanks
    Akash

    areee yaar...ajax and jsp are two different things altogther...whats harm in using ajax if most of the webapplication now deploy ajax for asynchronous call..

  • Challenge popup menu,  css stylesheet and button in table component

    Hello, in my last post i put the code of an example of popup menu but the only thing that need to run was a cdata tag. But in the example i only can open and close the popup menu in the top and left location that previously set in the css stylesheet .
    1.- I need to create a popup menu that can be diplayed if i click on a button in a table component of creator
    2.- The menu must waits and let me select the opcion I choose with a click otherrewise
    3.- The menu must dissapear if i move the cursor mouse away of the menu,
    I really need somebody helps me faster as u can, and i apreciate ur help, tnks!

    The best thing to do would be to find an existing popup menu widget in a JavaScript library, like dojo (dojotoolkit.org). If you can't find an existing JavaScript widget that fulfills your needs, you can write your own. It won't be easy, but you can use Creator's Auto Complete Text Field's JavaScript as a model. If that is the case, look at both the JavaScript at http://sunapp2.whardy.com/AjaxSamples2/faces/static/META-INF/autocomplete/script.js and the HTML source of the page located at http://sunapp2.whardy.com/AjaxSamples2/faces/DemoAutoCompleteTextField.jsp which is a page that is part of the Creator AJAX component catalog (http://developers.sun.com/ajax/componentscatalog.jsp).

  • Google Map markers text not formated properly in FireFox

    I'm using the Blueprints Ajax Map Viewer component to add a Google Map to one of my pages. This is too cool! It really makes using Google Maps easy.
    However I have a display problem in FireFox. The map has MapMarkers with markup. When you click on a marker the Info Window "balloon" is displayed with the markup text. In IE, the Info Window is nicely wrapped. However, in FireFox, the text is displayed one word per line. So in IE it looks like:
        My Marker
        Description of my marker.But, in FireFox
        My
        Marker
        Description
        of
        my
        marker.Here's an actual example of the "markup."
    <b>Downtown Danville</b><p>Parking. Water. Restroom (in Caboose!). Museum.</p>I suspect it is a style problem, but don't know where to start to troubleshoot. Do I have to dig into the Themes? Any Ideas?
    Cheers
    Dan

    Thank you for bringing this to the forum. One of our developers suggests replacing all spaces with non-breaking spaces ( ) and provides the following code associated with the component catalog found at http://developers.sun.com/ajax/componentscatalog.jsp:
    public String button1_action() {
    String userLocation = (String)this.selectValue1.getValue();
    if (userLocation != null) {
    GeoPoint userPoint = (GeoPoint)getSessionBean1().getGeoPoints().get(userLocation);
    if (userPoint != null) {
    double latitude = userPoint.getLatitude();
    double longitude = userPoint.getLongitude();
    this.mapViewer1_center.setLatitude(latitude);
    this.mapViewer1_center.setLongitude(longitude);
    renderMapViewer = true;
    String m = formatMarker(userPoint.toString());
    MapMarker marker = new MapMarker(latitude, longitude, m);
    this.mapViewer1.setMarkers( new MapMarker[] {marker} );
    //this.mapViewer1.setInfo(marker);
    } return null;
    private String formatMarker(String text) {
    text = "<b>" + text + "</b>";
    text = "Location shown: <br/>" + text;
    text = text.replaceAll(" ", " ");
    return text;
    Our tutorial will also be updated shortly. I hope this helps.
    ~Joe Silber
    Java Studio Creator Documentation

Maybe you are looking for

  • JDeveloper and JSP

    I am a new person to JDeveloper technology. I wanted to know that if I create JSP using JDeveloper 3.0, and then upload the JSP pages on a UNIX server, will I need application server. What is JServer ?

  • How to get the last executed SQL Statemnt of my session

    Hello, I am trying to log my SQL-Statements that I use in a PL/SQL Procedure or Package iinto a text file. How can I log my SQL-Statement without repeating the Statement? Here is an example: INSERT INTO people (id, name) SELECT people.nextval, name f

  • SOAP Adapter Help Needed

    Hi, I have a scenario where i need to call the Web Service on the Traget Side. I know how to configure the SOAP Adapter to do this but i am facing an issue here. The Webservice Expects the SOAP request to be in the form. I don't know how to bring thi

  • Ipad video not launching

    Can anyone help me?  I go into the video app on my ipad to watch tv shows and all I am getting is a black screen.  I can't even choose other shows - it is like frozen.  I have shut down my Ipad twice and it isn't resolving the issue.  Any help would

  • Install trial version of Presenter8.0 FAILED

    When i install the trial version of Presenter 8, it is failed, and the below window as following poped up. how did it happen? Thanks. Exit Code: 31 Please see specific errors and warnings below for troubleshooting. For example,  ERROR: DW048, DW049 .