Passing variable out of completefunc

Jun 19, 2012 at 4:40 PM

I'm trying to write a function that returns a user's ID given their username. I've got SPServices performing the AJAX call just fine and know I'm getting a correct result. However, I can't seem to get it to pass me the value of the user's ID out of the completefunc. Here's what I've got:

function getUserID(username) {
	var result = "";
   		operation: "GetUserInfo",
   		userLoginName: username,
   		completefunc: function(xData, Status){
			result = $(xData.responseXML).find("User:first").attr("ID");
	return result;

Using the console, I've confirmed that result gets set to the ID within the function, but then gets reset to "" once the out of the function. I'm guessing there's something I don't know about the scope of variables or something - can anyone lend a hand? Thanks!

Jun 19, 2012 at 4:50 PM
Add 'async: false' to your SPServices call options. The way you currently have it coded, your SPServices call is async, which means your getUserID() function exits (with "") prior to the SPServices call completing.

FYI: if just trying to get the "currently logged in user" ID, then it is already available under a global variable called window._spUserId

Paul T

Jun 19, 2012 at 4:57 PM

Thanks! That did the trick. Thanks also for the note about the ID - I can't use that in this case because I'm potentially looking up users besides the current one, but that's really helpful to know!