-1

I would like to get the current time in Javascript/ Jquery.

I could just use Math.floor($.now() / 1000) but that will return the time from the browser which could be accurate but possibly in the wrong timezone. I have setup the file time.php on my server which when visited returns the current unix timestamp for the correct timezone. Now all I need to do is get this into Javascript. I thought about using a jquery function like this:

    function time(){
        $.ajax({url: "time.php", success: function(result){
            return(result);
        }});
    }
    alert(time());

but that doesn't seem to work as the function comes back as undefined. Is there a solution to this that enables me to call alert(time());?

JBithell
  • 627
  • 2
  • 11
  • 27

2 Answers2

4

This is an a-synchronous call: $.ajax({url: "time.php", success: function(result){

This means the alert gets called way before your return actually returns your data. Consequentially, there's no return value when the alert was run, explaining the 'undefined'.

Rather than explaining it in detail, I'd recommend you to read the top answer on this post, it does an excellent job explaining the problem you're having, probably better than I could muster.

Community
  • 1
  • 1
Tom
  • 332
  • 2
  • 13
  • Thanks for your answer. I understand it is a-synchronous but is there a solution? – JBithell May 04 '15 at 13:55
  • 1
    See the link I edited in, there's a great explanation and possible solutions to your problem there. Just don't make the call synchronous because that locks up the browser.. Not something you'd want. – Tom May 04 '15 at 13:58
  • Replace `return(result);` with the code you want to run, in this case `alert(result);`. – Siguza May 04 '15 at 13:59
4

AJAX calls are asynchronous by nature. You need to place your logic inside the callbacks. There are many ways to handle it.

Placing logic inside success callback

function time(){
    $.ajax({url: "time.php", success: function(result){
        // Place your business logic here
    }});
}
time();

Passing callback

function time(callback){
    $.ajax({url: "time.php", success: function(result){
        callback(result);
    }});
}
time(function (result) {
    // Place your business logic here
});

You can even optimize this by

function time(successCB){
    $.ajax({url: "time.php", success: successCB});
}
time(function (result) {
    // Place your business logic here
});

Use Promises

Promises are experimental technology and is part of ES6.

function time(){
    var promise = new Promise(function (resolve, reject) {
        $.ajax({url: "time.php", success: function(result){
            resolve(result);
        }});
    });

    return promise;
}

time().then(function (result) {
    // Place your business logic here
});
Vigneswaran Marimuthu
  • 2,452
  • 13
  • 16