claudios
claudios

Reputation: 6656

Execute a function after changing location.href

I want to call a function after redirecting the page.

Inside my function I put a parameter which is an ID but when I check the console it wont display. I know I can be able to run it via on click event but I wont get the ID param from the previous page.

Is there a way to get it done?

Code:

function encode(item_id){
  $('.js-encode').click(function(){
    var url = $(this).data('url');
    location.href = url; // new url
    save(item_id); // call function after new url finish loading
  });
}

function save(item_id){
  console.log(item_id); // check if there's item_id exists
}

Upvotes: 1

Views: 6663

Answers (3)

Rocket Risa
Rocket Risa

Reputation: 383

I agree with Katana's comment. Anything after your redirect statement will not run because the page itself is redirecting. One way that I would suggest to still get the item_id and get around that barrier, would be to include the item_id in the redirect url as a parameter. Then once on the new page, parse that parameter out of the url and save the item_id.

A great example from Cory Laviska's article on Parsing URLs in Javascript, shows how you can get the individual parameters from a URL.

Building onto Manish' answer:

Function on the current page:

function encode(item_id){
    $('.js-encode').click(function(){
    var url = $(this).data('url');
    location.href = url+'?saved_item_id='+item_id; // new url
    });
}

Function on the REDIRECTED Page (assuming you only have one parameter)

$( document ).ready(function() {
     var url = $(this).data('url');
     var item_id = url.queryKey['saved_item_id'];
     save(item_id);
 });

It may need a few tweeks because I didn't test the code, but hopefully it'll get you on the right track. :)

Hopefully this helps. If it helps and/or answers your question, please select as answer and up vote! :D Feel free to let me know if you have any questions

Upvotes: 5

Regs Isabelo Jr.
Regs Isabelo Jr.

Reputation: 29

Try this one

The container is the section of your page where you perform an action.

function encode(item_id){
  $('.js-encode').click(function(){
    var url = $(this).data('url');
    $("#container").load(url,function(){
        // other stuffs and functionalities
         save(item_id); // call function after new url finish loading
    });
  });
}

Upvotes: 2

Manish
Manish

Reputation: 247

You can try something like this.

function encode(item_id){
  $('.js-encode').click(function(){
    var url = $(this).data('url');
    location.href = url+'?saved_item_id='+item_id; // new url
    //save(item_id); // call function after new url finish loading
  });
}

/*(function save(item_id){
  console.log(item_id); // check if there's item_id exists
}*/

Further more , On New redirected URL you can get item_id which was appended to URL in previous page.

Hope this may help.

Upvotes: 1

Related Questions