JavaScript function for searching YouTube videos

While browsing on stackoverflow, I came across the following code snippet:

$(document).ready(function () {
$("#show").click(function () {
    getYoutube($("#Search").val());
});

});

function getYoutube(title) {
$.ajax({
    type: "GET",
    url: yt_url = 'http://gdata.youtube.com/feeds/api/videos?q=' + title + '&format=5&max-results=1&v=2&alt=jsonc',
    dataType: "jsonp",
    success: function (response) {
        if (response.data.items) {
            $.each(response.data.items, function (i, data) {
                var video_id = data.id;
                var video_title = data.title;
                var video_viewCount = data.viewCount;
                $("#result").html(video_id);
            });
        } else {
            $("#result").html('false');
        }
    }
});

}

Is there a way to modify the code so that only the function remains? I would like to be able to use it like this: getYoutube(my_keywords);

Additionally, how can I store the output of the function in a variable? Something like: var_name = getYoutube(my_keywords); Would that work?

Thanks! ;)

Answer №1

Absolutely, you have the option to utilize it without the need for $(document).ready. However, please note that this function does not yield any output.

If you want to "return" a value from an Ajax call:

$.ajax({
    ...
    success: function(dataFromServer) {
        processServerResponse(dataFromServer);
    }
});

function processServerResponse(someString) {
    alert(someString);
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Data is not appearing when using Node.js with mongoose and the populate() method

I am facing an issue while trying to display data from a database. Even though I have integrated 3 different schemas into one, the combined data is not being displayed as expected. I have attached all three schemas for reference. While async-await along w ...

Naming axes in Chart.js is a simple process that can easily be implemented

Greetings to all, I'm currently working on creating bar charts using chartjs...everything is going smoothly except for one thing - I am struggling to find a clean way to name my axes without resorting to CSS tricks like absolute positioning. Take a ...

Serving pages with Node JS and loading .js files on the client side

Here is a simple JS file that will be familiar to those who have worked with Socket.IO in NodeJS and Express: var express = require('express'), app = express(), server = require('http').createServer(app), io = require(&apos ...

I am curious if there exists a VSCode plugin or IDE that has the ability to show the dependencies of TypeScript functions or provide a visual representation

Are there any VSCode plugins or IDEs available that can display the dependency of TypeScript functions or show a call stack view? I am looking for a way to visualize the call stack view of TypeScript functions. Is there a tool that can help with this? Fo ...

Guide to using a Selector in a mixin in VUE

I'm attempting to create a Mixin that will help me calculate the offsetWidth of an element. Here is my Mixin: export const boxWidth = (selector) => ({ mounted() { selector.addEventListener( 'resize', this.setBoxWidth ); ...

Generate an array using the properties of an object

Seeking a more efficient way to configure settings for an app using objects? Consider starting with the following object: var obj = { property_one: 3; property_two: 2; property_three: 1; } And transforming it into the desired array format: v ...

Leveraging the Power of Ajax Button for Django Model Filtering

My goal is to create buttons on my website that, once clicked, trigger a specific filter on my database of models. Specifically, I am trying to sort the "Clothes_Item" model and apply various filters. To start off, I want to keep it simple and create a but ...

Error occurred during validation in Postman despite providing input in fields

I encountered an issue while creating a RESTful API. Initially, everything was working fine using Postman and MongoDB to make requests. However, after adding a router, only Delete and Get requests are functioning correctly, while Update and create requests ...

Jquery's intermittent firing of .ajax within if statement

So, I've inherited a rather messy codebase that I need to modernize. The task involves upgrading from an old version of prototype to the latest jQuery 3.2.1 within a dated website built on php and smarty templates (not exactly my favorite). When a lo ...

Encountering an error with NextJs & Strapi when utilizing the getStaticPaths functionality

Currently, my project involves using Strapi to develop a custom API and NextJs for the frontend. I am experimenting with utilizing getStaticPaths to generate pages based on different categories. In Strapi, I have set up a collection for categories that is ...

What is the best way to upload a JSON file onto a local server?

After struggling for the past two hours trying to solve a problem I encountered, I've come to realize that accessing a local JSON file named data.json from my project directory is not possible due to cross-origin requests limitations. In order to acce ...

Optimal Strategy: Utilizing Spring Boot for Backend Development and jQuery for Frontend Interface

I am currently tackling a project that involves a Spring Boot 2 Backend and a jQuery Frontend. The frontend communicates with the backend by sending Ajax requests to Spring REST controllers in order to interact with database entities. One of the challenge ...

Issues with applying styles to custom components in styled-components

I attempted to customize the inner elements of react-id-swiper using the code below: import Swiper from 'react-id-swiper'; import styled from 'styled-components'; const MySwiper = ({ className, children }) => ( <Swip ...

"Return to previous page" feature

I am having difficulty figuring out how to implement the "go back" function for the page. For instance, I have pages A, B, C, and D. The possible switching between pages is as follows: A -> (B <-> C) -> A or D -> (B <-> C) -> D (w ...

What is the process for resizing a texture render target following a window resize event?

My intention was to improve the texture quality, but instead of achieving my goal, I encountered an issue where the same texture is being stretched over a larger area, resulting in unwanted staircase artifacts. I tried updating various elements like camera ...

Working with Angular to Retrieve a File Using Ajax

My dilemma revolves around a service that is capable of generating a CSV file and sending it back to the page through an http/ajax get request. The desired user interaction involves clicking a button, triggering the service call, and initiating the downloa ...

Is it possible to selectively mock certain components of an external module using jest?

I am totally new to using Jest, especially in regards to unit tests, and I am struggling to write a test for a specific scenario. I know that you can mock an external module like this.. jest.mock('@organisation/library', () => ({ Database: j ...

The unresponsive sticky navigation bar on a Joomla website is causing issues

I recently launched a new website that can be found here. The site includes the following JavaScript code: $(document).ready(function(){ $(window).bind('scroll', function() { var navHeight = $( window ).height() - 70; ...

Catching the Selenium NoSuchElementError in JavaScript is impossible

Update: It's puzzling why this was marked as answered since the linked questions don't address the issue at hand and do not involve Javascript. My objective is to detect this error, rather than prevent it, given that methods like invisibilityOfEl ...

Steps for iterating over the "users" list and retrieving the contents of each "name" element

I'm attempting to iterate over the "users" array and retrieve the value of each "name". Although the loop seems to be functioning correctly, the value of "name" is returning as "undefined" four times. JavaScript: for(var i = 0; i < customer.users ...