• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 7854
  • Last Modified:

Javascript function and jsp session attributes.

Hi all.
I set a session attribute in my jsp, which is writing out to the logs perfectly, and the data is right. however, after setting the session attribute,  ... code bit looks like this

while (rsSCOComments.next()) {
                        comments = rsSCOComments.getString("Comment");
                        session.setAttribute("SCOCOMMENT", comments);
                        System.out.println("sco comment is: " + session.getAttribute("SCOCOMMENT"));
                        %>
                        <script>showComments()</script>
                        <%
                  }
i'm calling a showComments() javascript method which opens a popup window and pre-populates the content ....

and the bit of the method...
tmp.write('<td div id="SUBLEFT"><p><%=session.getAttribute("SCOCOMMENT")%></p>'); returns null.

the showComments() method is defined at the top of the page..

what am i doing wrong?
Can anyone please assist?
Many thanks.
bg.
0
blue-genie
Asked:
blue-genie
  • 12
  • 11
  • 5
1 Solution
 
TimYatesCommented:
That's because the JSP is run before the javascript...

So the loop has no meaning here, as each call will overwrite the last, and as the function is at the top of the page, it will be null (as the code which puts the value in the session has not yet been run)

Basically, you can't do it this way (as JSP is run on the server, and javascript on the client)

What you need to do, is make your showComments function take parameters, and do:

               while (rsSCOComments.next()) {
                    comments = rsSCOComments.getString("Comment");
                    %>
                    <script>showComments( '<%= comments %>' )</script>
                    <%
               }

Not forgetting that if your "comments" contains a quote ('), it will need escaping so that it doesn't break your javascript call...

Something like:

               while (rsSCOComments.next()) {
                    comments = rsSCOComments.getString("Comment");
                    if( comments != null ) comments = comments.replaceAll( "'", "&quot;" ) ;
                    %>
                    <script>showComments( '<%= comments %>' )</script>
                    <%
               }
 Tim
0
 
blue-genieAuthor Commented:
Hi thanks for that. I thought about that but since you say the jsp is run before the javascript, then surely the session attribute is available when the javascript is called?

anyway gonna try that out, will let you know thanks.
it either picks up null, or it picks up the previous session attribute, ie. 1 step late.

0
 
TimYatesCommented:
>> then surely the session attribute is available when the javascript is called?

Not really...

Imagine this situation:

    <script>
        function a()
        {
            alert( '<%= session.getAttribute( "hi" ) %>' ) ;
        }
    </script>
    <%
        session.setAttribute( "hi", "Hello!" ) ;
    %>
    <script>a();</script>

Now, the first time the page is requested, the JSP code is run, and the HTML is returned to the browser:

    <script>
        function a()
        {
            alert( 'null' ) ;  // THIS IS NULL, AS NOTHING HAS BEEN SET YET IN THE SESSION
        }
    </script>
    // HERE, THE SESSION IS SET UP.  BUT IT'S TOO LATE
    <script>a();</script>

The second time the page is run by the same user, the session will already have been set up, so in this example it will work as expected  (but it is not working, the fact it looks right will just be fooling you)

Hope this explains it a bit better...

Feel free to ask as many questions as you want, it can be a bit confusing the first time :-D

Tim
0
VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

 
Michel PlungjanIT ExpertCommented:
Perhaps that is a new session.

Instead do this:


while (rsSCOComments.next()) {
                    comments = rsSCOComments.getString("Comment");
                    session.setAttribute("SCOCOMMENT", comments);
                    System.out.println("sco comment is: " + session.getAttribute("SCOCOMMENT"));
                    %>
<script>
comment = "<%=comments%>";
showComments()
</script>
 <%
               }
%>

and do
  tmp.write('<td div id="SUBLEFT"><p>'+opener.comments+'</p>');

or perhaps better:

<script>
comments = new Array()
<%
while (rsSCOComments.next()) {
%>comments[comments.length]="<%= rsSCOComments.getString("Comment") %>";
<% } %>
showComments()
</script>

and use
for (i=0;i<opener.comments.length;i++) {
  tmp.write('<td div id="SUBLEFT"><p>'+opener.comments[i]+'</p>');
}

0
 
Michel PlungjanIT ExpertCommented:
Ohh. I took too long
0
 
blue-genieAuthor Commented:
Ok, Tim, I'm being really thick here, but ...
how do i then parse it through here....

tmp.write('<td div id="SUBLEFT"><p>??????here??????</p>');
so as to not parse through a string?
if i have function showComments(comment)

i'm not sure i'm making sense ....
0
 
TimYatesCommented:
<script>
    function showComments( comment )
    {
        alert( '<td div id="SUBLEFT"><p>' + comment + '</p>' ) ;
    }
<script>

Tim
0
 
blue-genieAuthor Commented:
doh!!
and i can't even blame it on mondays.
thanks :-)
0
 
