html loads a new page before the jquery finishes the execution

50 views Asked by At

I want to change the value of variable in jquery when the anchor html tag with link is clicked , this tag also loads new page but when I click on that anchor tag new page is loaded but the variable value is not changed.

I looked on the internet and I found that this is due to asynchronous nature of jquery.

here is my code:-


var req;
$(document).ready(function(){
    $('header').load("navbar.html");
    $('footer').load("footer.html");
    $('#veg-caterer').click(function(){
        req = "c1";
    });
});


in the above code the new html page is loaded when i click on #veg-caterer before changing the value of req

I am checking the value of req on other page using alert and it shows undefined here is code :-

$(document).ready(function(){
    alert(req);
});

I have tried using URL get parameters , setTimeout but there is also I am facing same problems.I know its basic but I am bit new to jquery and js. Please explain your answers

My main motive is to pass the value to other js file when that anchor tag with link is clicked

1

There are 1 answers

2
Anish On

You can do a preventDefault on the click event, and then manually set the location of the page after you have set the value of req

$('#veg-caterer').click(function(e){
    e.preventDefault();
    req = "c1";
    window.location = e.currentTarget.getAttribute('href');
});