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"
    )
markwalker_
  • 12,078
  • 7
  • 62
  • 99

2 Answers2

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
        }
      })
   })
});
dhana
  • 6,487
  • 4
  • 40
  • 63
  • 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/` 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? – markwalker_ Apr 30 '14 at 09:58
  • Here is link http://stackoverflow.com/questions/20306981/how-do-i-integrate-ajax-with-django-applications – dhana Apr 30 '14 at 10:01
  • Here is another link http://www.fir3net.com/Django/how-do-i-use-ajax-along-side-django.html – dhana Apr 30 '14 at 10:02
  • whats the best way to debug an error being thrown if `errorThrown` is blank? #nothingisevereasy – markwalker_ Apr 30 '14 at 14:22
  • yeah, it hits the error callback every time but the error message is always blank (I've been following the jquery docs). & added my js to my original question. – markwalker_ May 01 '14 at 06:38
  • I've added the view as it stands. The ajax method I've posted is in `POST` but I've been switching between `GET/POST` in ajax, but django only ever seems to recieve a `GET` request. – markwalker_ May 01 '14 at 07:06
  • 1
    you can debug your server response in chrome developer toolbar. you can find the response network tab. https://developers.google.com/chrome-developer-tools/ – dhana May 01 '14 at 07:31
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 :)

Ahsan
  • 696
  • 1
  • 9
  • 9