twkl twkl - 6 months ago 31
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('', 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!

Here is the ping function:

function ping(host, pong) {

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

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

var milliseconds = ended - started;

if (pong != null) {
return milliseconds;
try {
} catch(exception) {
// this is expected



You could use synchronous AJAX.

function ping(host,pong){
    var http = new XMLHttpRequest();"GET", "http://" + host, /*not async*/false);

    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.