I’ve been scratching my head over this for about an hour and a half now. So, I’m sending a form via $.ajax and expecting a json response back from django.
On the front end, js looks like this
$.ajax({
"type" : "POST",
"url" : action,
"dataType" : "json",
"data" : serialized_form,
"success" : function (data) {
alert('hey')
console.log(data);
//$("#add_shipping").submit();
},
"error" : function (data) {
alert(data)
}
});
On the back end, django is returning an HttpResponse object stuffed with the serialized json
like so ->
redirectUrl = '/user/purchase/' + str(purchase.pk) + '/'
response_data = {}
response_data['redirect'] = redirectUrl
response_data['status'] = 200
rsp = HttpResponse(simplejson.dumps(response_data))
rsp["CONTENT-TYPE"] = "application/json"
return rsp
When jQuery gets the response, instead of logging it to the console like I have asked it to, it simply displays the formatted json in the browser surrounded by pre tags. I’m guessing this may have something to do with my Content-type header, but from what I can tell it’s responding with ‘application/json’. Can anyone think of what I may be doing wrong? Thank you!
You’re probably running that code in a form’s submit event without cancelling the submit.
Therefore, the browser is submitting the form and navigating to that page.
Add
return false.