33135

Search results in XML put into array with jQuery

Question:

I asked another question earlier and managed to get help with some code that would take an XML file from a YouTube search query. Then, using jQuery, get the information needed from the XML file (the video ID) and put it into a javascript variable.

This worked fine, but I would like (if possible) for our site to have not 1 but 3 of the latest videos from this channel. I was suggested to change the search to get 3 results instead of one, and put the jQuery .find() results into an array.

Problem is I think (I should really say I'm sure) I've done this wrong... Take a look:

<!-- enable jQuery --> <script type="application/javascript" src="jquery.js"> </script> <!-- video loading functions --> <script type="text/javascript"> jQuery(document).ready(function() { jQuery.ajax('https://gdata.youtube.com/feeds/api/videos?author=inthegamesroom&orderby=published&prettyprint=true&start-index=1&max-results=3&v=2',{ dataType:'xml', success: function(data,status, xhr ) { var $data =$(data); var videoTag = new array ($data.find('videoid')); var videoId1 = videoTag[0].text(); var videoId2 = videoTag[1].text(); var videoId3 = videoTag[2].text(); } }); // YouTube Video embed command function embedYT1(id, loaction) { jQuery(location).append("<object width=\"1000\" height=\"563\"><param name=\"movie\" value=\"https://www.youtube.com/v/"+id+"?version=3&amp;hl=en_US\"></param><param name=\"allowFullScreen\" value=\"true\"></param><param name=\"allowscriptaccess\" value=\"always\"></param><embed src=\"https://www.youtube.com/v/"+id+"?version=3&amp;hl=en_US\" type=\"application/x-shockwave-flash\" width=\"1000\" height=\"563\" allowscriptaccess=\"always\" allowfullscreen=\"true\"></embed></object>") } // Call video embed function for 3 vids embedYT(videoId1, '#vid1'); embedYT(videoId2, '#vid2'); embedYT(videoId3, '#vid2'); }); </script>

Can anyone help?

You may also notice I have a embedYT function which is designed to embed the 3 videos. Have I done this right? (I have three id='vid#' in my tags for my table.

Answer1:

Ok, there are some things wrong here. Don't feel bad about it. You are learning and is usual to make mistakes :)

First of all, the vars videoId1, videoId2 and videoId3 are local to the function where the are declared, so they won't be visible when you call embedYT(videoId1) and the later ones.

Second, even if the variables where global (try to not declare global variables in Javascript, really, please) the values you set in the success callback aint visible when you call the embedYT functions. The functions are executed as soon as the page loads, which probably happens before the AJAX callback is executed. To fix this we need to move the embedYT calling to the callback

Third, <a href="http://api.jquery.com/find/" rel="nofollow">$.fn.find()</a> returns a jQuery collection (something similar to an array), so there is no need for puting the result into other array. Also, looking at the response from the <a href="https://gdata.youtube.com/feeds/api/videos?author=inthegamesroom&orderby=published&prettyprint=true&start-index=1&max-results=3&v=2" rel="nofollow">youtube API</a>, the tag you should find is 'yt:videoid', not 'videoid' (its namespaced). <a href="http://www.rfk.id.au/blog/entry/xmlns-selectors-jquery/" rel="nofollow">In this page</a> I've found the correct syntax to do that with jQuery. Let's fix these two things:

var videoTag = $data.find('yt\\:videoid');

With that fixed, we can iterate the collection using <a href="http://api.jquery.com/each/" rel="nofollow">$.fn.each</a> inside the callback and call embedYT for each element, fixing the second problem:

... success: function(data,status, xhr ) { var $data =$(data); var videoTag = $data.find('yt\\:videoid'); videoTag.each(function(i) { embedYT($(this).text(), '#vid' + i); }); } ...

Iterating a collection is more future proof than accessing each element. If you have to change the amount of videos will probably work without changes in the javascript.

So the final code should look like this

<!-- enable jQuery -->] <script type="application/javascript" src="jquery.js"> </script> <!-- video loading functions --> <script type="text/javascript"> jQuery(document).ready(function() { jQuery.ajax('https://gdata.youtube.com/feeds/api/videos?author=inthegamesroom&orderby=published&prettyprint=true&start-index=1&max-results=3&v=2',{ dataType:'xml', success: function(data,status, xhr ) { var $data =$(data); var videoTag = $data.find('yt\\:videoid'); videoTag.each(function(i) { embedYT($(this).text(), '#vid' + i); }); } }); // YouTube Video embed command function embedYT(id, loaction) { jQuery(location).append("<object width=\"1000\" height=\"563\"><param name=\"movie\" value=\"https://www.youtube.com/v/"+id+"?version=3&amp;hl=en_US\"></param><param name=\"allowFullScreen\" value=\"true\"></param><param name=\"allowscriptaccess\" value=\"always\"></param><embed src=\"https://www.youtube.com/v/"+id+"?version=3&amp;hl=en_US\" type=\"application/x-shockwave-flash\" width=\"1000\" height=\"563\" allowscriptaccess=\"always\" allowfullscreen=\"true\"></embed></object>") } }); </script>

Hope it helps

Recommend

  • salesforce sandbox cURL request invalid grant_type
  • Kairosdb error metric[0](name=abcd).tag[xyz].value may not be empty
  • Video's suddenly stopped playing from Youtube API
  • Uncaught TypeError: this.pluginApi.setSrc is not a function
  • Change Playback Quality of YTPlayerView
  • getting error “There was a issue with network [400]” while playing You tube video
  • Sorting Tabulated Data
  • Ios swift - storing uiimage in document directory and path in core data
  • Why won't this override of the Model.save() function in Django work?
  • What is supported by broadcasting in tensorflow? How dimensions matches determined?
  • SerialForms.pas(17): W1010 Method 'Create' hides virtual method of base type 'TCompon
  • youtube video insert “onBehalfOfContentOwner” parameter value
  • GData Youtube : obtaining thumbnails
  • Does Windows Phone 7 have a standard Edit/Add/Delete convention?
  • In explicit LINQ-to-SQL (C#) does order matter?
  • Optional spaces and multiple alternatives in wl-pprint-extras
  • Strings appear exact, but they do not match?
  • Mongoose TypeError: Cannot use 'in' operator to search for '_id' in
  • Reloading table causes flickering
  • FlexJSON Orders Alphabetically by Default
  • Can you build a truly RESTful service that takes many parameters?
  • Sum data table columns using linq
  • Cannot page through all results using nextPageToken on YouTube search API v3
  • Count from each distinct date, fill in missing dates with zero
  • xcode don't localize specific strings
  • presentShareDialogWithParams posts to FB wall, but callback handler results say error
  • Sort List of Strings By Version
  • How to attach a node.js readable stream to a Sendgrid email?
  • swift auto completion not working in Xcode6-Beta
  • Hazelcast - OperationTimeoutException
  • Rearranging Cells in UITableView Bug & Saving Changes
  • RestKit - RKRequestDelegate does not exist
  • Circular dependency while pushing http interceptor
  • Linker errors when using intrinsic function via function pointer
  • Revoking OAuth Access Token Results in 404 Not Found
  • FormattedException instead of throw new Exception(string.Format(…)) in .NET
  • sending mail using smtp is too slow
  • Busy indicator not showing up in wpf window [duplicate]
  • Why is Django giving me: 'first_name' is an invalid keyword argument for this function?
  • How can I use `wmic` in a Windows PE script?