Skip to content Skip to sidebar Skip to footer

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

Solution 1:

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:

functionencode(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

Solution 2:

Try this one

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

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

Solution 3:

You can try something like this.

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

Post a Comment for "Execute A Function After Changing Location.href"