Call struts action from javascript?

Hi all
I'm having problem already discussed here quite a lot, but I have idea to solve it different way. And need to know is it possible or I'm doing mission impossible here :(
I have JSP with 2 drop down lilsts, where the second is populated according to selected value from first - that's basically my problem.
Is it possible to somehow only call my struts action which will return all needed values using javascript and onchange event handler?
I dont have any experience with javascript, and I'm trying to avoid it as much as possible at the moment.
Thanks in advance

well as far your requirement is concern if at all you are planning to implement AJAX try to use the below link which might be of some help...
http://www.it-eye.nl/weblog/2005/12/13/ajax-in-struts-implementing-dependend-select-boxes/
However,I somehow feel there are few loopholes in the author's approach...
i advice to use XmlHttpRequest.reponseXML property there.
However, i've mentioned a sample code snippet for you reference.
XML Response Pattern :
======================
<? xml version="1.1" ?>
<dropdown>
<option>
<val>CUSTOMIZED_VALUE</val>
<text>CUSTOMIZED_VALUE</text>
</option>
</dropdown>Sample.jsp:
===========
<%@page language="java" %>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Automatic Drop-Down Updation</title>
     <script language="javascript">
      // Global Variable for XmlHttp Request Object  
      var xmlhttp
      // Timer Variables
      var c = 0
      var t
       /* A function which calls a servlet  named AjaxServlet to get XmlData using XmlHttpObject */    
        function refreshCombo(txt){
            xmlhttp = null
            // code for initializing XmlHttpRequest Object On Browsers like  Mozilla, etc.
            if (window.XMLHttpRequest){
                 xmlhttp = new XMLHttpRequest()
            // code for initializing XmlHttpRequest Object On Browsers like IE
           else if (window.ActiveXObject) {
               xmlhttp = new ActiveXObject("Microsoft.XMLHTTP")
           if (xmlhttp != null){
              // Setting the Action url to get XmlData
               url = "dropdown.do?count="+txt;
               // Course of Action That Should be Made if their is a change in XmlHttpRequest Object ReadyState NOTE : it is 4 when it has got request from CGI
               xmlhttp.onreadystatechange = getResponseAction;
               // Open the Request by passing Type of Request & CGI URL
               xmlhttp.open("GET",url,true);
               // Sending URL Encoded Data
               xmlhttp.send(null);
           else{
             // Only Broswers like IE 5.0,Mozilla & all other browser which support XML data Supports AJAX Technology
             // In the Below case it looks as if the browser is not compatiable
              alert("Your browser does not support XMLHTTP.")
      /* Used for verifing right ReadyState & Status of XmlHttpRequest Object returns true if it is verified */
      function verifyReadyState(obj){
         // As Said above if XmlHttp.ReadyState == 4 then the Page Has got Response from WebServer
          if(obj.readyState == 4){
           // Similarly if XmlHttp.status == 200 it means that we have got a Valid response from the WebServer
            if(obj.status == 200){               
                return true
             else{
                alert("Problem retrieving XML data")
      /* Action that has to take place after getting reponse */
      function getResponseAction(){
          // Verifying State & Status
          if(verifyReadyState(xmlhttp) == true){
              // Building a DOM parser from Response Object
              var response = xmlhttp.responseXML.documentElement
              // Deleting all the Present Elements in the Drop-Down Box
              drRemove()      
              // Checking for the Root Node Tag
              var x = response.getElementsByTagName("option")
              var val
              var tex
              var optn
              for(var i = 0;i < x.length; i++){
                 optn = document.createElement("OPTION")
                 var er
                 // Checking for the tag which holds the value of the Drop-Down combo element
                 val = x.getElementsByTagName("val")
try{
// Assigning the value to a Drop-Down Set Element
optn.value = val[0].firstChild.data
} catch(er){
// Checking for the tag which holds the Text of the Drop-Down combo element
tex = x[i].getElementsByTagName("text")
try{
// Assigning the Text to a Drop-Down Set Element
optn.text = tex[0].firstChild.data
} catch(er){
// Adding the Set Element to the Drop-Down
document.SampleForm.SampleCombo.options.add(optn)
/* Function removes all the elements in the Drop-Down */
function drRemove(){
var x = document.SampleForm.SampleCombo
for(var i = document.SampleForm.SampleCombo.length - 1 ; i >= 0 ; i--){                     
x.remove(i)
</script>
</head>
<body onload="syncCount()">
<pre> <h1>Refresh Drop-Down <div id='txt'> </div> </h1></pre>
<form name="SampleForm">
<!-- Drop Down which has country list -->
<select name="x" onchange="refreshCombo(this.value)">
               <option value="1">United States</option>
               <option value="2">United Kingdom</option>
               <option value="3">United Arab Emriates</option>
</select>
<!-- Drop Down which is dependent on Country Drop down get list of states -->
<select name="SampleCombo">
<option value="-1">Pick One</option>
</select>
</form>
</body>
</html>
struts-config.xml:
==================
<action-mappings>
<action path="/dropdown" type="com.controlleraction.AjaxActionClass">
<forward name="error" path="/error.jsp"/>
</action>
</action-mappings>AjaxActionClass.java:
=====================
package com.controlleraction;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
public class AjaxActionClass extends DispatchAction {
  public ActionForward execute( ActionMapping mapping,ActionForm form,HttpServletRequest request,HttpServletResponse response) throws Exception {
    String req = new String("");
    try{
       req = request.getParameter("count");
    } catch(Exception exp){
   if(!req.equals("")){
       response.setContentType("text/xml");        
       response.setHeader("Pragma","no-cache");
       response.setHeader("Cache-Control","no-cache,post-check=0,pre-check=0");
       PrintWriter out = response.getWriter();
       /*a sample bean where we trying to call a service from Model*/
       com.Biz.XmlBean xml = new XmlBean();
       String buffer = xml.getXmlData(req);
       if(xml.close() == true && buffer.equals("") == false)
         out.write(buffer);     
       return(null);
  } else {
     return new ActionForward("error");
}XmlBean.java:
=============
* XmlBean.java
import java.sql.*;
import java.util.*;
import java.io.*;
* @author RaHuL
public class XmlBean {
    private Connection con = null;
    private PreparedStatement pstmt = null;
    private ResultSet rs = null;
    // Setting CLASSURL path to TYPE I Driver
    private String CLASSURL = "sun.jdbc.odbc.JdbcOdbcDriver";
    /* Specifing CONNECTION PATH to a DSN named TestDsn
     * Please Make Sure you create a DSN Named TestDsn to your database which holds EMP table
    private String CONNECTIONURL = "jdbc:odbc:TestDsn";
    boolean IS_ESTABLISHED = false;
    /** Creates a new instance of XmlBean and also establishes DB Connections */
    public XmlBean() {
        try{
            Class.forName(CLASSURL);
            con = DriverManager.getConnection(CONNECTIONURL,"admin","");
            IS_ESTABLISHED = true;
        } catch(SQLException sqe){
            sqe.printStackTrace();
        } catch(Exception exp){
            exp.printStackTrace();
    /* Generates XmlData For the Business Logic Specified */
    public String getXmlData(String req){
        String XmlBuffer = new String("");
        if(IS_ESTABLISHED == true){
            try{
                pstmt = con.prepareStatement("SELECT stateid,statename FROM STATE_TABLE where countryid = ?");
                pstmt.setString(1,req);
                rs = pstmt.executeQuery();
                if(rs != null){
                    XmlBuffer = XmlBuffer + "<?xml version=\"1.0\" encoding=\"ISO-8859-1\" ?>";
                    XmlBuffer = XmlBuffer + "<!--  Edited by Rahul Sharma -->";
                    // Root Node
                    XmlBuffer = XmlBuffer + "<dropdown>";
                    while(rs.next()){
                        String value = rs.getString(1);
                        String text = rs.getString(2);
                        // Sub-root Node
                        XmlBuffer = XmlBuffer + "<option>";
                        // node which holds value of drop-down combo
                        XmlBuffer = XmlBuffer + "<val>"+value+"</val>";
                        // node which holds text for drop-down combo
                        XmlBuffer = XmlBuffer + "<text>"+text+"</text>";
                        XmlBuffer = XmlBuffer + "</option>";
                    XmlBuffer = XmlBuffer + "</dropdown>";
            }catch(SQLException sqe){
                sqe.printStackTrace();
            } catch(Exception exp){
                exp.printStackTrace();
        return(XmlBuffer);
    /* Closes the DB Connection Conmpletely */
    public  boolean close(){
        if(IS_ESTABLISHED == true){
            try{
                pstmt.close();
                con.close();
                return(true);
            } catch(SQLException sqe){
                sqe.printStackTrace();
            } catch(Exception exp){
                exp.printStackTrace();
        return(false);
NOTE: I understand i'm not completely coded things as per proper coding standards.please execuse me for that as this example was just given to enable user to learn how XmlHttpRquest,reponseXML
can be used for better purposes instead of devising manual parsing.
where i've used XmlHttpResponse pattern to be in XML. you may make use of other practices like JSON & so on depending on your requirement..
and and if you are more instrested in integrating Struts with AJAX using few frameworks & customized tag based support please go though the below link.
http://struts.sourceforge.net/ajaxtags/index.html
Hope that might help :)
REGARDS,
RaHuL

Similar Messages

  • How to call a struts action from a JSF page

    I am working on a small POC that has to do with struts-faces. I need to know how to call a struts ".do" action from a JSF page..
    Sameer Jaffer

    is it not possible to call a action from the faces submit button and/or the navigation?
    This a simple POC using struts-faces exmaples.
    Here is my struts-config and faces-config file.
    <struts-config>
    <data-sources/>
    <form-beans>
      <form-bean name="GetNameForm" type="demo.GetNameForm"/>
    </form-beans>
    <global-exceptions/>
    <global-forwards>
      <forward name="getName" path="/pages/inputname.jsp"/>
    </global-forwards>
    <action-mappings>
      <action name="GetNameForm" path="/greeting" scope="request" type="demo.GreetingAction">
       <forward name="sayhello" path="/pages/greeting.jsp"/>
      </action>
    </action-mappings>
    <controller>
        <set-property property="inputForward" value="true"/>
        <set-property property="processorClass"
                value="org.apache.struts.faces.application.FacesRequestProcessor"/>
    </controller>
    </struts-config>faces-config
    <faces-config>
    <managed-bean>
      <managed-bean-name>calculate</managed-bean-name>
      <managed-bean-class>com.jsftest.Calculate</managed-bean-class>
      <managed-bean-scope>request</managed-bean-scope>
    </managed-bean>
    <managed-bean>
      <managed-bean-name>GetNameForm</managed-bean-name>
      <managed-bean-class>demo.GetNameForm</managed-bean-class>
      <managed-bean-scope>request</managed-bean-scope>
    </managed-bean>
    <navigation-rule>
      <from-view-id>/calculate.jsp</from-view-id>
      <navigation-case>
       <from-outcome>success</from-outcome>
       <to-view-id>/success.jsp</to-view-id>
      </navigation-case>
      <navigation-case>
       <from-outcome>failure</from-outcome>
       <to-view-id>/failure.jsp</to-view-id>
      </navigation-case>
    </navigation-rule>
    <navigation-rule>
      <from-view-id>/inputNameJSF.jsp</from-view-id>
      <navigation-case>
       <to-view-id>/pages/greeting.jsp</to-view-id>
      </navigation-case>
    </navigation-rule>
    </faces-config>in my inputNameJSF.jsp (faces page)
    <%@ taglib prefix="c" uri="http://java.sun.com/jstl/core" %>
    <%@ taglib prefix="f" uri="http://java.sun.com/jsf/core" %>
    <%@ taglib prefix="h" uri="http://java.sun.com/jsf/html" %>
    <%@ taglib prefix="s" uri="http://struts.apache.org/tags-faces" %>
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
    <title>Say Hello!!</title>
    </head>
    <body>
    Input Name
    <f:view>
         <h:form >
              <h:inputText value="#{GetNameForm.name}" id = "name" />
              <br>
              <h:commandButton id="submit"  action="/greeting.do" value="   Say Hello!   " />
         </h:form>
    </f:view>
    </body>
    </html>I want to be able to call the struts action invoking the Action method in the that returns the name
    package demo;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import org.apache.struts.action.ActionForm;
    import org.apache.struts.action.ActionForward;
    import org.apache.struts.action.ActionMapping;
    public class GreetingAction extends org.apache.struts.action.Action {
        // Global Forwards
        public static final String GLOBAL_FORWARD_getName = "getName";
        // Local Forwards
        private static final String FORWARD_sayhello = "sayhello";
        public GreetingAction() {
        public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
            String name = ((demo.GetNameForm)form).getName();
            String greeting = "Hello, "+name+"!";
            request.setAttribute("greeting", greeting);
            return mapping.findForward(FORWARD_sayhello);
    }Edited by: sijaffer on Aug 11, 2009 12:03 PM

  • What is the best way to call a pageflow action from JavaScript?

    What is the best way to call a pageflow action from JavaScript?
    Thanks,
    John

    John,
    How would I do this from a grid??? Unfortunately there are no JavaScript attributes
    on any of the grid tags that I can see.
    Thanks,
    John
    "John H" <[email protected]> wrote:
    >
    Thanks John!
    "John Rohrlich" <[email protected]> wrote:
    John,
    If you want to put up a confirm dialog before calling an action from
    an
    anchor it is done as follows.
    Here is an example from code of mine that deletes a customer order,if
    the
    user confirms the delete. I pass the order id as a parameter.
    - john
    Here is the JavaScript -
    function confirmDelete() {
    if(confirm('Continue with order delete?'))
    return true;
    else
    return false;
    Here is a sample anchor tag -
    <netui:anchor action="requestToDeleteOrder" onClick="return
    confirmDelete(); return false;">
    Delete
    <netui:parameter name="orderId" value="{container.item.orderId}"/>
    </netui:anchor>
    "John H" <[email protected]> wrote in message
    news:402138f5$[email protected]..
    Thanks for the replies. I figured it was going to require buildingmy own
    url
    to call the action. I had hoped there was an easier way to do it.Rich,
    the
    reason I want to do this is because I want to call the JavaScript
    function
    confirm()
    when a user clicks on a link (in a repeater/grid) to drop a record,I only
    want
    to call the drop action if the user confirms the drop. Maybe thereis a
    better
    way to do what I am trying to do??? I really appreciate any help
    you
    guys
    can
    give me on this, I am pretty new to this sort of stuff.
    Thanks,
    John
    "Rich Kucera" <[email protected]> wrote:
    "John H" <[email protected]> wrote:
    What is the best way to call a pageflow action from JavaScript?
    Thanks,
    JohnTry figuring out the URL to the pageflow action, create a hidden
    form
    in the
    page, then use JS to submit the form. Why would you want to though,
    isn't
    the server going to want to send you to the next page?

  • Calling a procedure from Javascript

    Hello
    I have created a procedure with two input paprameters.
    I have gratted access to public ... and all works well
    I would now like to call this from a Javascript where I supply the input paameters. The procedure has a redirect to another URL so there is no output
    Currently I used "window.location" with the prodcedure URL ... I must beable to call the produced directly?
    Thanks for taking the time to look at this request
    Regards
    Pete

    Pete,
    Have a look at this thread:
    How to call stored procedure from javascript? (about Google Suggest, AJAX)
    Regards,
    Dan
    http://danielmcghan.us
    http://sourceforge.net/projects/tapigen
    http://sourceforge.net/projects/plrecur
    You can reward this reply by marking it as either Helpful or Correct ;-)

  • Call .xhtml file from javascript function

    Hi,
    Is there a way to call .xhtml page from javascript function???

    BalusC wrote:
    Yes there are some ways. But this question has nothing to do with JSF and certainly not with Java at all. Javascript is an entirely different language, although it has a similar syntax as Java (and unforunately also a similar name, they should never have renamed it from ECMAScript).I think ECMAScript is a renaming from JavaScript. The originally JavaScript was called LiveScript by Netscape. I've heard that the ECMAScript name was deliberately chosen to be unsexy.

  • Help with calling java functions from javascript

    I am using javax.script to interpret javascript from a java applet. it loads the js file into a string, and then does engine.eval(script_string). My question is, how would I make functions in the class file that are available to javascript?
    Update: Instead of that, I am loading a js script that will contain all of the usable functions. Here it is:
    //core.js for Javasphere 0.31
    var pkgs = new JavaImporter(java.lang, java.lang.System, java.awt);
    with(pkgs) {
    function Abort(msg) {
            var graph = new Graphics();
            g = graph.getgraphics();
            g.drawString(msg, 20, 20);
    }When I do engine.eval("Abort(\"something\")"); it throws this error:
    javax.script.ScriptException: sun.org.mozilla.javascript.internal.EvaluatorException: error instantiating (0): class java.awt.Graphics is interface or abstract (<Unknown source>#8) in <Unknown source> at line number 8

    Eggbertx, let's start from scratch if you don't mind. Say you have this Applet
    pubic class MyApplet extends Applet
      String message;
      //CALL THIS METHOD FROM JAVASCRIPT
      public void setMessage(String msg)
        message = msg;
        // this saves you from having
        // to call getGraphics() from JavaScript
        repaint();
      public void paint(Graphics g)
        g.drawString(message, 10, 30);
    }Then in your HTML file you may have something like this:
    <input type="text" id="msg" value=""></input>
    <input type="button" value="Set Message" onclick="setAppletMessage()"></input>
    <applet id="myApplet" code="MyApplet.class" width="400" height="100"></applet>And in the JavaScript file:function setAppletMessage()
      var msg = document.getElementById("msg").value;
      document.myApplet.setMessage(msg);
    }This is about all you really need to do. See how the Graphics object is no longer in your .js file?
    Note: You may run into other difficulties in getting this code to work because of browser, security, or some other pain-in-the-neck issues, but this is the idea.
    Eggbertx, I see you added a star to my first post and I think you should take that off because:
    1. <tt>Component</tt> is abstract... so you can not call the <tt>new</tt> operator.
    2. The call <tt>component.getGraphics()</tt> is not going to work either, because <tt>component</tt> was never created.

  • Possibility of calling standard actions from a java program

    Hi ,
    I am working for a project where customer wants to have option of saving orders as draft only and later convert to order if need be. However since we do not want many drafts to reside on server there is a need to delete these at a specified time. For draft orders I am using order templates since they stay in the database without getting converted to orders. Now I do not know how to go about the deletion part.
    i need to write a program that would run on the server and which would fetch the templates (drafts) that have been created till a particular time and call the delete action of the template. Now the question is how do i call these actions from a java program where this java program will have to run on the server end (ie will be a backend process).
    Please suggest.
    Thanks
    Roopali

    hello roopali,
    you can create a separate thread that will run your
    code that will check for stale drafts and delete them.
    it is just like a session management program but here
    we will be looking over the drafts and not the session
    objects.
    now if you want the invocation of the action from another
    program, a socket program would suffice but opening ports
    will cause you network connections thru firewall.
    if you can make use of HTTP servlet as your service
    provider e.g., you can then just pass some action params
    to invoke it.
    regards
    jo

  • How to call SOAP API from JavaScript

    Hi,
    I'm trying to call the SOAP API to get statistics about emails. Are there any examples on how to call the API from JavaScript?
    Here is a link to my original question about using the REST API. REST API URL for email statistics
    Thanks,
    Tim

    Tim,
    In order to consume a SOAP API I recommend you use something other than JavaScript.
    Any platform can offer you a good SOAP client should be OK. (.Net, Java, php, Ruby, python).
    I didn't see anyone successfully used javascript and consume the Eloqua SOAP API.
    I know you can create a SOAP client in Java script but it will be too much work to handle the Eloqua response in some cases.
    Regards,
    Daniel

  • Calling JavaFX Script from JavaScript on mobile

    Hi,
    We are developing a application which would run on a mobile. We have to call javafxscript from javascript in this application. Is there a way to do this on a mobile application. I am able to do this for application running on browsers.
    Will javafx mobile application support this Calling JavaFX Script from JavaScript?
    Please share any information related to this.
    Regards,
    Sherlyn

    I doubt it (but I can be wrong!).
    javafx.stage.AppletStageExtension is only on the desktop profile.
    [Calling From JavaScript to JavaFX Script|http://javafx.com/docs/tutorials/javafx-javascript/] article states "+this functionality requires Java SE 6 Update 10 at minimum+" which seems incompatible with mobile usage.
    Beside, a quick Google search hints that JavaScript support on mobile browsers is weak or inexistent (depending on browsers).

  • How to call a action in javascript

    hi..
    am a learner..
    can anyone guide me how to call a action in Illustrator CS2 using javascript
    thanks in advance,
    Jasy

    Yep!
    Maybe they prefer Apple. Maybe most of their buyers comes from that side.  Maybe they dont know how to script.
    Java would have been to hard for most of us. Javascript is everywhere on the web ... pages.
    After so many years, they did not put the effort and money . This scripting idea is still for ' amateur' and to compensate for I dont know what.

  • How to call struts action manually in onchange property???

    Hello!
    action defined in struts-config.xml:
    <action path="/editLafLm" className="oracle.adf.controller.struts.actions.DataActionMapping" type="oracle.adf.controller.struts.actions.DataForwardAction" name="DataForm" parameter="/editLafLm.jsp">
    <set-property property="modelReference" value="editLafLmUIModel"/>
    <forward name="Submit" path="/viewLaf.do"/>
    </action>
    In my JSP the following form:
    <html:form action="/editLafLm.do" target="laf" onsubmit="self.close();">
    <input type="hidden" name="<c:out value='${bindings.statetokenid}'/>" value="<c:out value='${bindings.statetoken}'/>"/>
    <html:select property="StaId1">
    <html:optionsCollection label="prompt" value="index" property="StaId1.displayData"/>
    </html:select>
    <c:out value="${bindings.editingMode}"/>
    <input name="event_Submit" type="submit" value="    OK    "/>
    </html:form>
    When i click choose an entry from the Select list and then click the Submit Button all works well (the action forward goes to viewLaf.do)
    But i want to use the "onchange" property on the select list:
    <html:select property="StaId1" onchange="submit();">
    This is not the same as pressing the Submit button because here the action editLafLm.do is done in a new window (and then i have to click the submit button)...
    So can i call the action or the action forward manually in the onchange-property so that there is the same behavour as clicking on the submit button???
    Thanks
    Markus

    Markus,
    You can use the click method on the submit button called "event_Submit". The trick is to access it in the elements array of the form.
    So instead of:
    <html:select property="StaId1" onchange="submit();">you will have
    <html:select property="StaId1" onchange="elements[n].click();">where n is the correct index of the 'event_Submit' element in the array of form elements.
    If you need to access the form by name you can always count the form name to be DataForm. So from the document it will be:
    document.forms.DataForm.elements[8].click()Charles.

  • How to call java classes from javascript?

    i have a button which calls javascript i need to access a class to update the values in the database.. how do you call the java code from within the javascript?
    the class is stored under tomcats classes directory and is accessed:
    com.Database.Employee
    the method is called : UpdateEmployeeDetails
    the button
    <input type="button" value="Save" onclick="submitForm('save')" />the javascript
    <script language="javascript">
            function submitForm(process){    
                document.myForm.action="update.jsp";
                document.myForm.submit();
    </script>

    is it not possible?
    do i have to refresh the page and read in the values like...
    <%
    String ename = request.getParameter( "EmployeeName");
         session.setAttribute( "ename", ename);
    %>and then call the class from here?
    looking around ive come across ajax but i dont know how to use it and what you need to install and if its compatable with tomcat and jsp?
    is ajax better or not really worth it?
    i have anything up to 100 fields that need saving at one save click

  • Call Java Method From JavaScript Function

    hi everyone
    i need a help in calling Java method from a javaScript method
    ex:
    function confirmAddRecord() {
    cHours =document.getElementById('frmP:ChargeHours').value;
    cSTime =document.getElementById('frmP:ChargeStartTime').value;
    var answer = confirm("Are you sure you want to add Record?")
    if (answer){
    here i want to call the Java Method that is located in session bean that takes the upper params cHours & cSTime
    else{
    return false;
    i know i can do it as an action button but it is required me to be in that way can any one help plz
    Message was edited by:
    casper77

    That depends on the nature of your parameters. I guess you calculate the params on client and then want to submit them. In this case and if you don't want to use Ajax simple add some <input type="hidden"> elements (of course there correspondend components dependent of your framework) and store the params there. If the javascript isn't invoked by a button click, you can use a button nevertheless. Set visible="false" and call
    document.getElementById('client_id_of_my_hidden_button').click();
    (or maybe doClick() dependent on your framework).

  • Call Java method from JavaScript

    Hi,
    I have a Java class called abc.java and in that I have a method called assignValue(String value).
    I need to call this method, assignValue() , from JavaScript.
    Is there a way to call a Java method from JavaScript.
    Any help is greatly appreciated.
    Thanks.

    Yes I did, and I still don't get it, I have created a JSF web application, not an applet, as I posted earlier my code to executes sit's in a class file, not an applet file.
    My Page1.class file is as follows
    * Page1.java
    package a1;
    import ....
    public class Page1 extends AbstractPageBean {
        public void valset(int val) {
    }my jsp file "Page1.jsp" is as follows:
    <?xml version="1.0" encoding="UTF-8"?>
    <jsp:root version="1.2" xmlns:f="http://java.sun.com/jsf/core" xmlns:h="http://java.sun.com/jsf/html" xmlns:jsp="http://java.sun.com/JSP/Page" xmlns:ui="http://www.sun.com/web/ui">
        <jsp:directive.page contentType="text/html;charset=UTF-8" pageEncoding="UTF-8"/>
        <f:view>
            <ui:page binding="#{Page1.page1}" id="page1">
                <ui:html binding="#{Page1.html1}" id="html1">
                    <ui:head binding="#{Page1.head1}" id="head1">
                        <ui:link binding="#{Page1.link1}" id="link1" url="/resources/stylesheet.css"/>
                    </ui:head>
                    <ui:body binding="#{Page1.body1}" id="body1" style="-rave-layout: grid">
                        <ui:form binding="#{Page1.form1}" id="form1">
    <applet code="Page1.class" name="Page1" width="1100" height="600">
                    </applet>
                            <ui:button action="#{Page1.button1_action}" binding="#{Page1.button1}" id="button1" onMouseOver="form1.Page1.valset(1);"
                                style="left: 239px; top: 192px; position: absolute" text="Button"/>
    </ui:form>
                    </ui:body>
                </ui:html>
            </ui:page>
        </f:view>
    </jsp:root>All I get is a grey box the size of the applet window. Could you please let me know what I'm doing wrong?

  • Call C# method from javascript in WebView and retrieve the return value

    The issue I am facing is the following :
    I want to call a C# method from the javascript in my WebView and get the result of this call in my javascript.
    In an WPF Desktop application, it would not be an issue because a WebBrowser
    (the equivalent of a webView) has a property ObjectForScripting to which we can assign a C# object containg the methods we want to call from the javascript.
    In an Windows Store Application, it is slightly different because the WebView
    only contains an event ScriptNotify to which we can subscribe like in the example below :
    void MainPage_Loaded(object sender, RoutedEventArgs e)
    this.webView.ScriptNotify += webView_ScriptNotify;
    When the event ScriptNotify is raised by calling window.external.notify(parameter), the method webView_ScriptNotify is called with the parameter sent by the javascript :
    function CallCSharp() {
    var returnValue;
    window.external.notify(parameter);
    return returnValue;
    private async void webView_ScriptNotify(object sender, NotifyEventArgs e)
    var parameter = e.Value;
    var result = DoSomerthing(parameter);
    The issue is that the javascript only raise the event and doesn't wait for a return value or even for the end of the execution of webView_ScriptNotify().
    A solution to this issue would be call a javascript function from the webView_ScriptNotify() to store the return value in a variable in the javascript and retrieve it after.
    private async void webView_ScriptNotify(object sender, NotifyEventArgs e)
    var parameter = e.Value;
    var result = ReturnResult();
    await this.webView.InvokeScriptAsync("CSharpCallResult", new string[] { result });
    var result;
    function CallCSharp() {
    window.external.notify(parameter);
    return result;
    function CSharpCallResult(parameter){
    result = parameter;
    However this does not work correctly because the call to the CSharpResult function from the C# happens after the javascript has finished to execute the CallCSharp function. Indeed the
    window.external.notify does not wait for the C# to finish to execute.
    Do you have any solution to solve this issue ? It is quite strange that in a Window Store App it is not possible to get the return value of a call to a C# method from the javascript whereas it is not an issue in a WPF application.

    I am not very familiar with the completion pattern and I could not find many things about it on Google, what is the principle? Unfortunately your solution of splitting my JS function does not work in my case. In my example my  CallCSharp
    function is called by another function which provides the parameter and needs the return value to directly use it. This function which called
    CallCSharp will always execute before an InvokeScriptAsync call a second function. Furthermore, the content of my WebView is used in a cross platforms context so actually my
    CallCSharp function more look like the code below.
    function CallCSharp() {
    if (isAndroid()) {
    //mechanism to call C# method from js in Android
    //return the result of call to C# method
    } else if (isWindowsStoreApp()) {
    window.external.notify(parameter);
    // should return the result of call to C# method
    } else {
    In android, the mechanism in the webView allows to return the value of the call to a C# method, in a WPF application also. But I can't figure why for a Windows Store App we don't have this possibility.

Maybe you are looking for