Global Javascript vars in jQuery selector callback function

I am trying to call Ajax with jQuery and need to pass a variable that is set with PHP on the page load, to two separate functions to either move my calendar forward or backwards by the months.

var ajax_load = "Loading...",
    loadUrl = "calendar_backend.php",
    month = parseInt(<?php echo $month ?>);
    console.log(month);
    month = <?php echo $month ?>;

$("#calendar_box").on("click",'#next_month',function(){  
    console.log(month);
    $("#calendar")  
        .html(ajax_load)  
            .load(loadUrl, "month=" + month + "&go=next");
    var month = ++month;

    console.log(month);
});

$("#calendar_box").on("click",'#previous_month',function(){  
    $("#calendar")  
        .html(ajax_load)  
            .load(loadUrl, "month" + month + "&go=previous");  
    var month = --month;
});

I have the console calls in there to try to debug this and I get 4 from the first .log() undefined from the second one, and NaN from the third. From those three I can see that the variable is not getting passed into the .on() handler function.

The calender generating page is included_once on the index page and then the AJAX would be used to regenerate the correct data for the month. I need the month passed in the get string to know how far from the current month i need to offset.

Thanks for the help!!

Answers


Simply don't use the var keyword inside the function body. var will instanciate a new variable inside the success function. And you using the decress/incresse operator wrong, its only month++; and month--;

var ajax_load = "Loading...",
    loadUrl = "calendar_backend.php",
    month = parseInt(<?php echo $month ?>);
    console.log(month);
    month = <?php echo $month ?>;

$("#calendar_box").on("click",'#next_month',function(){  
    console.log(month);
    $("#calendar")  
        .html(ajax_load)  
            .load(loadUrl, "month=" + month + "&go=next");
    month++; // Removed var and incressing

    console.log(month); 
});

$("#calendar_box").on("click",'#previous_month',function(){  
    $("#calendar")  
        .html(ajax_load)  
            .load(loadUrl, "month" + month + "&go=previous");  
    month--; // Removed var and decressing
});

Need Your Help

Using Smartcard to enter UserID in my Java form

java smartcard javacard

I am very new to Java and Smartcard programming. I have this requirement which looks simple but I am unable to find the exact resource till now.