Json does not work in Django with Ajax
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 input_string = $("#nom").val();
var t = {};
$.ajax({
type: "POST",
url: urlSubmit,
dataType: "json",
data : {input :
input_string},//$(this).serializeArray(),
success: function(data) {
alert("Ajax completed");
$('#result').html(data);
}
});
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
import json
def home2(request):
return render_to_response('seghca/form.html',
context_instance=RequestContext(request))
def test_post(request):
if request.POST.has_key('input'):
print request.POST['input']
return HttpResponse(request.POST['input'])
else:
return HttpResponse("No input")
No comments:
Post a Comment