0

I have this script:

function getUsername() {
    $.ajax("http://one2xs.com/index.php", {
        success: function(a) {
            console.log($(a).find("#left").html().match(/Je bent ingelogd als ([ ^A-z0-9]*)/)[1]);
            return $(a).find("#left").html().match(/Je bent ingelogd als ([ ^A-z0-9]*)/)[1];
        }
    }); 
}

alert(getUsername());

In the console log it says my username: console log

But the alert is 'undefined', I dont know why. I have already doing some debugging but its will not work. Does somebody know why my username works in the console log but not in the alert?

Thanks.

2 Answers2

1

Since it is an ajax call, it is async. So your alert is running before the call returns from the server.

Put the alert in the success function and it will work.

Jason
  • 1,879
  • 16
  • 19
0

You need to wait for the 'success' of the $.ajax call. So do something like this:

var username
function getUsernameFromServer() {
    $.ajax("http://one2xs.com/index.php", {
        success: function(a) {
            username = $(a).find("#left").html().match(/Je bent ingelogd als ([ ^A-z0-9]*)/)[1];
            console.log("got username: " + username)
        }
    }); 
}
getUsernameFromServer()

function getUsername()
  if ( username != null ) {
       return username
  } else {
       //de give it a second then try again
       setInterval(function(){
            getUsername()
       },1000);
  }
}

That is not exact, but gives you the main concept. var username is the most important part.

digitalextremist
  • 5,952
  • 3
  • 43
  • 62