Using JSP parameters as input in a JavaScript function

hey
I have a JavaScript function, which I call with JSP parameters.
The function call looks similar to:
<button onclick="myFunction(<%= jspParameter%>);"> </button>
However, this JavaScript function is called from a jsp page, which is asynchronously refreshed upon a click of the button.
The problem is that the JavaScript function does NOT function when I click the button for the first time (or maybe it functions, but with the old value of the jspParameter).
Only after the second click it starts taking the jspParameter.
Can you please tell me how to properly get the jspParameter as input in my case....
thank you

I'm sorry, you're right - I didn't give enough details.
My whole page consists of several jsp-s.
The jsp, from which I call the JavaScript function is just one part of the whole page. I'll call it partToBeChanged.jsp.
When I press the button, the partToBeChanged.jsp should refresh asynchronously and call the JavaScript function using the new jsp parameter as input.
To be more precise, here is roughly how myFunction looks like (JavaScript):
function myFunction(url, jspParam) {
     var XMLHttpRequestObject = false;
     if (window.XMLHttpRequest) {
          XMLHttpRequestObject = new XMLHttpRequest();
     } else if (window.ActiveXObject) {
          XMLHttpRequestObject = new ActiveXObject("Microsoft.XMLHTTP");
     if (XMLHttpRequestObject) {
          XMLHttpRequestObject.open("GET", myServlet + url, true);
          XMLHttpRequestObject.onreadystatechange = function() {
               if (XMLHttpRequestObject.readyState == 4 && XMLHttpRequestObject.status == 200) {
                    //plug server response in the target place.
                    //The target is an id of a division, which holds the partToBeChanged.jsp page
                    //The server itself uses RequestDispatcher to direct the response to the partToBeChanged.jsp     
                    //NOTE: partToBeChanged is only a part of the whole HTML page, which is refreshed dynamically               
                    document.getElementById('target').innerHTML = XMLHttpRequestObject.responseText;
                    //changes the content of a div, which is IN ANOTHER .jsp fragment (different than partToBeChanged.jsp)
                    y = document.getElementById("div_to_change");
                    y.innerHTML = jspParam;
          XMLHttpRequestObject.send("");
}the jspParam is a java object, initialized in the servlet and used in partToBeChanged.jsp
To summarize: the servlet dispatches the response to the partToBeChanged.jsp page, which uses the jspParam as input for myFunction, and myFunction tries to change the content of the "target" div accorting to the jspParam. However it changes as expected only after the second button click.
Thanks a lot for any help....

Similar Messages

  • Using a request scope object in a javascript function

    Hello,
    is there a way to obtain a reference to a request scope attribute in a javascript function?
    or after using <jsp:useBean id="myBean" ...>, how do I pass the "myBean" object to a javascript fuction?
    Thanks for any help.
    E-

    ok, thanks...this is working for a string property of a bean... but I get an 'invalid character' error when I want to create an actual reference to the bean object itself.
    here is the jist of what I need to get working... myBean has a property 'listItems' that is a Vector of listBeans.
    function buildList() {
    var myBean = <%=request.getAttribute("mybean")%> ;
    // get referenence to the Vector property listItems
    var list = myBean.getListItems();
    // now I want to iterate the list and use the properties of the list beans
    for (x = 0 ; x < list.size() ; x++ ) {
    var listBean = list[x];
    var foo = listBean.getFoo();
    // need to use foo to populate a hierarchical list
    can I do this in JavaScript??? do I need to cast the classes to the variables?

  • Using JSP variable inside Java Script's alert function.

    Hi Gurus,
    We are trying to use alert function with one of the string variables populated inside JSP code, but its not working.
    Here is the code snippet, please advice.
         <%
         oracle.apps.qot.util.RequestCtx.log("qotcustom.jsp",AOLMessageManager.getMessageSt(QotUtil.QOT_APPS_CODE, "XDPYY_DISC"));
         %>
         var alert_text="<%=AOLMessageManager.getMessageSt(QotUtil.QOT_APPS_CODE, "XDPYY_DISC")%>";
         alert(alert_text);
         Here in the first line we are using API to get text message defined in database, the line is getting executed properly and we could see output text message in debug log file, after this in the 4th line, we are assiging this string output of API to java script variable alert_text and further using alert function with the variable alert_text as argument. But alert function is failing, no errors are thown in debug log file.
    Please advice whether we are doing any thing wrong.
    Thanks in advance.

    What pgeuens means is that you can't mix javascript and jsp/java code in this way.
    ALL of the jsp/java code gets executed at the server end.
    This produces an HTML page (with embedded javascript) which gets sent to the client.
    The client then runs javascript code in response to events (onLoad, onClick, onChange etc etc)
    So in this case, the jsp:forward will always be executed, because as far as the server is concerned, the javascript is just template text.
    If you WANT to do a conditional forwarding on the server side you do it in java ie (horribly using scriptlet)
    <%
    if (testCondition){
    %>
      <jsp:forward>
    %<
    %>Or if you want to test what the client has entered client side, all you can do is submit the form, or navigate to a URL
    <script>
    function test()
    if(document.f.htemp.value=="true")
    alert("jus");
    else
    var s=document.f.htemp.value;
    alert(s);
    document.f1.action="success.jsp";
    document.f.submit();
    </script>You cannot run JSP code based on your javascript code.
    Java. Javascript. Not the same thing.
    Hope this helps,
    evnafets

  • How do webpage developers get Firefox to use the windows.resize or windows.moveTo javascript functions that seem to now be passed over?

    Before V7, this code worked and did as requested every time the page was run. Now, it does not work and no error is reported. Google Chrome and Internet Explorer are able to produce th correct result.
    <script type="text/javascript">
    window.resizeTo(325,700);
    window.moveTo(1150,10);
    </script>
    I have a site where I use window.open to create a login window with minimum chrome.
    On successful login, the window that created the login window updates itself to another page. The login window is supposed to resize itself and move to create a console panel to the right of the screen.
    I have tried to update the window from its parent at the point of successful login (flagged by a database change, checked frequently). I have also included code in the new window itself to resize itself to no avail.
    The new code seems to be failing on both the conditions laid out!

    Some conditions were added in 7.0 to avoid abuse of the resize and move functions:
    #Can't resize a window/tab that hasn't been created by window.open.
    #Can't resize a tab if the tab is in a window with more than one tab.
    * https://bugzilla.mozilla.org/show_bug.cgi?id=565541#c24
    There's still some discussion on the bug - including some solutions and troubleshooting for pages that were affected that shouldn't be - and it's being tracked to make sure it doesn't have any adverse effects.

  • How to use javascript functions in struts jsp page

    hi
    iam using struts jsp pages. here iam calling one javascript function. but iam not able to access the form in javascript.
    wat i have to give as form name to get the elements of the form.
    please reply me soon
    it is urgent
    vamsi

    your form has no name liek this one:
    <html:form action="/userRegistration.do" >so you cannot access the elements inside your form?
    accessing the elements inside the form will be like this:
    document.forms[0].propertyName.value;

  • How to use a Session object in a Javascript function

    I have an object that I have set in my session.
    On my jsp I want to pull it out of my session and use it as a parameter for a javascript function. But I am not sure how to do that... the function call is below... I want to assign a value to ifFormat (last variable in function) But I am not sure what to use inside javascript.
    <script type="text/javascript">
         Calendar.setup({inputField:"f_date_dfFirstPmtDate",
                                              button:"f_trigger_dfFirstPmtDate",
                                             singleClick:true,
                                              ifFormat:XXXXX});
    </script>

    Note that javascript runs on the client side, and JSP runs on the server. JSP and the session objects are NOT available to javascript in reaction to the user.
    If this function is called only when the page is first created, not when the user interacts with the page, or if you want that value to be constant with respect to the javascript, then you can do this:
    <%
      String someValue = (String)session.getAttribute("theAttributeName");
    %>
    <script type="text/javascript">
         Calendar.setup({inputField:"f_date_dfFirstPmtDate",
                                              button:"f_trigger_dfFirstPmtDate",
                                             singleClick:true,
                                              ifFormat:<%=someVale%>});
    </script>

  • Call JavaScript function when my Condition is true in JSP

    Hi all,
    in my jsp i wanna call a javascript function (user defined) when a particular condition si met. How to go about it ? Can anyone plz help me out. Help appreciated.

    hi
    yes! we can do it as follows:
    in the JSP code u can include the javascript function
    first u declare the Javascript function before the </head> tag in the HTML
    and in the JSP u can just call the function which is as follow:
    <script>call the JavaScript function()</script>
    for example:
    <html>
    <head>
    <script language="JavaScript">
    function sayhi() {
    alert("hi");
    </script>
    </head>
    <body>
    <%
    zStr = request.getParameter("str");
    if(zStr.equals("true")) {
    %>
    <script>sayhi();</script>
    <%
    else {
    %>
    </body>
    </html>

  • Making a commandButton's action dependant on a javascript function's result

    Hi guys,
    I have a command button "Login". I have a managed bean "userLoginInfoBean" with session scope whose "loginToSystem" method I want to call when user clicks on Login button.
    <h:commandButton id="loginButton" type="submit" value="Login" style="font-family: Verdana; font-size: 8pt" action="#{userLoginInfoBean.loginToSystem}">So far so good. Its working perfect.
    Now before calling the action, I want to call a javascript function isGoAhead(). This javascript function will return true or false. Only when it returns true then I want to call the action.
    How can I do it in JSF?
    Thanks

    I know using onclick attribute I can call my javascript function "isGoAhead()"
    <h:commandButton id="loginButton" type="submit" value="Login" style="font-family: Verdana; font-size: 8pt" onclick="isGoAhead();" action="#{userLoginInfoBean.loginToSystem}">But the question is how to make sure that the commandButton's action only gets called if the return value from "isGoAhead()" is true?
    Thanks

  • How to set JavaBean in JSP using JavaScript function

    Hello,
    When a user clicks on an item, I want to execute a JavaScript function. Within that function, I want to set specific JavaBeans (<jsp:setProperty... />) within my JSP page.
    Can anyone tell me how to do this or where I can find examples on how to set JavaBeans in a JSP page using JavaScript?
    Thanks.
    Pat

    try this:
    your.jsp
    <html>
    <SCRIPT>function buttonClick()
    {document.compform.submit();}
    </SCRIPT>
    <body>
    <form name=compform method=post action='your.jsp'>
    <%
    //write your code which you want to execute once the button is submitted
    String submit;
    submit=request.getParameter("mysubmit");
    if ((submit != null) && (! submit.equals("")))
    %>
    <input type=hidden name=mysubmit value="submit">
    <input type=button value=add onclick='buttonClick()'>
    </form></body></html>

  • Access Initialization Parameters using jsp

    Hi All,
    Now I'm learning JSP . I want to access the initialization parameters using jsp. How to do it. I used the following code , but it shows null
    initparameter.jsp
        <html>
         <body>
              <h1>
                   <%
                        out.println("InitParameter Checking");
                        out.println(application.getInitParameter("param1"));
                   %>
              </h1>
         </body>
    </html>I configured the following tags in my web.xml.
            <servlet>
              <servlet-name>initparameter</servlet-name>
              <jsp-file>/initparameter.jsp</jsp-file>
            <init-param>
                    <param-name>param1</param-name>
                    <param-value>value1</param-value>
                </init-param>
         </servlet>
                    Help me to resolve this problem
    Thanks in advance,
    mahes

    try overriding the jspInit method and then call getServletConfig() method and call getInitiParameter() on that ..infact the config implicit object would iachieve the same .i don't understand why it's printing null in your case .let me test and see

  • Call javascript function using parameters cause a immediate execute at load

    Hello.
    I recognized a strange behavior if I try to use parameters to javascript in af:clientListener method property.
    Using syntax <af:commandButton text="Init" id="cb1"
       partialSubmit="true">
       <af:clientListener method="OnInitControl1" type="click"/>
    </af:commandButton> and javascript function OnInitControl1() {
      alert('OnInitControl1 called');
    } the method OnInitControl1 is called first with the click of the button.
    But with the syntax <af:commandButton text="Init" id="cb1"
       partialSubmit="true">
       <af:clientListener method="InitCtrl('Control1')" type="click"/>
    </af:commandButton> and javascript function InitCtrl(frameName) {
      alert('InitCtrl(' + frameName + ') called');
    }the function InitCtrl is called immediate at load of the page.
    In both cases the javascript file is inserted in af:document using<af:resource type="javascript" source="/ScriptHelper.js"/>Is my syntax for "method" property of the af:clientListener wrong?
    Paul.

    Hi,
    I am using Oracle JDeveloer version 11.1.1.0.2. I have gone through your discussion. Since i am new to ADF, just wanted to request you to share the code related to <af:resource type="javascript" source="/ScriptHelper.js"/>. Also, the Tag included for the same. In my Environment, if i use <af:resource, it shows, "element af: resource is not expected".
    My requirement is similar to your as you explained in details. I need to push all the client side validation to Javascript file and need to call in the ADF pages wherever it is required (re-usable). Also, is there any specific formate for JS file to be maintained from the point of view of ADF calling the JS file.
    Your help will be greatly appreciated.
    Thanks in Advance,
    --Mahesh                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

  • To Retrieve dynamic radio button values using jsp & javascript

    Hi All,
    How can i retrive the dynamically created radio button values and also want to get the clicked radio button values.I am using JSP and JAVA beans to retrive the values from the form. I dont have any probs to retrieve combo box values, text box values only problem showing with radio button values. If any data which is entered wrong in the form all the fields should prefills with the old value.Except radio button values all others fields such as combo box, text box values are prefilled with the old values.
    I have given the code for radios.
    document.write('<input type="radio" name="distradio" OnClick="sampleReq.fcidis.value=\'Y\'"/>Yes   ');
    document.write('<input type="radio" name="distradio" OnClick="sampleReq.fcidis.value=\'N\'"/>No');
    document.write('<input type="hidden" name="fcidis" value="">')
    <form method="POST" action="Update.jsp" name="sampleReq" >
    <tr>
    <td class="Txt_gris">
    <input type="radio" name="requester" OnClick="sampleReq.requester1.value='supplier'"/> supplier
    </td>
    <td class="Txt_gris">
    <input type="radio" name="requester" OnClick="sampleReq.requester1.value='customer'"/>customer
    </td>
    <td class="Txt_gris">
    <input type="radio" name="requester" OnClick="sampleReq.requester1.value='distributor'"/> distributor
    </td>
    <td class="Txt_gris">
    <input type="radio" name="requester" OnClick="sampleReq.requester1.value='employee'"/> employee
    </td>
    <td class="Txt_gris">
    <input type="radio" name="requester" OnClick="sampleReq.requester1.value='New partner'"/>New partner
    <input type="hidden" name="requester1" value=""/>
    </td>
    </tr>
    Advanced Thanks for help
    Regards
    Sona

    Hi,
    If you have this code
    document.write('<input type="radio" name="distradio" OnClick="sampleReq.fcidis.value=\'Y\'"/>Yes ');
    document.write('<input type="radio" name="distradio" OnClick="sampleReq.fcidis.value=\'N\'"/>No');
    document.write('<input type="hidden" name="fcidis" value="">')
    <form method="POST" action="Update.jsp" name="sampleReq" >
    <tr>
    <td class="Txt_gris">
    <input type="radio" name="requester" OnClick="sampleReq.requester1.value='supplier'"/> supplier
    </td>
    <td class="Txt_gris">
    <input type="radio" name="requester" OnClick="sampleReq.requester1.value='customer'"/>customer
    </td>
    <td class="Txt_gris">
    <input type="radio" name="requester" OnClick="sampleReq.requester1.value='distributor'"/> distributor
    </td>
    <td class="Txt_gris">
    <input type="radio" name="requester" OnClick="sampleReq.requester1.value='employee'"/> employee
    </td>
    <td class="Txt_gris">
    <input type="radio" name="requester" OnClick="sampleReq.requester1.value='New partner'"/>New partner
    <input type="hidden" name="requester1" value=""/>
    </td>
    </tr>
    this field distradio will not be able Update.jsp.
    You will need to insert these field into the form definition.
    Now, to get a valeu from a radio button, you need only to do request.getAttribute("fieldName").
    To generate dinamically all radio button values, i need to know where are these information? In database? If yes, you need to read the resultset na in value attribute you need to do somethink like this <input type=radio name=fieldName value="<%out.println(resultset.getString("FieldName"));%>">
    If you have more question, only send me a email,
    best regards
    Edney Imme
    [email protected]

  • Unable to use two SQL choices Input parameters in Production Reporting 9.0

    Hi Experts, <BR>I am unable to use two parameters as SQL Choices in Production Reporting. When i use only 1 SQL Choice parameter, it works fine but when i use more than one SQL Choice parameter, it gives error. It works fine in Production Reporting Server but when i publish it on System9 workspace, it doesn't work.<BR><BR>any help would be appriciated.<BR><BR>Thanks & Regards<BR>Arpit Shanker

    Azeroth wrote:
    @Twinkle.. it doesnt work
    SQL> create table ignore_columns
      2  (a varchar2(90),
      3  b varchar2(90));
    Table created.
    SQL> CREATE OR REPLACE PROCEDURE
      2   input_columns
      3   (
      4   table_name IN user_tab_columns.table_name%TYPE,
      5   column_list IN VARCHAR2
      6   ) IS
      7   stmt VARCHAR2(3000);
      8   BEGIN
      9   stmt := 'INSERT INTO ignore_columns VALUES (:1,:2)';
    10 
    11   EXECUTE IMMEDIATE stmt using table_name,column_list;
    12 
    13   END;
    14   /
    Procedure created.
    SQL> execute input_columns('HELL', 'HELLO');
    PL/SQL procedure successfully completed.
    SQL> select * from ignore_columns;
    A
    B
    HELL
    HELLOTwinkle

  • How to pass value to pop up window using javascript function?

    I am not sure how to do this, I want to open new window from existing form,This is Mod/PLsql for consists some javascript functions also. When I am clicking on new window in form then new form should open with results of value entered,but new window form is opening with main page :( , not able to get text box value from parent form. How to call textbox input value in popup window from parent window using javascript?
    currently I'm using following code:
    HTP.p('<script type="text/javascript">
    function pop_up5()
    var l_url=window.opener.document.getElementById("p_single_store_pc").value;
    window.open(l_url, '''', ''fullscreen=no, scrollbars=1'');
    </script>' );
    Edited by: user11970612 on Jun 14, 2012 5:02 AM

    this is probably due to the Javascript code and not a "real link" to another page... I don't know if the null is due to the Javascript...
    But if you really really want to use javascript instead of a ... you can pass the location of the url with JSP (on your main page) as a parameter to the open window... (...) u can put instead of main.jsp <%= request.getServerName()+request.getRequestURI() %>
    the value <%= ... %> will return something like test.com/html/main.jsp
    Hope this helps.

  • I would like to upload a excel file using jsp

    Hi,
    I would like to upload the excel file using jsp in my netbeans ide. Please help.
    I don Know what is the error in this jsp file. It is not showing any thing and the file is also not getting uploaded.
    Please gothru the code below.
    <%@ taglib uri="/WEB-INF/struts-bean.tld" prefix="bean" %>
    <%@ taglib uri="/WEB-INF/struts-html.tld" prefix="html" %>
    <%@ taglib uri="/WEB-INF/struts-logic.tld" prefix="logic" %>
    <%@ page import="java.io.*" errorPage="err.jsp"%>
    <%@page contentType="text/html"%>
    <%@page pageEncoding="UTF-8"%>
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <link href="<html:rewrite page="/design.css" />" rel="stylesheet" type="text/css">
    <title>Upload Page</title>
    </head>
    <body onKeyDown="DisablingBackFunctionality()" onLoad="DisablingBackFunctionality()">
    <html:form action="download" >
    <div style="position:absolute; left:100;top:200;">Select an excel File :<input type="file" name="uploadfile"></div>
    <div style="position:absolute; left:190;top:250;"><input type="submit" name="Submit" value="Read"></div>
    <div style="position:absolute; left:336;top:250;"><input type="reset" name="Reset" value="Clear"></div>
    mainmenu
    </html:form>
    </body>
    </html>
    <%
    String contentType = request.getContentType();
    if ((contentType != null) && (contentType.indexOf("multipart/form-data") >= 0)) {
    DataInputStream in = new DataInputStream(request.getInputStream());
    int formDataLength = request.getContentLength();
    byte dataBytes[] = new byte[formDataLength];
    int byteRead = 0;
    int totalBytesRead = 0;
    while (totalBytesRead < formDataLength) {
    byteRead = in.read(dataBytes, totalBytesRead, formDataLength);
    totalBytesRead += byteRead;
    String file = new String(dataBytes);
    //out.println("<br> file :"+file);
    String saveFile = file.substring(file.indexOf("filename=\"") + 10);
    //out.println("<br> savefile :"+saveFile);
    saveFile = saveFile.substring(0, saveFile.indexOf("\n"));
    //out.println("<br> now file1 :"+saveFile);
    saveFile = saveFile.substring(saveFile.lastIndexOf("\\") + 1, saveFile.indexOf("\""));
    //out.println("<br> now file2 :"+saveFile);
    //out.print(dataBytes);
    String ext = "";
    if (saveFile.indexOf(".") != -1) {
    ext = saveFile.substring(saveFile.lastIndexOf("."));
    int lastIndex = contentType.lastIndexOf("=");
    //out.println("<br>lst index of"+lastIndex);
    String boundary = contentType.substring(lastIndex + 1, contentType.length());
    //out.println("<br> boundary"+boundary);
    //out.println("<br> file :"+file);
    int pos;
    pos = file.indexOf("filename=\"");
    //out.println("<br> now 0 :"+pos);
    pos = file.indexOf("\n", pos) + 1;
    //out.println("<br>now 1 :"+pos);
    pos = file.indexOf("\n", pos) + 1;
    //out.println("<br>now 2 :"+pos);
    pos = file.indexOf("\n", pos) + 1;
    //out.println("<br>now 3"+pos);
    int boundaryLocation = file.indexOf(boundary, pos) - 4;
    int startPos = ((file.substring(0, pos)).getBytes()).length;
    int endPos = ((file.substring(0, boundaryLocation)).getBytes()).length;
    FileOutputStream fileOut = new FileOutputStream("D:\\" + saveFile);
    //FileOutputStream fileOut = new FileOutputStream(saveFile);
    //fileOut.write(dataBytes);
    fileOut.write(dataBytes, startPos, (endPos - startPos));
    fileOut.flush();
    fileOut.close();
    session.setAttribute("fil", saveFile);
    //out.println("File saved as " +saveFile);
    %>
    <script type="text/javascript" >
    function DisablingBackFunctionality()
    var URL;
    var i ;
    var QryStrValue;
    URL=window.location.href ;
    i=URL.indexOf("?");
    QryStrValue=URL.substring(i+1);
    if (QryStrValue!='X')
    window.location=URL + "?X";
    </script>
    Please let me know the result as soon as possible. Its my very urgent.
    Thanking Yu,
    Muthu Kumar.R

    No.
    Mylenium

Maybe you are looking for

  • Backing Up To An External DVD Drive. Any Suggestions?

    I have a question please? How do I change settings in iTunes to backup to an external "DVD" drive instead of an internal "Cd" drive? Everytime I try to back things up in iTunes, the only option I see is to backup to Cd. I rarely backup anything to Cd

  • Bdc recording for mm01

    hi all, this is an extract of materail master upload for mm01 when i execute this recording purchase order text view doesnot get populated with text. anybody can tell me whts wrong with this????? perform bdc_field       using 'MAKT-MAKTX'            

  • How to download or upgrade to the io5 system on my iPad 2?  Thanking everyone in advance for assisting me.

    How to download or upgrade to the ios5 on my iPad 2 .  Thanking you in advance for assisting me.

  • Warning messages on my RV180 router

                 I have noticed I am getting the following message more than once a second.  Just not sure what it means. Wed Dec 5 12:31:55 2012(PST) [rv180][Kernel][KERNEL] [793941.270000] cmd 35313 is not SIOCDEVPRIVATE(35312) Wed Dec 5 12:31:55 2012(

  • Sandisk SD Card won't download images

    A friend of mine is having trouble opening Raw images he shot on D800 Nikon. They won't open on his Macbook Pro, but I can open them on my IMac. Any advice?