Monday, 26 August 2013

Ajax Posts but does not call Django View

Ajax Posts but does not call Django View

The Problem
After posting to my django view, the code seems to just stop halfway through.
I have an ajax post to a Django view that is hard coded to render a
specific response (see below). When I post to that view it should always
return that response, but for some reason the view out puts all of the
print statements, but not the query or the render. I know I'm being
redirected by my sever log (shown below).
Any idea what could be causing this behavior?
Server log:
127.0.0.1 - - [26/Aug/2013 21:27:23] "GET / HTTP/1.1" 200 -
127.0.0.1 - - [26/Aug/2013 21:27:23] "GET /static/css/style.css HTTP/1.1"
304 -
127.0.0.1 - - [26/Aug/2013 21:27:23] "GET /static/js/map.js HTTP/1.1" 200 -
127.0.0.1 - - [26/Aug/2013 21:27:23] "GET /static/js/home_jquery.js
HTTP/1.1" 304 -
127.0.0.1 - - [26/Aug/2013 21:27:23] "GET
/static/js/jquery_cookie/jquery.cookie.js HTTP/1.1" 304 -
127.0.0.1 - - [26/Aug/2013 21:27:23] "GET /favicon.ico HTTP/1.1" 404 -
I've been posted. Here are my values
<QueryDict: {u'name': [u'Mission Chinese Food'], u'address': [u'154
Orchard Street Manhattan']}>
Mission Chinese Food
154 Orchard Street Manhattan
127.0.0.1 - - [26/Aug/2013 21:27:32] "POST /results/ HTTP/1.1" 200 -
Simple Django View:
def results(request):
if request.method == 'POST':
print "I've been posted. Here are my values"
print request.POST
print request.POST.get('name')
print request.POST.get('address')
restaurant = Restaurant.objects.filter(name='Fish', address='280
Bleecker St')[0]
return render(request, "stamped/restaurant.html", {'restaurant':
restaurant}
Simple ajax post:
var send_data = { 'name': place.name, 'address': address};
var csrftoken = $.cookie('csrftoken');
alert(csrftoken);
alert(send_data);
function csrfSafeMethod(method) {
// these HTTP methods do not require CSRF protection
return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
$.ajaxSetup({
crossDomain: false, // obviates need for sameOrigin test
beforeSend: function(xhr, settings) {
if (!csrfSafeMethod(settings.type)) {
xhr.setRequestHeader("X-CSRFToken", csrftoken);
}
}
});
$.ajax({ url: '/results/',
type: 'POST',
data: send_data,
success: function(response) {
console.log("everything worked!");
},
error: function(obj, status, err) { alert(err); console.log(err); }
});
});

No comments:

Post a Comment