Prabhu
Prabhu

Reputation: 13335

How to perform a javascript action right after redirect?

After a user creates an account on my website, I want to redirect the user to the home page and display a twitter style message bar on top. This is how I have it:

success: function (response) {
            if (response.Success) {
                location.href = response.ReturnUrl;
            } 

            ShowMessageBar(response.Message);                
        },

The message bar does appear but it gets displayed only for a second as it gets canceled by the redirect. What can I do to display the message right after the redirect has completed? Is there a complete event for the location.href? Thanks.

Upvotes: 0

Views: 851

Answers (6)

Sebastián Grignoli
Sebastián Grignoli

Reputation: 33432

This will need the Cookie plugin for jQuery:

http://plugins.jquery.com/project/Cookie

Put this somewhere in the header of your homepage:

jQuery(function($){ 
  if($.cookie("message")) {
    ShowMessageBar($.cookie("message"));
    $.cookie("message", "any_value", { expires: -1 });
});

And in your success function:

success: function (response) {
        if (response.Success) {
            $.cookie("message", response.Message);
            location.href = response.ReturnUrl;
        } 
    },

Upvotes: 2

Josiah Ruddell
Josiah Ruddell

Reputation: 29831

You need to pass it through a cookie, the quesrystring, or localStorage. Something like this using localStorage or cookies (localStorage is available in IE8+ and most other browsers):

on the current page:

if('localStorage' in window) 
    localStorage.setItem('message', response.Message);
else // use cookie

On the new page:

$(function(){
    if('localStorage' in window && !!localStorage['message']) {
         ShowMessageBar(localStorage['message']);
         localStorage.removeItem('message');
    }
    else // use cookie
});

If you are uncomfortable with these techniques there are jquery plugins that wrap this functionality. I would recommend jstorage.

Upvotes: 3

Groovetrain
Groovetrain

Reputation: 3325

If you REALLY wanted to show the message, you could always throw it in an alert before you redirect them, which would halt execution until they clicked 'ok'.

Upvotes: 0

Jason MacLean
Jason MacLean

Reputation: 513

You could send a parameter and check for its existence on document ready. Probably the easiest way of achieving the desired effect.

Upvotes: 0

Josh Weatherly
Josh Weatherly

Reputation: 1730

Sounds to me like you would need to call ShowMessageBar() from the redirected URL.

Upvotes: 0

Diodeus - James MacFarlane
Diodeus - James MacFarlane

Reputation: 114377

Once the url of a page changes all execution stops and is transferred to the new page. Pass a parameter to the new page that triggers the event you want instead.

Upvotes: 1

Related Questions