1

I am writing the following code below, which basically takes the data from the current date to a PHP file to handle in jQuery. Until here everything well. But I'm not understand why I can not have a new value of the total variable after it picks the value coming PHP file.

day.each(function () {

        var $this = $(this);
        var the_index = $this.index();
        var the_date = $this.find('h3.date').html().substr(0,2);
        var the_day = $this.find('h3.day');

        /*THIS VARIABLE*/   
        var total = 0;

        $.get('trd/datetime.php', function (date) {

            if(that.hasClass('list-'+date.day)) {
                weekList.find('.item.list-'+date.day).addClass('active');
            }

            total = date.firstDate;

        }, 'json');

        console.log(total);


    });

I don't know if my english helps, but, please, tell me what wrong I'm doing!

Thanks.

McGarnagle
  • 101,349
  • 31
  • 229
  • 260
  • Oh, thanks for the alert @Asad. I will read this questions and see if it works for me too. If not, let you know. – Gláuber Sampaio Jul 11 '13 at 00:00
  • @Asad thank you very much! That explanation has worked for me. See how I fixed the problem: I created a callback function `changeWeekDates()`, where I passed the value `date.firstDate` to execute, instead to execute in the AJAX call. Thanks again. – Gláuber Sampaio Jul 11 '13 at 00:19

1 Answers1

5

The .get call is asynchronous -- the stuff inside it runs after your console.log statement.

You probably want to use a callback, which you invoke from inside the .get handler:

$.get('trd/datetime.php', function (date) {
    // ...

    callback(total);
}, 'json');

function callback(total) {
    console.log(total);
}
McGarnagle
  • 101,349
  • 31
  • 229
  • 260
  • Suppose the variable `total` have to get a number value, coming from the PHP file. So, it is not updating the value of the variable, it remains zero. Could understand? ;-/ – Gláuber Sampaio Jul 10 '13 at 22:51
  • so long as your php serves valid json structured as you expect it then you pass your callback date.firstDate – Kai Qing Jul 10 '13 at 22:54