I have the following JQuery Ajax request on my template that i want pass to my django view,
function loginUser(){
$.ajax({
type:"POST",
url :"/login-user/",
data:"title=ajax call",
datatype:"json",
error:function(data){alert('Error:'+data);}
success:function(data){alert('OK!'+data.message+','+data.code);}
});
}
my django view looks like this:
def login_user(request):
print "garbage"
print request.GET['title']
return_dict = {'message': 'bla bla bla','code':324}
json=serialize("json",return_dict)
return HttpResponse(json, mimetype="application/x-javascript"
When i call the ajax function i get the following error:
Error: [object XMLHttpRequest]
and on the django side i get the following error:
Traceback (most recent call last):
File "c:\python26\lib\site-packages\django\core\servers\basehttp.py", line 281, in run
self.finish_response()
File "c:\python26\lib\site-packages\django\core\servers\basehttp.py", line 321, in finish_response
self.write(data)
File "c:\python26\lib\site-packages\django\core\servers\basehttp.py", line 417, in write
self._write(data)
File "c:\python26\lib\socket.py", line 297, in write
self.flush()
File "c:\python26\lib\socket.py", line 284, in flush
self._sock.sendall(buffer)
error: [Errno 10053] An established connection was aborted by the software in your host machine
What am i missing on this call?
Gath
Using Ajax in Django can be done by directly using an Ajax library like JQuery or others. Let's say you want to use JQuery, then you need to download and serve the library on your server through Apache or others. Then use it in your template, just like you might do while developing any Ajax-based application.
To send and receive data to and from a web server, AJAX uses the following steps: Create an XMLHttpRequest object. Use the XMLHttpRequest object to exchange data asynchronously between the client and the server. Use JavaScript and the DOM to process the data.
I think the problem is serializing the dictionary. When I tested your code, I edited it to look like this and it worked:
from django.utils import simplejson
def login_users(request):
print "garbage"
print request.GET['title']
return_dict = {'message': 'bla bla bla','code':324}
json = simplejson.dumps(return_dict)
return HttpResponse(json, mimetype="application/x-javascript")
Also make sure you are passing in a value for title in your GET query string. I ran into that as well (may need to be error checked). It helps if you use a tool like Firebug, or even the Webkit Inspector. That way you can view the HTML error pages that Django is returning from your XHR request.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With