Skip to content

Instantly share code, notes, and snippets.

@housker
Created March 15, 2018 21:19
Show Gist options
  • Save housker/2955d4c0190bcd04f381304ef61c5a5e to your computer and use it in GitHub Desktop.
Save housker/2955d4c0190bcd04f381304ef61c5a5e to your computer and use it in GitHub Desktop.
//fetch API
var searchYouTube = function(options, callback) {
var url = 'https://www.googleapis.com/youtube/v3/search';
var params = `?part=snippet&maxResults=${options.max}&q=${options.query}&type=video&videoEmbeddable=true&key=${options.key}`;
fetch(url + params)
.then(resp => resp.json())
.then(jsonResp => callback(jsonResp.items))
.catch(err => console.log('GET failed', err));
};
//jQuery
// var searchYouTube = function(options, callback) {
// $.get('https://www.googleapis.com/youtube/v3/search', {
// part: 'snippet',
// key: options.key,
// q: options.query,
// maxResults: options.max,
// type: 'video',
// videoEmbeddable: 'true'
// })
// .done(data => callback(data.items))
// .fail(err => console.log('Request Failed', err));
// };
//jQuery (again)
// var searchYouTube = function(options, callback) {
// $.ajax({
// type: 'GET',
// url: 'https://www.googleapis.com/youtube/v3/search',
// contentType: 'application/json',
// data: {
// part: 'snippet',
// key: options.key,
// q: options.query,
// maxResults: options.max,
// type: 'video',
// videoEmbeddable: 'true'
// },
// success: function(resp) {
// callback(resp.items)
// },
// error: function(err) {
// console.log(err);
// }
// })
// };
// XMLHTTPRequest
// var searchYouTube = function(options, callback) {
// var url = 'https://www.googleapis.com/youtube/v3/search';
// var params = `?part=snippet&maxResults=${options.max}&q=${options.query}&type=video&videoEmbeddable=true&key=${options.key}`;
// var xhr = new XMLHttpRequest();
// xhr.responseType = 'json';
// // xhr.onreadystatechange = function() {
// // if (xhr.readyState === XMLHttpRequest.DONE) {
// // callback(xhr.response.items)
// // }
// // }
// xhr.onload = function() {
// if (xhr.status >= 200 && xhr.status < 400) {
// callback(xhr.response.items)
// } else {
// console.log('We reached our target server, but it returned an error')
// }
// };
// xhr.open('GET', url + params, true);
// xhr.onerror = function() {
// console.log('Connection error')
// }
// xhr.send();
// };
window.searchYouTube = searchYouTube;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment