rohtakdev
rohtakdev

Reputation: 976

Javascript top.navigation NOT working with JSF Primefaces

I am trying to redirect users when they click on a button via javascript. So something like this :

top.location=url;

Normally this redirects you to the specified "url" but strangely enough user is being redirected to same page.

Is there a way to redirect a user using javascript that works with Primefaces ? Not sure why primefaces is interfering.

<div> 
   <p:commandButton value="Cancel" onclick="javascript:$.fn.RedirectMe('http://google.com')" />
</div>

Javascript:

$.fn.RedirectMe = function(url) {      
        var confirmBox=confirm("Are you sure ?");
        if (confirmBox==false)
          {
           return false;
          }

        if(typeof(url) =="undefined" || url == null || url==""){
            top.location=top.location;
        }else{
            url = encodeURI(url);
            top.location=url;
        }


    };

Upvotes: 0

Views: 340

Answers (1)

BalusC
BalusC

Reputation: 1108567

The <p:commandButton> submits by default the parent form via an ajax POST request. It's thus essentially the wrong tool for the job.

Use <p:button> instead. Don't forget to return false, otherwise it'll still perform the implicit navigation.

<p:button ... onclick="$.RedirectMe(url); return false;" />

Unrelated to the concrete problem, the javascript pseudoprotocol makes no sense in HTML4/5 compatible event handler attributes as it's the default already. Further, the $.fn mapping is unnecessary when you just want to invoke the function rather than creating it. The abovegiven answer has already taken that into account. Last but not least, JS naming conventions state that function names should start with lowercase.

Upvotes: 1

Related Questions