I’m stuck trying to convert data from the AJAX call to view.py
and back to HTML:
JQuery/Javascript
function getCookie(name) {
var cookieValue = null;
if (document.cookie && document.cookie !== '') {
var cookies = document.cookie.split(';');
for (var i = 0; i < cookies.length; i++) {
var cookie = cookies[i].trim();
// Does this cookie string begin with the name we want?
if (cookie.substring(0, name.length + 1) === (name + '=')) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
}
function csrfSafeMethod(method) {
// these HTTP methods do not require CSRF protection
return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
$(document).ready(function(){
var csrftoken = getCookie('csrftoken');
$.ajaxSetup({
beforeSend: function(xhr, settings) {
if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
xhr.setRequestHeader("X-CSRFToken", csrftoken);
}
}
});
// AJAX CALL TO VIEW
$('a.play').click(function(e){
e.preventDefault();
var song_id = $(this).attr('id');
alert(song_id);
$.ajax({
url: $(this).data('href'),
type: 'POST',
content: 'application/json; charset=utf-8',
data: {
'song_id': song_id
},
dataType: 'json',
success: function(html) {
alert(html);
$('.player').replaceWith(html);
},
});
});
});
views.py
from django.shortcuts import render
from django.http import Http404, JsonResponse
from django.core import serializers
from django.template.loader import render_to_string
from .models import Song
def change_song(request):
if request.method == "POST":
request.session['featured_song'] = request.POST.get('song_id', '')
featured_song_id = request.session['featured_song']
obj = Song.objects.get(pk=featured_song_id)
song_list = Song.objects.all().order_by('-date') # list of objects
context = {
"featured_song": obj,
"song_list": song_list,
}
return render_to_string("music/player.html", context)
Therefore, after receiving the POST for the AJAX call, I try to return it to alert its content (debugging). The first alert song_id
returns the id as it should, the second does not even run. When trying to debug (I don’t remember the exact situation), when it runs, the second alert()
just returns the WHOLE html page, not just the portion.
NOTES:
music/player.html
on the view is basically the .player
container. It is void of includes or extends or blocks that extend other templates.
2
Answers
So, I ended up resolving the issue. It was an template/url issue all along...
I was trying to access the sub APP url path
href="/change/"
and didn't fill the complete URL for the APPhref="/music/change/"
. My thought process was that, since the template was inside the template folder in 'music' APP, the URL only needed the/change/
part of the URL.That being said, I will still post the code here for future reference since I also fixed some JSON handling, in case someone needs to use something similar.
views.py
AJAX/jQuery/Javascript
If you want to parse the ajax call json, do the following in your view: