Javascript Variable issues

I'm having issues filling a variable.
I'm using YouTube's API to create a playlist on my website.

I have a list of video codes and I want to loop through and get the video names (eventually more than that), and display them on a page.

For some reason, the videoDesc variable clears out after the for-loop finishes.  I'm not getting any errors (at least not in FireFox's error consol), and if I put an alert inside the for-loop, it displays the information.  Can you tell what I'm doing wrong?
 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js" ></script>
<script language="javascript">
	var videoDesc = "Desc: ";
	var myVids=['o322TIvmqtc','pnjTPSQXvtQ','gcMPhuhqVO4'];
	var numVids = myVids.length;
	for (i=0;i<numVids;i++){
		
		$.getJSON('http://gdata.youtube.com/feeds/api/videos/'+myVids[i]+'?v=2&alt=jsonc',function(data,status,xhr){
		
		videoDesc += data.data.title + '<br/>';
		
		});
	}
	alert(videoDesc);   //shows up blank
	$('#result').text(videoDesc); //Does nothing...
	
	
</script>

Open in new window


Thank you for your help!!!

Steve
LVL 1
slightlyoffAsked:
Who is Participating?
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.

Big MontySenior Web Developer / CEO of ExchangeTree.org Commented:
the code looks alright syntactically, the first thing I would do is make sure you have the right URL and parameters set. take the url you have any plug it directly into the browser and see if you get a response.

also, should

data.data.title

be data.title

?
0
slightlyoffAuthor Commented:
Thanks for the quick reply!

The youtube.com address is correct, I can put alerts inside the loop and display the titles of the videos.  also, data.data.title is correct.

I think this is a scope issue, but I can't figure out why.
I set the variable videoDesc = "Desc: "; and the alert after the for-loop displays: "Desc:" even though it was changed in the loop.

For the purposes of testing, I just changed the variable in the loop to:  
videoDesc = "Blue", but it still didn't change the result after the loop completed.

Thanks again for your help!

Steve
0
Big MontySenior Web Developer / CEO of ExchangeTree.org Commented:
it seems like then there is something wrong here, as its not firing:

$.getJSON('http://gdata.youtube.com/feeds/api/videos/'+myVids[i]+'?v=2&alt=jsonc',function(data,status,xhr){
		
		videoDesc += data.data.title + '<br/>';
		
		});

Open in new window

if you put the alert statement in there, does it fire?
0
Determine the Perfect Price for Your IT Services

Do you wonder if your IT business is truly profitable or if you should raise your prices? Learn how to calculate your overhead burden with our free interactive tool and use it to determine the right price for your IT services. Download your free eBook now!

slightlyoffAuthor Commented:
If I put in an alert there, it works as expected... but once the loop is done, videoDesc does not change (outside the loop).
0
Julian HansenCommented:
Yes it will because your problem is that the $.getJSON is running asynchronously.

So what is happening is that the loop is running through all three calls before the first one has finished.
So the Desc is being updated but you are outputting it before the getJSON calls are finished.
0
Julian HansenCommented:
Here is some code that should work using $.ajax and async: false
<!doctype html>
<html>
<head>
<title>Test</title>
<script src="https://code.jquery.com/jquery.js"></script>
<script language="javascript">
$(function() {
    var videoDesc = "Desc: ";
    var myVids=['o322TIvmqtc','pnjTPSQXvtQ','gcMPhuhqVO4'];
    var numVids = myVids.length;
    for (i=0;i<numVids;i++){
        $.ajax({
            url: 'http://gdata.youtube.com/feeds/api/videos/'+myVids[i] + '?v=2&alt=jsonc',
            dataType: 'JSON',
            async: false,
            type: 'GET',
            success: function(data) {
                videoDesc += data.data.title + '<br/>';
            }
        });
    }
    $('#result').html('videoDesc' + videoDesc);
});
</script>
</head>
<body>
<div id="result"></div>
</body>
</html>

Open in new window

0
Julian HansenCommented:
Also your code was running out side of a document ready block
$(function() {
});

Open in new window

So when it came time to update your result block the document was not ready so the Jquery call failed.
0
Julian HansenCommented:
Alternative using the data option for the v=2 and alt=jsonc params
<!doctype html>
<html>
<head>
<title>Test</title>
<script src="https://code.jquery.com/jquery.js"></script>
<script language="javascript">
$(function() {
    var videoDesc = "Desc: ";
    var myVids=['o322TIvmqtc','pnjTPSQXvtQ','gcMPhuhqVO4'];
    var numVids = myVids.length;
    for (i=0;i<numVids;i++){
        $.ajax({
            url: 'http://gdata.youtube.com/feeds/api/videos/'+myVids[i],
            dataType: 'JSON',
            async: false,
            type: 'GET',
            data: {v:2, alt: 'jsonc'},
            success: function(data) {
                videoDesc += data.data.title + '<br/>';
            }
        });
    }
    $('#result').html(videoDesc);
});
</script>
</head>
<body>
<div id="result"></div>
</body>
</html>

Open in new window

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:
Thank you!  That makes a ton of sense.  I appreciate your help.
0
Julian HansenCommented:
You are welcome - thanks for the points.
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.