Koolaid Koolaid - 1 month ago 9
Javascript Question

Passing a JSON string to django using JQuery and Ajax

I'm a bit new to Django and trying to understand it. Currently, I'm creating a network topology visualiser (think routers and switches connected together). It works fine and all of the data is saved in a javascript object.

I want to have the ability to, when a user clicks a button, send this javascript object to django so that it can be parsed and handled appropriately. I did a lot of research and found a bunch of similar implementation which use a combination of JQuery and ajax to POST a JSON string. This is some of my code currently:

mainapp/urls.py

from django.conf.urls import include, url
from django.contrib import admin

urlpatterns = [
url(r'^NetworkTopology/', include('OpenAutomation.NetworkTopology.urls')),
url(r'^NetworkTopology/json/', include('OpenAutomation.NetworkTopology.urls')),
url(r'^admin/', admin.site.urls),
]


NetworkTopology/urls.py

from django.conf.urls import url

from . import views

urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'^json/$', views.returnjson, name='returnjson'),
]


NetworkTopology/views.py

from django.http import HttpResponse
from django.shortcuts import render_to_response


def index(request):
return render_to_response('index.html')


def returnjson(request):
if request.is_ajax():
request_data = request.POST
print("Raw Data: " + request_data.body)
return HttpResponse("OK")


JavaScript function (return JSON button is pressed):

function returnJsonTop(){
$(document).ready(function() {
$.ajax({
method: 'POST',
url: '/NetworkTopology/json',
dataType: 'json',
data: JSON.stringify(nodes.get(),null,4),
success: function (data) {
//this gets called when server returns an OK response
alert("it worked!");
},
error: function (data) {
alert("it didnt work");
}
});
});
}


In my index template, I have created a button which calls the returnJsonTop() function when it is pressed:

<button id="submitJson" onclick="returnJsonTop();">Deploy</button>


Currently, when I press the Deploy button, I just get the 'it didn't work' alert that has been setup to handle an errors. I'd really appreciate someone pointing me in the right direction here. I suspect the issue is in my urls.py files but I've tried various combinations of urls without any luck.

Answer

For those reading this later, this is what I did:

mainapp/urls.py

from django.conf.urls import include, url
from django.contrib import admin

urlpatterns = [
    url(r'^NetworkTopology/', include('OpenAutomation.NetworkTopology.urls')),
    url(r'^admin/', admin.site.urls),
]

NetworkTopology/urls.py

from django.conf.urls import url

from . import views

urlpatterns = [
    url(r'^$', views.index, name='index'),
    url(r'^json/$', views.returnjson, name='returnjson'),
]

NetworkTopology/views.py

from django.http import HttpResponse
from django.shortcuts import render_to_response
from django.views.decorators.csrf import csrf_exempt


def index(request):
    return render_to_response('index.html')


@csrf_exempt
def returnjson(request):
    if request.is_ajax():
        request_data = request.POST
        print("Raw Data: " + str(request_data))
        return HttpResponse("OK")

I was getting a 403 error so I added '@csrf_exempt'. I'll probably change this to handle it properly afterwards.

Return JSON function:

function returnJsonTop(){
            $.ajax({
                method: 'POST',
                url: '/NetworkTopology/json/',
                dataType: 'json',
                data: JSON.stringify(nodes.get(),null,4)
            });         
    }