TimYatesCommented:
heheh...tuesdays are just as bad in my experience ;-)

Does the JSP/javascript boundary stuff make sense now?

As I said, feel free to ask if there's something that doesn't quite click with you :-)

Tim
0
 
blue-genieAuthor Commented:
it's currently returning undefined now, instead of null .... progress???

what you explained does make sense - your solution is suggesting not using the session attribute right? my comments declaration... as in

String comments = "";
happens outside the while (resultset) - so technicall i shouldn't need to clearr it, should revert to an empty string right?

i'm busy fiddling with some if statements to see if i can make this code dance the way i want it to :-)
0
 
TimYatesCommented:
You are calling it like this aren't you?

               while (rsSCOComments.next()) {
                    comments = rsSCOComments.getString("Comment");
                    if( comments != null ) comments = comments.replaceAll( "'", "&quot;" ) ;
                    %>
                    <script>showComments( '<%= comments %>' )</script>
                    <%
               }

can you post your code as it stands now?
0
 
blue-genieAuthor Commented:
ok, off on a tangent for a bit,
in my database, there could be more than 1 comment per activity, so i need to concatenate those comments into one string. but i can't call the method in the while, cause i want 1 pop up with all the comments, rather than 2 pop ups.
if i take the method call out, var comments then is not available, so ..... ????
0
 
TimYatesCommented:
make an array like mplungan suggested...

    <script>
        var comments = new Array() ;
        <%
            int i = 0 ;
            while (rsSCOComments.next()) {
                comments = rsSCOComments.getString("Comment");        
                out.println( "comments[ " + i + "] = '" + comments.replaceAll( "'", "&quot;" ) + "'" ) ;
            }
        %>
        showComments( comments ) ;
    </script>

Then, in your javascript function:

    function showComments( comments )
    {
        var aLen = comments.length ;
        for( i = 0 ; i < aLen ; i++ )
        {
            alert( 'Comment #' + i + ': ' + comments[ i ] ) ;
        }
    }

Tim
0
 
blue-genieAuthor Commented:
ok, this is what i've done so far....

while (rsSCOComments.next()) {
                    comments += rsSCOComments.getString("Comment");
                              
                    if (( comments != null) || (!comments.equals("")))
                              {      
                                    comments = comments.replaceAll( "'", "`" ) ;
                    }
                              %>
                    <script>showComments('<%= comments %>')</script>
                    <%
          }

opens the window twice, but in quick succession - so a user that's not too alert will probably not notice, and it's concatenating the 2 strings.....
not tidy.
Will try the array option.
:-)
this is fun!!!!
0
 
TimYatesCommented:
just spotted in my code, that:

              out.println( "comments[ " + i + "] = '" + comments.replaceAll( "'", "&quot;" ) + "'" ) ;

should be:

              out.println( "comments[ " + i + "] = '" + comments.replaceAll( "'", "&quot;" ) + "' ;" ) ;

;-)
0
 
blue-genieAuthor Commented:
OKay, i'll understand if your patience is wearing thin about now,
but here...
comments += rsSCOComments.getString("Comment"); throws a 'cannot resolve symbol' error

here's the code....
synchronized (stmtSCOComments)
{
      stmtSCOComments.setInt(1, activityID);
      rsSCOComments = stmtSCOComments.executeQuery();
}
%>
<script>
            var comments = new Array() ;
       <%
            int j = 0 ;
            while (rsSCOComments.next()) {
                comments = rsSCOComments.getString("Comment");        
                 out.println( "comments[ " + i + "] = '" + comments.replaceAll( "'", "&quot;" ) + "' ;" ) ;
            }
              %>
             showComments( comments ) ;
   </script>



 
0
 
TimYatesCommented:
   <script>
           var comments = new Array() ;
       <%
            int j = 0 ;
            while (rsSCOComments.next()) {
                String cmnt = rsSCOComments.getString("Comment");        
                 out.println( "comments[ " + j + " ] = '" + cmnt.replaceAll( "'", "&quot;" ) + "' ;" ) ;
                 j++ ;
            }
             %>
            showComments( comments ) ;
   </script>

0
 
blue-genieAuthor Commented:
Tim, we're so close I can smell it.
It's working great in terms of pulling the right comment for the right activity. Yah!!!

But, now when nothing is selected, it's calling the method anyway and returning an empty string.
explain something to me.....

my comments array is declared outside the while loop, after the while loop, if i try to say
if (comments.length() > 0) {
 it can't find the comments symbol  - is this scope issue due to the jsp scripts inside the <script> tags?
also, the out.print, is that actually adding something to the array? or is that simply printing it out.
What would the syntax be (just out of curiosity) to add the item to the array without the out.println?

i think this is the last step, i promise.
ta.
bg
:-)
0
 
blue-genieAuthor Commented:
wooohoo, i had a light bulb moment.

array.length not array.length() - confusing with java vector.size()

grrrrr.
young man, u're a genius, thank you very much.

bg.
:-)
0
 
TimYatesCommented:
Can you post the proper code then?  When is the method suypposed to be called?  When a user clicks on something?

How is this performed?

Do you have more than one thing that can have comments on the same page?

As the JSP is run before the page gets to the user, you will have to get ALL the comments for ALL the items first, then send it all back to the user

Or else you will need to use some sort of XmlHTTP object to call the webserver to fetch comments for a specific item...

Without seeing the code and the context it's in, it's hard to say :-/

Tim
0
 
TimYatesCommented:
>> wooohoo, i had a light bulb moment.

Yay! :-D

Cool! :-D

Glad we got this sorted out :-)

Good luck with it all!  And thanks!! :-D

Tim
0
 
Michel PlungjanIT ExpertCommented:
Hmm...
0
 
blue-genieAuthor Commented:
mplungjan, sorry, i didn't forget about you, but i figured since i was going along with Tim's option and he was holding my hand all the way (so to speak) - i gave him all the points.
Don't be dissed!!!!

i thank u anyway, although i suppose it don't mean too much.

0
 
Michel PlungjanIT ExpertCommented:
I was more or less expecting a split since my

<script>
comments = new Array()
<%
while (rsSCOComments.next()) {
%>comments[comments.length]="<%= rsSCOComments.getString("Comment") %>";
<% } %>
showComments()
</script>

and use
for (i=0;i<opener.comments.length;i++) {
  tmp.write('<td div id="SUBLEFT"><p>'+opener.comments[i]+'</p>');
}

and Tim's

 <script>
           var comments = new Array() ;
       <%
            int j = 0 ;
            while (rsSCOComments.next()) {
                String cmnt = rsSCOComments.getString("Comment");        
                 out.println( "comments[ " + j + " ] = '" + cmnt.replaceAll( "'", "&quot;" ) + "' ;" ) ;
                 j++ ;
            }
             %>
            showComments( comments ) ;
   </script>

only differs in complexity (I would say mine is simpler) and the replace, which I would personally would consider doing like this:


<script>
comments = new Array()
<%
while (rsSCOComments.next()) {
%>comments[comments.length]="<%=  java.net.URLEncoder(rsSCOComments.getString("Comment"),"UTF-8") %>";
<% } %>
showComments()
</script>

and use
for (i=0;i<opener.comments.length;i++) {
  tmp.write('<td div id="SUBLEFT"><p>'+unescape(opener.comments[i])+'</p>');
}
0
 
TimYatesCommented:
URLEncoder wouldn't work, but if you want to reopen this question for a split, I am more than happy.

It's up to you blue-genie :-)

Tim
0
 
Michel PlungjanIT ExpertCommented:
Why would that not work???
0
 
TimYatesCommented:
Sorry, I missed the "unescape" call in the javascript ;-)

I forgot to engage my brain before posting ;-)
0
 
blue-genieAuthor Commented:
wait. plungjan, u can help me format my code nicely....
see new post.
0

Featured Post

Keep up with what's happening at Experts Exchange!

Sign up to receive Decoded, a new monthly digest with product updates, feature release info, continuing education opportunities, and more.

  • 12
  • 11
  • 5
Tackle projects and never again get stuck behind a technical roadblock.
Join Now