I'm having a problem when trying to reset a variable inside an button event in jquery. This variable represents the page loaded in div. Then with the setInterval function I refresh the div element with the page stored in the variable. This is the code:
$( document ).ready(function() {
var current_page="data.php"; //For update-the first page shown is data.php
//At startup
$("#content").load("/data.php",function(response){
//current_page="data.php"; The first command-current_page already set to "data.php"
if(response=="0"){
location.href="http://website.com";
}
});
//JS refresh timer
setInterval(function(){
alert(current_page); //Always shows 'data.php'->means it is not updated
if(current_page!="insert.php"){
$("#content").load("/"+current_page,function(response){
if(response=="0"){
location.href="http://website.com";
}
});
}
},5000); //5 seconds
//EVENTS
//Menu links pressed
$(".menu_link").click(function(){
var page=$(this).attr("data-page");
current_page=page; //Here it works.
$("#content").load("/"+page,function(response){
if(response=="0"){
location.href="http://website.com";
}
});
});
});
//Outside Jquery 'document'
//Select user button pressed
function loadData(){
var user_id=$("#menu_selector option:selected").val();
current_page="users.php?user_id="+user_id; //Not globally updated;inside function it is set.
$("#content").load("/users.php?user_id="+user_id,function(response){
if(response=="0"){
location.href="http://website.com";
}
});
}
I tested the current_page's value by putting in my code "alert" statements. The conclusion: in the setInterval function the current_page variable is always set to "data.php". If I remove the first line var current_page="data.php"; then current_page is 'undefined'. It looks like it is not updated by the loadData function.
I also tried moving the loadData function inside the JQuery load but then the button can't find it(I used <button onclick="loadData();">Load page</button>)
Where is the problem?