El arquitecto El arquitecto - 4 years ago 176
jQuery Question

Trying to get input value through ajax with Django

I'm trying to get the input value through with django using ajax is not working I hope you can help me I have seen the code all the day and I do not find the error.

It suppose to give the value by an alert window.

views.py

def form(request):
return render_to_response('prueba2.html')

from django.views.decorators.csrf import csrf_exempt
@csrf_exempt
def form_ajax(request):
if request.is_ajax() and request.method == 'POST':
nombre = request.POST['nombre']
return HttpResponse(nombre)


file.html

<!DOCTYPE html>
<html>
<head>
<title></title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
</head>
<body>
<script type="text/javascript">
$(function() {

$(document).on('submit', '#fomulario', function(e){
e.preventDefault();

$.ajax({
type:'POST',
url:'http://127.0.0.1:8000/form_ajax/',
async: 'true',
data: $('#nombre').val(),

success: function(data) {
alert(data)
},

});

})


});
</script>

</body>

<form id="fomulario">
<label for="Nombre">Nombre</label>
<input type="text" name="nombre" id="nombre" value="hola">
<input type="submit">
</form>

<div id="valor"></div>

</html>


All suppose to work properly if I make something like this:

views.py

def form(request):
return render_to_response('prueba2.html')

from django.views.decorators.csrf import csrf_exempt
@csrf_exempt
def form_ajax(request):
if request.is_ajax() and request.method == 'POST':
#nombre = request.POST['nombre']
return HttpResponse('HELLO THIS IS ME...')


I think django is not taking the value of the input name.

Do you have any idea how to solve this problem ?

Answer Source

You should set param name.

 $.ajax({
    type:'POST',
    url:'http://127.0.0.1:8000/form_ajax/',
    async: 'true',
    data: {nombre: $('#nombre').val()},       

    success: function(data) {
        alert(data)
    },  

});
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download