ova2 / primefaces-cookbook

PrimeFaces Cookbook - recipes to leading JSF component suite
http://ova2.github.com/primefaces-cookbook/
100 stars 92 forks source link

re: executing javascript from java #6

Closed eekremer closed 9 years ago

eekremer commented 9 years ago
Hello Oleg !

I am currently engaged in developing a web project using PrimeFaces. I bought your cookbook (pretty insightful !). I am putting in practice some concepts shown on this book, but I cannot execute a javacript from java. In short, I need "to click a button from java". I debugged and logged it, checked the browser's console for errors (none), tried jQuery's different notations ($, jQuery, PF), but nothing. I also reviewed the page's source code and jQuery plugin is there. Any hints is welcome ! Thanks in advance,

Ed Kremer
user.xhtml
...
<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
    xmlns:h="http://xmlns.jcp.org/jsf/html"
    xmlns:f="http://xmlns.jcp.org/jsf/core"
    xmlns:p="http://primefaces.org/ui"
    xmlns:ui="http://xmlns.jcp.org/jsf/facelets">
<f:view contentType="text/html">
    <div style="padding-right: 20px;">
        <h:form prependId="false" id="userData">

            <h:outputText id="indicator" value="Enabled? - #{LoginController.loggedIn}"/>

            <p:commandButton id="btn2" widgetVar="btn2"
                value="enable cash-in !" onclick="java.enableBillValidator()" />
...
LoginController.java
if (password.equals(loggedCustomer.getPassword())) {
        if (loggedCustomer.getPassword() == null) {
            password = "";
            password2 = "";
            msg = "Error este usuario no tiene su clave seteada. Contacte al administrador.";
            rc.execute("PF('dlgmsg').show();");
        } 
        else {
            loggedIn = true;
            script1 = "PF('btn2').show();";
            script2 = "$('btn2').show();";
            script3 = "$('btn2').show();";  
            rc.execute(script1);
            rc.execute(script2);
            rc.execute(script3);
            try {
                ExternalContext ec = FacesContext.getCurrentInstance()
                        .getExternalContext();
                ec.redirect(((HttpServletRequest) ec.getRequest())
                        .getRequestURI());
            } catch (IOException e) {
                log.error("Error inesperado.", e);
            }
        }
    } else {
        msg = "Contraseña incorrecta, reintente.";
        rc.execute("PF('dlgmsg').show();");
    }
}
ova2 commented 9 years ago

You have to look the button's client ID in Firebug or Chrome Dev. Tool. (in HTML). If you know the full client ID, you can write (assume the full client ID is mainForm_btn2):

rc.execute("$('#mainForm_btn2').show();");

Please note the # sign for jQuery's ID. Alternative, you can set an unique style class on the button

<p:commandButton id="btn2" styleClass="myButton" .../>

and reference the button by this style class as follows:

rc.execute("$('.myButton').show();");

Report here please if this that solved your problem and give us 5 stars on amazon :-) http://www.amazon.com/PrimeFaces-Cookbook-Edition-Mert-Caliskan/dp/1784393428 Thanks!

eekremer commented 9 years ago

Hi Oleg,

Thanks for your prompt response !, but I am still stuck on this problem. I've double-debugged the code and it's reading correctly the jquery's script. I think I might be executing the javascript before the view is rendered. Is it possible or by default primefaces completes the whole lifecycle before executing the javascript ?

I will post a 5-star comment on Amazon !

Cheers

Ed

On Thu, Jun 18, 2015 at 3:49 AM, Oleg Varaksin notifications@github.com wrote:

You have to look the button's client ID in Firebug or Chrome Dev. Tool. (in HTML). If you know the ID, you can write:

rc.execute("$('#mainForm_btn2').show();");

Please note the # sign for jQuery's ID. Alternative, you can set an unique style class on the button

<p:commandButton id="btn2" styleClass="myButton" .../>

and reference the button by this style class as follows:

rc.execute("$('.myButton').show();");

Report here please if this that solved your problem and give us 5 stars on amazon :-) http://www.amazon.com/PrimeFaces-Cookbook-Edition-Mert-Caliskan/dp/1784393428 Thanks!

— Reply to this email directly or view it on GitHub https://github.com/ova2/primefaces-cookbook/issues/6#issuecomment-113054550 .

ova2 commented 9 years ago

It is not possible to execute the JavaScript code BEFORE the view is rendered :-). The JS Code will be executed in DOM ready event. That mean short before window.onload.

What is the problem exactly? Where do you have rc.execute(...)? It should be in a quite normally action in bean.

eekremer commented 9 years ago
Hi Oleg,

Thanks for your comments regarding the fact that JavaScript code is executed after the view is rendered (I was not certain!). However, when I force the page reload in the managed bean by using the ExternalContext class, this seems to prevent the JavaScript code from executing (please see code below). On the opposite, if I remove the ExternalContext code lines from the bean, the JavaScript code is executed correctly, but the page is not reloaded and I need it to do so. Any suggestions welcome ! (by the way: I just sent a mail to Amazon customer service because though your cookbook 2nd edition is among my purchases, the site will not allow me to post my comments on it. I shall have news for you shortly) Cheers Ed Kremer

                ....
                loggedIn = true;

                rc.execute("$('#btn2').click();");
                log.info("about to execute script... ");

                try {
                    ExternalContext ec = FacesContext.getCurrentInstance().getExternalContext();
                    ec.redirect(((HttpServletRequest) ec.getRequest()).getRequestURI());

                } catch (IOException e) {
                    log.error("Error inesperado.", e);
                }

            }
ova2 commented 9 years ago

Ah, you're doing redirect to the same page. This will not work because these are two request then. POST (you action will be executed) - Response to the browser (JS will be executed) - GET (by reason of redirect) - Response to the browser. Why do you need a redirect? Can you not only use POST? Simple execute your action in bean with return value void.

If you really need a redirect to another page, this another page should have a script block with JS logic (click on the btn2 button). See the book, the last chapter with examples.

eekremer commented 9 years ago

Hi Oleg, as requested find below my review I just posted on Amazon.com.

Byeduardo kremer http://www.amazon.com/gp/pdp/profile/A2EBKC6CSNAORD/ref=cm_cr_pr_pdp?ie=UTF8on June 20, 2015 Format: Paperback http://www.amazon.com/PrimeFaces-Cookbook-Edition-Mert-Caliskan/product-reviews/1784393428/ref=cm_cr_pr_rvw_fmt?ie=UTF8&sortBy=byRankDescending&formatType=current_formatVerified Purchase http://www.amazon.com/PrimeFaces-Cookbook-Edition-Mert-Caliskan/product-reviews/1784393428/ref=cm_cr_pr_rvw_rvwer?ie=UTF8&reviewerType=avp_only_reviews&sortBy=byRankDescending I recommend this book to anyone who is engaged (or plan to be) in implementing a JSF project and wants to take advantage of PrimeFaces' fast-paced development edge. Though PrimeFaces is a powerful library on JSF which allows you to greatly speed up your web project development compared to other technologies, it involves high abstraction so you need a good sidekick (book) in order to beat your project's challenges. In my case, I wanted to get both a grasp on PrimeFaces and also a step-by-step walk-through on how to solve some complex situations (Chapter 10 Advanced Use Cases: a MUST !!!). Chapter 5 clearly explains essentials such as: sorting, listing, and visualizing data by using data iteration components. The book's GitHub allows you to build and run its projects in a snap of finger all at once ! If you actually want to take full advantage of this book you need to have some understanding on JSF, jQuery, CSS, and HTML. CommentLooking for voting buttons? Sorry, we don't let customers vote on their own reviews.Report abuse http://www.amazon.com/gp/voting/cast/Reviews/2115/R3KPGEFGX86DVB/Inappropriate/1/ref=cm_cr_prvoteyn?ie=UTF8&target=L3NzL2N1c3RvbWVyLXJldmlld3MvMTc4NDM5MzQyOC9yZWY9Y21fY3JfZHBfc2VlX2FsbF9zdW1tYXJ5&token=6044CD05BF34F28366A8A3B2574CA7576AB7DEF8&voteAnchorName=R3KPGEFGX86DVB.2115.Inappropriate.Reviews&voteSessionID=177-3571880-0508644&type=popup

On Sat, Jun 20, 2015 at 2:51 PM, Oleg Varaksin notifications@github.com wrote:

Ah, you're doing redirect to the same page. This will not work because these are two request then. POST (you action will be executed) - Response to the browser (JS will be executed) - GET (by reason of redirect) - Response to the browser. Why do you need a redirect? Can you not only use POST? Simple execute your action in bean with return value void.

If you really need a redirect to another page, this another page should have a script block with JS logic (click on the btn2 button). See the book, the last chapter with examples.

