0

I've got a page which draws thumbnails of Youtube videos via the google API and I've used Masonry to control said thumbnails & enlarge an element when it's clicked on (at which point I'd like to have the iframe displaying the video).

What I would like to do is render a template containing the iframe & a few extra things for a selected video in the thumbnail element. Trouble is, I'm not great with javascript that isn't clearly found in an example!

At the moment django is setup for non-script users...

My thumbnail page is at /videos/ with each thumbnail rendering the following template;

<div class="video">
    <a class="GetYoutubeVideo" data-video-id="{{ object.video_id }}" href="{% url 'show_video' video_id=object.id %}">
    {{ object.get_img_tag }}
    <span class="title">
        <p>{{ object.get_title|slice:":20" }}...</p>
        <p class="date">{{ object.date_created|date:"d/m/Y" }}</p>
    </span>
    </a>
</div>

<script>
    $(document).ready(function(){
        $(".GetYoutubeVideo").click(function(){
            $.ajax({
                type: "POST",
                dataType: 'json',
                url: $(this).attr('href'),
                timeout: 5000,
                data: {
                    csrfmiddlewaretoken: document.getElementsByName('csrfmiddlewaretoken')[0].value,
                    video_id: $(this).attr('data-video-id')
                },
                success : function(json) {
                    console.log('Success ' + json);
                    $('#result').append('Server Response: ' + json.server_response);
                },
                error : function(xhr, errmsg, err) {
                    // Currently hits this with an empty `err`
                    console.log('Ajax Error: ' + errmsg + ' and ' + err);
                    alert(xhr.status + ": " + xhr.responseText);
                }
            })
        })
    });
</script>

With video iframes at /videos/<video_id>/ using the following view;

@never_cache
def show_video(request, page_id=None, video_id=None, **kwargs):
    """
    Displays the selected YouTube video.

    @type request:      HttpRequest
    @param request:     The HttpRequest object
    @type page_id:      int
    @param page_id:     The ID of the page where this video is found
    @type video_id:     int
    @param video_id:    The id of the video to display the images of
    @rtype:             HttpResponse
    @return:            The rendered template
    """
    # Get the VideoGalleryPlugin object
    video = get_object_or_404(VideoGalleryPlugin, pk=video_id)
    video_data = video.video_data()

    return render_to_response('display_video.html',
        RequestContext(
            request, {
                'page_id': page_id,
                'video': video,
                'video_data': video_data,
            }
        )
    )

Do I need to do something like bind a click event to the thumbnail link with $.ajax and then have a request.is_ajax() in show_video()?

edit Here's my view as it stands while I'm hitting the error callback in $.ajax():

@csrf_exempt
@never_cache
def show_video(request, page_id=None, video_id=None, **kwargs):

    # Get the VideoGalleryPlugin object
    video = get_object_or_404(VideoGalleryPlugin, pk=video_id)
    video_data = video.video_data()

    return HttpResponse(
        json.dumps({
            'page_id': page_id,
            'video': serializers.serialize('json', [video, ]),
            'video_data': video_data,
        }), content_type="application/json"
    )

2 Answers 2

1

Try this,

<div class="video">
    <a class="GrapSomeData" href="{% url 'show_video' video_id=object.id %}">{{ object.get_img_tag }}
    <span class="title">
        <p>{{ object.get_title|slice:":20" }}...</p>
        <p class="date">{{ object.date_created|date:"d/m/Y" }}</p>
    </span>
    </a>
</div>

Django view:

@never_cache
def show_video(request, page_id=None, video_id=None, **kwargs):
    """
    Displays the selected YouTube video.

    @type request:      HttpRequest
    @param request:     The HttpRequest object
    @type page_id:      int
    @param page_id:     The ID of the page where this video is found
    @type video_id:     int
    @param video_id:    The id of the video to display the images of
    @rtype:             HttpResponse
    @return:            The rendered template
    """
    # Get the VideoGalleryPlugin object
    video = get_object_or_404(VideoGalleryPlugin, pk=video_id)
    video_data = video.video_data()

    return HttpResponse(json.dumps({
                'page_id': page_id,
                'video': video,
                'video_data': video_data,
            }))

At Jquery side,

$(document).ready(function(){
   $(".GrapSomeData").click(function(){
      $.ajax({
        type:"GET",
        dataType: 'json',
        url:this.href,
        success: function(response){
           // Get response from django server
          // do your code here
        }
      })
   })
});
Sign up to request clarification or add additional context in comments.

7 Comments

That appears to do what I need, however it may be my lack of experience with this type of response, but it just renders the json data (plain json in the page) to the /videos/<video_id> url rather than returning the json to the success function. Is there a doc I can read to explain this or a simple answer to this?
whats the best way to debug an error being thrown if errorThrown is blank? #nothingisevereasy
you can debug your server response in chrome developer toolbar. you can find the response network tab. developers.google.com/chrome-developer-tools
|
1

You actually don't need to add request.is_ajax(), if you are not using the several actions in same method. If you only want to load a page in ajax call your code is pretty fine to work with.

And follow the jquery ajax code,

jQuery(function(){
jQuery('class_or_id').on('click', function(){
  jQuery.ajax(
    url: 'your_url',
    type: 'POST or GET',
    success: function(response){
      //whatever you want
      // means if you want to load your content in specific place you can
    }
  );
});
});

I hope you'll enjoy :)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.