More Javascript Scope Issues

I'm trying to figure out why I can't call a javascript function from a jQuery click function block.
Here's my code:

//GET STATS
		function getStats(vidID){
			var theIDs
				$.ajax({
					url: 'https://www.googleapis.com/youtube/v3/videos?id=' + vidID + '&key={myAPI}&part=snippet,contentDetails,statistics,status', 
					async: false,
					dataType: "json",
					success: function(data) {
					
					theIDs = data.items[0].statistics.viewCount;
					//For Testing - this alert returns the correct value;
                                        alert(theIDs);
					return theIDs;
					}
				});			
		}
		
		//SEARCH - FIND VALUES
		$('#vform1 #vsubmit').click(function(){
			var theVsearch = $("#vSearch").val();
			var whatweneed;
			var re = /^[\w, ]+$/;
			if (re.test(theVsearch)){
				if (theVsearch.indexOf(',') === -1){
					whatweneed = theVsearch;	
				} else {
					whatweneed = theVsearch.replace(",","/");
					whatweneed = $.trim(whatweneed);
				}
				
			} else {
				alert("Please only use letters, numbers and commas.");	
				return false;
			}

			var searchVidResult = "";
			var title;
			var theTitle;
			var description;
			var vidResults;
			var vidID;
			var vidImg;
			var finalID;
			var theStats;
			var t = 0;
					    
			var nUrl = 'https://www.googleapis.com/youtube/v3/search?order=date&q='+whatweneed+'&maxresults=50&type=video&channelId={channelID}&maxResults=50&key={myAPI}&part=snippet';
			copyToClipboard(nUrl);
			$.ajax({
				url: nUrl,
				async: false,
				dataType: "json",
				success: function(data) {

					vidResults = data.items.length;
					finalID = data.items[0].id.videoId;
					theTitle = data.items[0].snippet.title;
					description = data.items[0].snippet.description;
					
					$('#trio_videos').html("");

					for(var i=0;i<vidResults;i++) {

						if (data.items[i].id.kind == "youtube#playlist"){

						} else {
							vidID = data.items[i].id.videoId;
							title = data.items[i].snippet.title;
							vidImg = data.items[i].snippet.thumbnails.high.url;
							t = i + 1;
							
							theStats = getStats(vidID);
                                                        //This alert checks the value of theStats - it's Undefiend.  Is it because it's out of scope?
                                                        alert(theStats);
							
                                                         //THE RESULTS DISPLAYED IN 3 COLUMNS - ADD lastvid CLASS ON EVERY 3rd RESULT
								if (t % 3 == 0) {
									searchVidResult += '<div class="col-md-4 triovid"><a class="btn" value="'+ vidID +'" href="#" ><img src="' + vidImg + '" width=200px height=122px border=0 /></a><p style="text-align:left;"><span class="vidTitle">'+ title +'</span><br/><span class="numViews">' + nStats +' views</span></p></div>';
								}else{
									searchVidResult += '<div class="col-md-4 triovid"><a class="btn" value="'+ vidID +'" href="#"><img src="' + vidImg + '" width=200px height=122px border=0 /></a><p style="text-align:left;"><span class="vidTitle">'+ title +'</span><br/><span class="numViews">' + nStats +' views</span></p></div>';
								}
						}
					}

					$("#trio_videos").append(searchVidResult);
					if (t>0){
						
						//vidID = response.feed.entry[0].id.$t.split(':');
						//finalID = vidID[3];
						$('#main_video').html('<iframe width="636" height="358" src="//www.youtube.com/embed/'+finalID+'?list={myListID}&wmode=transparent" frameborder="0" allowfullscreen wmode="Opaque"></iframe>');
						$("#vSearch").val("");
						$('#vidDescription').html('<h2 style="font-family:arial; font-size:15px; color:#bc8e30;">' + theTitle + '</h2><p style="font-family:verdana; font-size:12px;">'+ description + '</p>');
						
					}

				}
			});
			return false;
		});

Open in new window


Line #72 calls the GetStats function.  I put in a couple of alerts to check for values.  GetStats generates the correct value - it is called, but it returns "undefined".  I'm not sure why...

Any ideas?  Thanks for the help!!!
LVL 1
slightlyoffAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Rainer JeschorCommented:
Hi,
not 100% sure but what happens if you move the return from inside your ajax.success function to the outside function?

//GET STATS
function getStats(vidID){
	var theIDs = null;
	$.ajax({
		url: 'https://www.googleapis.com/youtube/v3/videos?id=' + vidID + '&key={myAPI}&part=snippet,contentDetails,statistics,status', 
		async: false,
		dataType: "json",
		success: function(data) {
			theIDs = data.items[0].statistics.viewCount;
			//For Testing - this alert returns the correct value;
			alert(theIDs);
		}
	});			
	return theIDs;
}

Open in new window

HTH
Rainer
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
slightlyoffAuthor Commented:
Rainer - You rock!

That was it :)  Thanks!
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
JavaScript

From novice to tech pro — start learning today.