locked
Returned Value in Function showing undefined - REST, SharePoint javascript RRS feed

  • Question

  • i'm trying to get the picture details from his user profile in the pictureRetrieve function. when i check the console the PictureDetails value exists for each item . But what i'm trying to achieve is to return the value to the completedetails function.

    But the line that calls the pictureRetrieve function runs i get undefined as a result. Not sure if this is a scope problem or return keywords run differently in json.

    any help would be much appreciated

    function CompleteDetails() { var requestUri = _spPageContextInfo.webAbsoluteUrl + "/_api/Web/Lists/getByTitle('OrganisationalChart')/items?$select=Id,user/Title,user/Id,user/Name,Boss/Id,Boss/Title,PictureUrl,Designation&$expand=user,Boss"; $.ajax({ url: requestUri, type: "GET", async:false, headers: { "ACCEPT": "application/json;odata=verbose" }, success: function (data) { var dataResults = data.d.results; console.log(dataResults); for (var i = 0; i < dataResults.length; i++) { var userDetails = dataResults[i]['user'].Name.split('|')[1]; var employeeId = dataResults[i]['user'].Id.toString(); var employeeName = dataResults[i]['user'].Title var Designation = dataResults[i].Designation != null ? dataResults[i].Designation : ''; var reportingManager = dataResults[i]['Boss']['Id'] != null ? dataResults[i]['Boss']['Id'] : ''; reportingManager = reportingManager.toString(); //Get the user profile picture for each user userPicture = pictureRetrieve(userDetails); } }, failure: function (r) { alert(r.d); }, error: function (r) { alert(r.d); } }); } var pictureRetrieve = function GetPictureUrl(user) { var requestUri = _spPageContextInfo.webAbsoluteUrl + "/_api/SP.UserProfiles.PeopleManager/GetPropertiesFor(accountName=@v)?@v='"+user+"'"; $.ajax({ url: requestUri, type: "GET", async:false, headers: { "ACCEPT": "application/json;odata=verbose" }, success: function (data) { var DataRes = data.d.PictureUrl; var PictureDetails = data.d.PictureUrl != null ? data.d.PictureUrl : 'nouserimageurl'; console.log(PictureDetails);

    return PictureDetails;

    }, failure: function (r) { alert(r.d); }, error: function (r) { alert(r.d); } }); }




    • Edited by dongotti Friday, January 13, 2017 10:55 AM
    Friday, January 13, 2017 10:53 AM

Answers

  • My bad, yes you are right.

    I had a similar issue and the way i went about solving it was to use the Promise and Deferred concept in jQuery. Please refer to the below code and see if this helps.

    	function getSubcontractors(currentSiteName, role) {
            var restURL = projectSiteURL + "/_api/web/sitegroups/getbyname('" + currentSiteName + "_Subcontractors')/Users";
            $.ajax({
                url: restURL,
                method: "GET",
                dataType: "json",
                async: true,
                headers: { "Accept": "application/json; odata=verbose" },
                success: function (data) {
    				$.when(getUserProfilePropertiesForSubContractors(data,role)).done(function(){
    					intializeDataTable();
    				});
                },
                error: function (data) {
                    alert('err');
                }
            });
        }
    
    	function getUserProfilePropertiesForSubContractors(data,role) {
    		var def = $.Deferred(),
    			requests = [];
    		var items = data.d.results;
    
    		for (var i = 0; i < items.length; i++)  {
    			 var userLoginName = items[i].LoginName.split('|')[1];
                if(userLoginName != null && userLoginName.indexOf('\'') == '-1'){          	
    					restURL = projectSiteURL + "/_api/SP.UserProfiles.PeopleManager/GetPropertiesFor(accountName=@v)?@v=%27" + userLoginName + "%27";
    					
    					requests.push($.ajax({
    						url: restURL,
    						method: "GET",
    						async: true,
    						headers: { "Accept": "application/json; odata=verbose" }}).done(function(data,role){
    						populateContactCard(data);
    					})); 			           		           					
                }			
    		}
    
    		$.when.apply($, requests).then(function() { def.resolve(); });
    
    		return def.promise();
    	}

     
    • Marked as answer by dongotti Tuesday, January 17, 2017 4:23 PM
    Friday, January 13, 2017 3:44 PM
  • Hi,

    The following code for your reference:

    <script src="//code.jquery.com/jquery-3.1.0.min.js" type="text/javascript"></script>
    <script type="text/javascript">
    $(function () {
    	CompleteDetails();
    });
    
    function CompleteDetails(){    
    	var requestUri = _spPageContextInfo.webAbsoluteUrl + "/_api/Web/Lists/getByTitle('OrganisationalChart')/items?$select=Id,user/Title,user/Id,user/Name&$expand=user";
    	$.ajax({
    		url: requestUri,
    		method: "GET",		
    		headers: { "Accept": "application/json; odata=verbose" },
    		success: function (data) {
    			var dataResults = data.d.results;			
    			for (var i = 0; i < dataResults.length; i++) {
    				if(dataResults[i].user!=null){
    					var userDetails = dataResults[i].user.Name.split('|')[1];
    					//Get the user profile picture for each user
    					console.log(userDetails);
    					var userPicture = GetUserPictureUrl(userDetails);					
    				}				
    			}
    		},
    		error: function(data){
    		}
    	});
    }
    function GetUserPictureUrl(user){
    	var userPicture="";
    	var requestUri = _spPageContextInfo.webAbsoluteUrl + "/_api/SP.UserProfiles.PeopleManager/GetPropertiesFor(accountName=@v)?@v='"+user+"'";
    	$.ajax({
    		url: requestUri,
    		method: "GET",
    		async: false,
    		headers: { "Accept": "application/json; odata=verbose" },
    		success: function (data) {
    			var PictureDetails = data.d.PictureUrl != null ? data.d.PictureUrl : 'nouserimageurl';
    			console.log(PictureDetails);
    			userPicture=PictureDetails;
    		},
    		error: function (data) {
    		}
    	});
    	return userPicture;
    }
    </script>

    Best Regards,

    Dennis


    Please remember to mark the replies as answers if they help.
    If you have feedback for TechNet Subscriber Support, contact tnmff@microsoft.com

    • Marked as answer by dongotti Tuesday, January 17, 2017 4:23 PM
    Tuesday, January 17, 2017 2:35 AM

All replies

  • Hi, 

    Can you please try the below in your success method of GetPictureUrl function.

    var PictureDetails;
    
    var properties = data.d.UserProfileProperties.results;
    for (var i = 0; i < properties.length; i++) {
        var property = properties[i];
    	if (property.Key == "PictureUrl") {
    		PictureDetails = property.Value;
    	}                
    }
    
    return PictureDetails;

    Please remember to mark the replies as answers if they help.


    Friday, January 13, 2017 2:18 PM
  • Thanks Giridharan.  i can get the url value without the need iterate the data object returned by the Ajax call. By simply going data.d.PictureUrl give me the value. But i would like this value to be availble for use by the CompleteDetails function.

    The problem is which i guess is because of the asynchronous nature of Ajax. Picture url is returning undefined because it is called before it has been assigned a value. i'm yet to get around the order in which ajax runs its lines of code.

    i'm struggling with how to get around it. Someone suggested the use of callbacks, but i'm not sure how i can apply that in my case.

    Friday, January 13, 2017 3:23 PM
  • My bad, yes you are right.

    I had a similar issue and the way i went about solving it was to use the Promise and Deferred concept in jQuery. Please refer to the below code and see if this helps.

    	function getSubcontractors(currentSiteName, role) {
            var restURL = projectSiteURL + "/_api/web/sitegroups/getbyname('" + currentSiteName + "_Subcontractors')/Users";
            $.ajax({
                url: restURL,
                method: "GET",
                dataType: "json",
                async: true,
                headers: { "Accept": "application/json; odata=verbose" },
                success: function (data) {
    				$.when(getUserProfilePropertiesForSubContractors(data,role)).done(function(){
    					intializeDataTable();
    				});
                },
                error: function (data) {
                    alert('err');
                }
            });
        }
    
    	function getUserProfilePropertiesForSubContractors(data,role) {
    		var def = $.Deferred(),
    			requests = [];
    		var items = data.d.results;
    
    		for (var i = 0; i < items.length; i++)  {
    			 var userLoginName = items[i].LoginName.split('|')[1];
                if(userLoginName != null && userLoginName.indexOf('\'') == '-1'){          	
    					restURL = projectSiteURL + "/_api/SP.UserProfiles.PeopleManager/GetPropertiesFor(accountName=@v)?@v=%27" + userLoginName + "%27";
    					
    					requests.push($.ajax({
    						url: restURL,
    						method: "GET",
    						async: true,
    						headers: { "Accept": "application/json; odata=verbose" }}).done(function(data,role){
    						populateContactCard(data);
    					})); 			           		           					
                }			
    		}
    
    		$.when.apply($, requests).then(function() { def.resolve(); });
    
    		return def.promise();
    	}

     
    • Marked as answer by dongotti Tuesday, January 17, 2017 4:23 PM
    Friday, January 13, 2017 3:44 PM
  • Hi,

    The following code for your reference:

    <script src="//code.jquery.com/jquery-3.1.0.min.js" type="text/javascript"></script>
    <script type="text/javascript">
    $(function () {
    	CompleteDetails();
    });
    
    function CompleteDetails(){    
    	var requestUri = _spPageContextInfo.webAbsoluteUrl + "/_api/Web/Lists/getByTitle('OrganisationalChart')/items?$select=Id,user/Title,user/Id,user/Name&$expand=user";
    	$.ajax({
    		url: requestUri,
    		method: "GET",		
    		headers: { "Accept": "application/json; odata=verbose" },
    		success: function (data) {
    			var dataResults = data.d.results;			
    			for (var i = 0; i < dataResults.length; i++) {
    				if(dataResults[i].user!=null){
    					var userDetails = dataResults[i].user.Name.split('|')[1];
    					//Get the user profile picture for each user
    					console.log(userDetails);
    					var userPicture = GetUserPictureUrl(userDetails);					
    				}				
    			}
    		},
    		error: function(data){
    		}
    	});
    }
    function GetUserPictureUrl(user){
    	var userPicture="";
    	var requestUri = _spPageContextInfo.webAbsoluteUrl + "/_api/SP.UserProfiles.PeopleManager/GetPropertiesFor(accountName=@v)?@v='"+user+"'";
    	$.ajax({
    		url: requestUri,
    		method: "GET",
    		async: false,
    		headers: { "Accept": "application/json; odata=verbose" },
    		success: function (data) {
    			var PictureDetails = data.d.PictureUrl != null ? data.d.PictureUrl : 'nouserimageurl';
    			console.log(PictureDetails);
    			userPicture=PictureDetails;
    		},
    		error: function (data) {
    		}
    	});
    	return userPicture;
    }
    </script>

    Best Regards,

    Dennis


    Please remember to mark the replies as answers if they help.
    If you have feedback for TechNet Subscriber Support, contact tnmff@microsoft.com

    • Marked as answer by dongotti Tuesday, January 17, 2017 4:23 PM
    Tuesday, January 17, 2017 2:35 AM
  • userPicture = pictureRetrieve(userDetails);  

    Thanks Dennis,Giridharan Both approaches worked but I'm intrested to know how you forced  Ajax to get pictures first before using it or what was the thinking behind it, just to help my learning. In the original code I was getting an undefined, in my original code in the part above. But yours seems to work well

    What did I do wrong??
    Tuesday, January 17, 2017 4:28 PM