-1

I am currently doing some tests using the following code:

function updateCurrentTime() {
    var HeaderDate;

    $.ajax('/', {
        url: "http://www.google.com",
        type: 'HEAD',
        success: function(r,status,xhr) {
            HeaderDate = xhr.getResponseHeader('Date');
        }
    });
    var curTime = new Date(HeaderDate);
}

Unfortunately at the following line:

var curTime = new Date(HeaderDate);

I am not able to retrieve the variable content of the HeaderDate in the AJAX code.

The goal is to get time from a different location than the local computer running the script.

I even tried using global variables without any success.

Can you help me out please?

Thanks a lot for your time and help.

Matt Burland
  • 44,552
  • 18
  • 99
  • 171
Dyr Fenrir
  • 129
  • 2
  • 15

1 Answers1

0

It is because curtime is set BEFORE the ajax returns.

Something like the following would be better, but the takeaway here is that you need to have your application updating when the ajax returns, so within the success callback.

function updateCurrentTime() {
    var HeaderDate, curTime;
    function setCurrentTime(time){ curTime = new Date(time);}

    $.ajax('/', {
        url: "http://www.google.com",
        type: 'HEAD',
        success: function(r,status,xhr) {
            setCurrentTime(xhr.getResponseHeader('Date'));
        }
    });

}
Mild Fuzz
  • 29,463
  • 31
  • 100
  • 148