Ajax Post and Django Tastypie

curl --dump-header - -H "Content-Type: application/json" -X POST --data '{"latlong": "test"}' http://localhost:8000/geo/api/geolocation/ 

This works fine, but when I try to reproduce the POST in ajax below, I get 500 errors.

 $.ajax({ type: 'POST', url: 'http://localhost:8000/geo/api/geolocation/', data: '{"latlong": "test"}', success: latlongSaved(), dataType: "application/json", processData: false, }); 

Error message:

 {"error_message": "The format indicated 'application/x-www-form-urlencoded' had no available deserialization method. Please check your ``formats`` and ``content_types`` on your Serializer." .... } 

It is worth noting that this is a cross-domain, and I am using django-crossdomainxhr-middleware.py found using git: gist

If I add a content type to an ajax call, for example:

 contentType: "application/json" 

I am returning this error:

 XMLHttpRequest cannot load http://localhost:8000/geo/api/geolocation/. Request header field Content-Type is not allowed by Access-Control-Allow-Headers. Request URL:http://localhost:8000/geo/api/geolocation/ Request Method:OPTIONS Status Code:200 OK Request Headersview source Access-Control-Request-Headers:Origin, Content-Type, Accept Access-Control-Request-Method:POST Origin:http://localhost:3000 Response Headersview source Access-Control-Allow-Methods:POST,GET,OPTIONS,PUT,DELETE Access-Control-Allow-Origin:* Content-Type:text/html; charset=utf-8 Date:Tue, 23 Aug 2011 07:59:49 GMT Server:WSGIServer/0.1 Python/2.6.1 
+8
jquery ajax django tastypie
source share
3 answers

I added XS_SHARING_ALLOWED_HEADERS to the middleware and solved the problem.

https://gist.github.com/1164697

+3
source share

You explicitly declare your content type in your call to curl , but you do not point to your jQuery.ajax() call.

Update your JavaScript to determine what the content type will be:

 $.ajax({ type: 'POST', url: 'http://localhost:8000/geo/api/geolocation/', data: '{"latlong": "test"}', success: latlongSaved(), dataType: "application/json", processData: false, contentType: "application/json" }); 
+7
source share

Add XsSharing (https://gist.github.com/1164697) in settings.py:

 MIDDLEWARE_CLASSES = [ ..., 'django-crossdomainxhr-middleware.XsSharing' ] 

Then use the following javascript to call ajax:

 $.ajax({ type: 'POST', url: 'http://localhost:8000/geo/api/geolocation/', data: '{"latlong": "test"}', success: latlongSaved(), contentType:'application/json', dataType: 'application/json', processData: false, }); 

Please note that data must be a properly formed JSON string, otherwise jQuery will silently ignore the ajax call and do nothing.

What is behind the scenes is that the ajax call will first send OPTIONS /geo/api/geolocation/ . Since the response header is modified by the XsSharing middleware, jQuery issues another POST /geo/api/geolocation that does the actual creation.

+3
source share

All Articles