Uncaught TypeError: Cannot read properties of undefined (reading 'forEach')

Viewed 6765

I want to use Youtube API on my project where user can search for videos and it displays search results as the user is typing. I am only familiar with python and django. So, I am using a tutorial to do the JS part to add ajax. Everything in my code is exactly as shown in the tutorial but mine is not working.

So my javascript for ajax is:

<!--        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>

and this is my views.py file where I use my 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'})

My goal here is not to display youtube videos rightnow. My goal is to simply display 'Loading...' when the user is typing and if the user stops typing for one second it displays 6 video titles related to the term in the searchbar. So, i guess the problem is in the Javascript.

Also it is doing it's working upto the 'Loading...' part but shows nothing once user stops typing.

And this is the error it showing on console:

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)

I know nothing about JS right now so please be as specific as possible. This is a django project just needed to use javascript for this part.

Let me know if you need more information.

Thank you in advance!

Application/Json code from YouTube Search API:

{
  "kind": "youtube#searchListResponse",
  "etag": "eZ_XegkOrAIwxYDVnpYZmKbrfbE",
  "nextPageToken": "CAYQAA",
  "regionCode": "CA",
  "pageInfo": {
    "totalResults": 1000000,
    "resultsPerPage": 6
  },
  "items": [
    {
      "kind": "youtube#searchResult",
      "etag": "U21Po-KMvdNZ7xiYZgqhPjinEps",
      "id": {
        "kind": "youtube#video",
        "videoId": "ma67yOdMQfs"
      },
      "snippet": {
        "publishedAt": "2021-01-23T17:00:15Z",
        "channelId": "UC--3c8RqSfAqYBdDjIG3UNA",
        "title": "These Were The All-Time Surfing Moments Of The Year | Best Of 2020",
        "description": "Well, that was a weird ride. Though it hasn't been easy, at least when we fixed our gaze on the ocean — or favorite place in the world – very little had changed.",
        "thumbnails": {
          "default": {
            "url": "https://i.ytimg.com/vi/ma67yOdMQfs/default.jpg",
            "width": 120,
            "height": 90
          },
          "medium": {
            "url": "https://i.ytimg.com/vi/ma67yOdMQfs/mqdefault.jpg",
            "width": 320,
            "height": 180
          },
          "high": {
            "url": "https://i.ytimg.com/vi/ma67yOdMQfs/hqdefault.jpg",
            "width": 480,
            "height": 360
          }
        },
        "channelTitle": "Red Bull Surfing",
        "liveBroadcastContent": "none",
        "publishTime": "2021-01-23T17:00:15Z"
      }
1 Answers

I was using Crispy Forms on that page for my forms and it was stopping the code from running. I dont know why but once I removed crispy forms the code worked fine. Instead of crispy forms I am using widget tweaks now.

Related