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?
 
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
 
slightlyoffAuthor Commented:
Rainer - You rock!

That was it :)  Thanks!
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.