I am working on a project that involves integrating the Youtube API. The goal is to allow users to search for videos and display search results as they type. However, I only have experience with Python and Django, so I followed a tutorial to add AJAX functionality using JavaScript. Despite following the tutorial closely, my implementation is not functioning correctly.
The AJAX JavaScript code in question looks like this:
<!-- javascript for ajax-->
<script>
var delayTimer;
$("#div_id_search_form").keyup(function() {
clearTimeout(delayTimer);
$('#search_results').text('Loading...');
delayTimer = setTimeout(function() {
var text = $("#div_id_search_form").val();
$.ajax({
url: '/video/search',
data: {
'search_term': text
},
dataType: 'json',
success: function(data) {
var results = '';
$('#search_results').text('');
data['items'].forEach(function(video){
results += video['snippet']['title']
});
$('#search_results').append(results);
}
});
}, 1000);
});
</script>
In addition, here is the relevant portion of my views.py file which utilizes the YouTube API:
def video_search(request):
search_form = SearchForm(request.GET)
if search_form.is_valid():
encoded_search_term = urllib.parse.quote(search_form.cleaned_data['search_term'])
response = requests.get(f'https://youtube.googleapis.com/youtube/v3/search?part=snippet&maxResults=6&q={ encoded_search_term }&key={ YOUTUBE_API_KEY }')
return JsonResponse(response.json())
return JsonResponse({'error': 'Not able to validate form'})
At present, the objective is to show 'Loading...' while the user types, and upon pausing for one second, display six video titles related to the search term. It seems that there might be an issue with the JavaScript portion.
Although the 'Loading...' message appears successfully, no results are displayed once the user stops typing.
The error shown in the console is as follows:
Uncaught TypeError: Cannot read properties of undefined (reading 'forEach')
at Object.success (addvideo:75)
at c (jquery.min.js:2)
at Object.fireWith [as resolveWith] (jquery.min.js:2)
at l (jquery.min.js:2)
at XMLHttpRequest.<anonymous> (jquery.min.js:2)
Given my limited knowledge of JavaScript, any specific guidance would be greatly appreciated. This is a Django project where JavaScript expertise is required solely for this segment.
Please let me know if further details are necessary.
Thank you in advance!
Below is a snippet from the JSON response received from the YouTube Search API:
{
"kind": "youtube#searchListResponse",
"etag": "eZ_XegkOrAIwxYDVnpYZmKbrfbE",
"nextPageToken": "CAYQAA",
"regionCode": "CA",
[...]
}