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.
LVL 39
blue-genieAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

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
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.

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
Determine the Perfect Price for Your IT Services

Do you wonder if your IT business is truly profitable or if you should raise your prices? Learn how to calculate your overhead burden with our free interactive tool and use it to determine the right price for your IT services. Download your free eBook now!

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>');
}

Michel PlungjanIT ExpertCommented:
Ohh. I took too long
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 ....
TimYatesCommented:
<script>
    function showComments( comment )
    {
        alert( '<td div id="SUBLEFT"><p>' + comment + '</p>' ) ;
    }
<script>

Tim
blue-genieAuthor Commented:
doh!!
and i can't even blame it on mondays.
thanks :-)
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
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 :-)
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?
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 ..... ????
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

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
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!!!!
TimYatesCommented:
just spotted in my code, that:

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

should be:

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

;-)
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>



 
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>

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
:-)
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.
:-)
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
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
Michel PlungjanIT ExpertCommented:
Hmm...
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.

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>');
}
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
Michel PlungjanIT ExpertCommented:
Why would that not work???
TimYatesCommented:
Sorry, I missed the "unescape" call in the javascript ;-)

I forgot to engage my brain before posting ;-)
blue-genieAuthor Commented:
wait. plungjan, u can help me format my code nicely....
see new post.
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
JavaScript

From novice to tech pro — start learning today.