Passing a JSON string to django using JQuery and Ajax
<p>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.</p>

<p>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:</p>

<p>mainapp/urls.py</p>

<pre><code>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),
]
</code></pre>

<p>NetworkTopology/urls.py</p>

<pre><code>from django.conf.urls import url

from . import views

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

<p>NetworkTopology/views.py</p>

<pre><code>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")
</code></pre>

<p>JavaScript function (return JSON button is pressed):</p>

<pre><code>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");
                    }
                });
            });           
        }
</code></pre>

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

<pre><code>&lt;button id="submitJson" onclick="returnJsonTop();"&gt;Deploy&lt;/button&gt;
</code></pre>

<p>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.</p>

<p>first of all you dont even need to use all this in your ajax call 
      data: JSON.stringify(nodes.get(),null,4),
replace by 
      data: nodes.get(),
should be enougth as long as this method returns a valid json object</p>

<p>second  one, I Â´d strongly recommend you to use a framework to help you to parse JSON
python have may, but to ilustrate this example, I ve used django rest framework, which is a very good one.</p>

<pre><code>from django.shortcuts import render
from django.http import HttpResponse
from django.views.decorators.csrf import csrf_exempt
from rest_framework.renderers import JSONRenderer
import json
import controllers#this class belongs to my business logic layer, you can encapsulate yours and use instead of it

#in this solution you must create a pre-parser to handle responses
class JSONResponse(HttpResponse):
    """
    An HttpResponse that renders its content into JSON.
    """
    def __init__(self, data, **kwargs):
        content = JSONRenderer().render(data)
        kwargs['content_type'] = 'application/json'
        super(JSONResponse, self).__init__(content, **kwargs)

@csrf_exempt # this is for prevent invasions
def login(request):
#this one here handle your jquery post data into a valid json object in python represented by a Dict
    envelopin = json.loads(request.body)
# here we pass the dict inside my business controll logic routine which also responds with a valid Python Dict
    envelopout = controllers.login(envelopin)
# and for last, we use our pre-parser Class to make your response be handled by jquery as valid json
    return JSONResponse(envelopout)
</code></pre>

<p>and that is it, you success jquey data variable, will hold the envelopout json object, in the same shape as it has inside yor django-python code.</p>

<p>hope this help</p>

javascript jquery python ajax django