— Reply to this email directly or view it on GitHub https://github.com/ova2/primefaces-cookbook/issues/6#issuecomment-113793373 .

eekremer commented 9 years ago

[image: Amazon.com] Your Profile http://www.amazon.com/gp/pdp/profile/A2EBKC6CSNAORD Your Reviews http://www.amazon.com/gp/cdp/member-reviews/A2EBKC6CSNAORD?ie=UTF8&sort_by=MostRecentReview Your

Account http://www.amazon.com/gp/css/homepage.html

Dear eduardo kremer,

Congratulations! Your review on Amazon has been posted to the site. Thanks for taking the time to write about your experience with this item. Every day millions of shoppers on Amazon rely on customer reviews like yours to make smart buying choices. As you write more reviews that other customers find to be helpful, you have a shot at becoming one of our celebrity top reviewers. Would you like to add more to your review? You can always edit it here. http://www.amazon.com/review/edit-review?ie=UTF8&asin=1784393428&reviewID=R3KPGEFGX86DVB [image: Product Image] PrimeFaces Cookbook - Second Edi... http://www.amazon.com/gp/product/1784393428 ~Mert Caliskan [image: 5.0 out of 5 stars] http://www.amazon.com/PrimeFaces-Cookbook-Edition-Mert-Caliskan/product-reviews/1784393428 (1 http://www.amazon.com/PrimeFaces-Cookbook-Edition-Mert-Caliskan/product-reviews/1784393428 ) [image: 5.0 out of 5 stars] A great book !!!, June 20, 2015 By eduardo kremer http://www.amazon.com/gp/pdp/profile/A2EBKC6CSNAORD Verified Purchase(What's this? http://www.amazon.com/gp/community-help/amazon-verified-purchase) This review is from: PrimeFaces Cookbook - Second Edition (Paperback) I recommend this book to anyone who is engaged (or plan to be) in implementing a JSF project and wants to take advantage of PrimeFaces' fast-paced development edge. Though PrimeFaces is a powerful library on JSF which allows you to greatly speed up your web project development compared to other technologies, it involves high abstraction so you need a good sidekick (book) in order to beat your project's challenges. In my case, I wanted to get both a grasp on PrimeFaces and also a step-by-step walk-through on how to solve some complex situations (Chapter 10 Advanced Use Cases: a MUST !!!). Chapter 5 clearly explains essentials such as: sorting, listing, and visualizing data by using data iteration components. The book's GitHub allows you to build and run its projects in a snap of finger all at once ! If you actually want to take full advantage of this book you need to have some understanding on JSF, jQuery, CSS, and HTML. See your review on the site http://www.amazon.com/review/R3KPGEFGX86DVB Find more products to review at: http://www.amazon.com/review/review-your-purchases Share this review with friends: [image: Facebook] http://www.amazon.com:80/gp/redirect.html?_encoding=UTF8&location=http%3A%2F%2Fwww.facebook.com%2Fdialog%2Ffeed%3Fapp_id%3D164734381262%26caption%3DAmazon%26display%3Dpopup%26link%3Dhttp%253A%252F%252Fwww.amazon.com%252Freview%252FR3KPGEFGX86DVB%252Fref%253Dcm_sw_r_fa_cm_cr_notf_app_fbt%26name%3DI%2520just%2520reviewed%253A%2520%27PrimeFaces%2520Cookbook%2520-%2520Second%2520Edition%27%26redirect_uri%3Dhttp%253A%252F%252Fwww.amazon.com%252Freview%252FR3KPGEFGX86DVB%252Fref%253Dcm_sw_r_fa_cm_cr_notf_app_fbt&source=standards&token=6BD0FB927CC51E76FF446584B1040F70EA7E88E1 [image: Twitter] http://www.amazon.com:80/gp/redirect.html?_encoding=UTF8&location=http%3A%2F%2Ftwitter.com%2Fshare%3Fcount%3Dnone%26original_referer%3Dhttp%253A%252F%252Fwww.amazon.com%252Freview%252FR3KPGEFGX86DVB%252Fref%253Dcm_sw_r_tw_cm_cr_notf_app_fbt%26related%3Damazon%252Camazondeals%252Camazonmp3%26text%3DI%2520just%2520reviewed%253A%2520%27PrimeFaces%2520Cookbook%2520-%2520Second%2520Edition%27%26twitterURL%3Dhttp%253A%252F%252Fwww.amazon.com%252Freview%252FR3KPGEFGX86DVB%252Fref%253Dcm_sw_r_tw_cm_cr_notf_app_fbt%26via%3Damazon&source=standards&token=7A1A4AE8F6CE0BD277D8295E58702D283F329C0F Please note that this message was sent to the following e-mail address: eekremer@gmail.com We hope you found this message to be useful. However, if you'd rather not receive future e-mails of this sort from Amazon.com, please visit the opt-out link here. http://www.amazon.com/review/notification-opt-out/ref=cm_cr_notf_app_opt?ie=UTF8&authToken=gFDIPxOpRUmJQ8JO9XSipz6rT8dVzbTkmCdFptsAAAADAAAAAFWGENtyYXcAAAAA&customerID=A2EBKC6CSNAORD © 2015 Amazon.com, Inc. or its affiliates. All rights reserved. Amazon, Amazon.com and the Amazon.com logo and 1-Click are registered trademarks of Amazon.com, Inc. or its affiliates. Amazon.com, 410 Terry Avenue N., Seattle, WA 98109-5210. Reference: R3KPGEFGX86DVB

eekremer commented 9 years ago

Hi Oleg,

Thanks for your comments ! they're pretty insightful.

Ed

On Sat, Jun 20, 2015 at 10:22 PM, Eduardo Kremer < ekremer@nevada-entertainment.com> wrote:

Hi Oleg, as requested find below my review I just posted on Amazon.com.

Byeduardo kremer http://www.amazon.com/gp/pdp/profile/A2EBKC6CSNAORD/ref=cm_cr_pr_pdp?ie=UTF8on June 20, 2015 Format: Paperback http://www.amazon.com/PrimeFaces-Cookbook-Edition-Mert-Caliskan/product-reviews/1784393428/ref=cm_cr_pr_rvw_fmt?ie=UTF8&sortBy=byRankDescending&formatType=current_formatVerified Purchase http://www.amazon.com/PrimeFaces-Cookbook-Edition-Mert-Caliskan/product-reviews/1784393428/ref=cm_cr_pr_rvw_rvwer?ie=UTF8&reviewerType=avp_only_reviews&sortBy=byRankDescending I recommend this book to anyone who is engaged (or plan to be) in implementing a JSF project and wants to take advantage of PrimeFaces' fast-paced development edge. Though PrimeFaces is a powerful library on JSF which allows you to greatly speed up your web project development compared to other technologies, it involves high abstraction so you need a good sidekick (book) in order to beat your project's challenges. In my case, I wanted to get both a grasp on PrimeFaces and also a step-by-step walk-through on how to solve some complex situations (Chapter 10 Advanced Use Cases: a MUST !!!). Chapter 5 clearly explains essentials such as: sorting, listing, and visualizing data by using data iteration components. The book's GitHub allows you to build and run its projects in a snap of finger all at once ! If you actually want to take full advantage of this book you need to have some understanding on JSF, jQuery, CSS, and HTML. CommentLooking for voting buttons? Sorry, we don't let customers vote on their own reviews.Report abuse http://www.amazon.com/gp/voting/cast/Reviews/2115/R3KPGEFGX86DVB/Inappropriate/1/ref=cm_cr_prvoteyn?ie=UTF8&target=L3NzL2N1c3RvbWVyLXJldmlld3MvMTc4NDM5MzQyOC9yZWY9Y21fY3JfZHBfc2VlX2FsbF9zdW1tYXJ5&token=6044CD05BF34F28366A8A3B2574CA7576AB7DEF8&voteAnchorName=R3KPGEFGX86DVB.2115.Inappropriate.Reviews&voteSessionID=177-3571880-0508644&type=popup

On Sat, Jun 20, 2015 at 2:51 PM, Oleg Varaksin notifications@github.com wrote:

Ah, you're doing redirect to the same page. This will not work because these are two request then. POST (you action will be executed) - Response to the browser (JS will be executed) - GET (by reason of redirect) - Response to the browser. Why do you need a redirect? Can you not only use POST? Simple execute your action in bean with return value void.

If you really need a redirect to another page, this another page should have a script block with JS logic (click on the btn2 button). See the book, the last chapter with examples.

— Reply to this email directly or view it on GitHub https://github.com/ova2/primefaces-cookbook/issues/6#issuecomment-113793373 .

ova2 commented 9 years ago

Thank you a lot too. I hope I could help you. You can also use our forum for any kind of questions http://forum.primefaces.org/viewforum.php?f=14