2

I want to make an ajax request in a Django framework. However, I don't pass to get data from the client in json. It works when I don't use Json. If I use dataType:'json' with a {'a': 'value'} in the ajax, I can't get it in the view.py, the result is nothing... However if I use data:$(this).serializeArray() in the ajax I can get result with request.POST. However, I really need to customize my data and send to my view.py other data than the data from the form. I would like to send a {'a', 'mydata', 'form': myformdata}... Is there a way to do it?

template:

<form id="ajax2" action="/seghca/test-post/" method="post">{% csrf_token %}
Nom : <input type="text" name="nom" value="" id="nom"/><br/>
prenom : <input type="text" name="prenom" value=""/><br/>
<input type="submit" value="Envoyer"/>
</form>


<div id="result"></div>

javascript:

$(document).ready(function(){


        // POST AJAX
        $("#ajax2").submit( function() {
        var urlSubmit = $(this).attr('action');

        var data = $(this).serializeArray();
        data.push({
                key:   "keyName",
                value: "the value"
            });
        $.ajax({  
            type: "POST",
            url: urlSubmit,
            dataType: "json",               
            data      : data,//$(this).serializeArray(),
            success: function(response){
                 var json_response = JSON.parse(response);
                    // now get the variables from the json_response
                    $('#result').html(json_response.html);
            }
        });
        return false;
    });

    });

view.py (the ajax launch the test_post view, home2 is the view of the formular):

from datetime import datetime
from django.http import HttpResponse, Http404
from django.shortcuts import redirect, render
from seghca.models import Article


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

def home2(request):
    return render_to_response('seghca/form.html', context_instance=RequestContext(request))

@csrf_exempt
def test_post(request):
    data = {'html': request.POST['key']}
    return HttpResponse(json.dumps(data), mimetype="application/json")
1

3 Answers 3

1

When you are using ajax view you should return the data back from your view in the json form:

data = {'html': request.POST['input']}
return HttpResponse(json.dumps(data), mimetype="application/json")

Second it is necessary to parse the response first on client side:

success: function(response){
    var json_response = JSON.parse(response);
    // now get the variables from the json_response
    $('#result').html(json_response.html);
}

Third if you need to pass the form data along with some more info you can do:

var data = $(this).serializeArray();
data.push({
    key:   "keyName",
    value: "the value"
});

Fourth you are missing csrf token.

Sign up to request clarification or add additional context in comments.

4 Comments

I edited my code with your correction, however, it does not solve the problem, views.py does not received anything! It seems django does not want to get get json...
Please make sure you are passing csrf token also in post data.
I edited with the decorator (it that correct?), but it still does not work.
Ok after several test, I found that from client to server everything works I can get a customize dictionnary. However from server to client json does not work at all, if I remove json it works but with json I have got nothing.
0

change data: data, to data: {'data': JSON.stringify(data)},

and you'll be able to access the serialized version of your data via POST['data'] in django. Keep in mind that if you want to use this in django you have to deserialize it, for instance json.loads(POST['data'])

Comments

0

I have your same needs. My solution was:

The AJAX request:

    var posturl = $('#'+formid).prop('action');

$.ajax({
        async:false,
        type: "POST",
        dataType: "json",
        contentType: "application/x-www-form-urlencoded",
        url : posturl,
        data : $('#'+formid).serialize() + '&mode=ajax', //&mode=ajax is my custom data
        success:function(response){             

                console.log(response);
                        alert(response.message);

        },
        timeout:10000
});

In the views.py:

        data = {'error': '0', 'message': 'all was ok'}
        return HttpResponse(json.dumps(data), mimetype="application/json")

The above should work for you. My test was with Django 1.6 and Python 2.7.5

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.