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

PHP, Dwoo - Variables

php dwoo

I'm trying to convert this to dwoo:

how do I return a boolean from a java program to a CentOS shell script?

java linux shell centos

A shell script run on a CentOS 7 server needs to pass three parameters to a java program, and then read a Boolean value returned by the Java program as a result of operations done on the three

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.