Django: accept AJAX call and render response?

524 Views Asked by At

Here's my javascript code:

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 = jQuery.trim(cookies[i]);
                // 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;
    };

    var csrftoken = getCookie('csrftoken');

    //Ajax call
    function csrfSafeMethod(method) {
    // these HTTP methods do not require CSRF protection
        return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
        }
        $.ajaxSetup({
            crossDomain: false, // obviates need for sameOrigin test
            beforeSend: function(xhr, settings) {
                if (!csrfSafeMethod(settings.type)) {
                    xhr.setRequestHeader("X-CSRFToken", csrftoken);
                }
            }
    });

    $(".color_wheel").click(function() {
    $.ajax({
        url:'/',
        type: "POST",
        data: {num : level},
    });});

And here's my views file:

from django.shortcuts import render
from .models import Joke

# Create your views here.
def home_page(request):
    return render(request, 'home.html')

def joke_page(request):
    if request.POST:
        num = request.POST['num']     
        return render(request, 'joke.html', {'joke': Joke.find_joke(num)})

As you can see, I want Django to accept an AJAX call, take the given number(num) and use it to display a new page. The thing is, it doesn't work... Maybe I'm doing something wrong, maybe the whole thing is wrong... Please help if you know how. Thank you!

Edit:

urls.py

from django.conf.urls import url

from jokes import views

urlpatterns = [
    url(r'^$', views.home_page, name='home_page'),
    url(r'^(?P<joke_id>[0-9]+)/$', views.joke_page, name='joke_page'),
]
1

There are 1 best solutions below

5
On

I think this can done simply using a GET request

$(".color_wheel").click(function() {
    window.location.href = "/"+devel,
})

In view

def joke_page(request, joke_id):
    return render(request, 'joke.html', {'joke': Joke.find_joke(joke_id)})