twkl twkl - 3 months ago 11
Javascript Question

Javascript functions returns undefined

Ok,I've been trying to get this to work for the past two days and I cannot figure out what I am doing wrong. I have a function called "ping" that makes a calculation, and I have a callback function to retrieve the calculated value, but all I keep getting is undefined!

var test;

var p = ping('apple.com', function (num) {
test = num;
console.log(test); //this works, the value is displayed in the console.
});

console.log("p: " +p); //says undefined
console.log("test: " +test); //says undefined


Can someone tell me what I am doing wrong? Thanks!

Edit:
Here is the ping function:

function ping(host, pong) {

var started = new Date().getTime();

var http = new XMLHttpRequest();

http.open("GET", "http://" + host, /*async*/true);
http.onreadystatechange = function() {
if (http.readyState == 4) {
var ended = new Date().getTime();

var milliseconds = ended - started;

if (pong != null) {
pong(milliseconds);
//console.log(milliseconds);
return milliseconds;
}
}
};
try {
http.send(null);
} catch(exception) {
// this is expected
}

}

Answer

You could use synchronous AJAX.

function ping(host,pong){
    var http = new XMLHttpRequest();

    http.open("GET", "http://" + host, /*not async*/false);
    http.send(null);

    if(pong)pong(http.responseText);
    return http.responseText;
};

Otherwise you will not be able to return the http.responseText.

However, this technique is not really best practice because it causes all other Javascript on the page to stall until the request has completed. If the server takes a long time to answer, then your page will be not responding. Extremely annoying to users.

Note that you would have an error trying to do AJAX to another domain as you have shown in the code in your question.