I have tried both JsonResponse and HttpResponse(along with json.dumps) but even though ajax is returning to success, returned json can't be parsed by $.parseJSON(returned_json).
I am sure that the problem is not with parsing($.parseJSON(returned_json)) by printing out json.dumps value in terminal and copying the value into a variable and giving it to $.parseJSON, and it successfully parsed it.
I tried to pass simplest json but it also fails whose example I am showing below: In views.py
from django.http import JsonResponse
In my view which is handling ajax:
return JsonResponse({"stat":"Success"})
In my ajax file:
$.ajax({
url:"feed/get_comments/",
type: "GET",
data:{c_id: cid}, //cid is a variable initialized above and not creating any problem
success: function(ret_json){
alert("Inside success"); //Running everytime
var sam_json = '{"stat":"Success"}'; //same as what is given in JsonResponse
var data = $.parseJSON(ret_json); //for debugging change to sam_json
alert(data); //with sam_json alerting with dictionary, with ret_json not giving any alert
},
Instead of JsonResponse if I use json.dumps along with HttpResponse same thing is happening. From above I can only conclude that JsonResponse and HttpResponse is not returning data in json format even though json.dumps is successfully converting in json format(as I copied this and pasted in ajax variable). Please help.
parseJSON isn't needed.
Since you're just working with a dictionary you can just access it as you would with any other dictionary in javascript
For example.
alert(ret_json.stat);
With HttpResponse and json dump, you can get response data in js like this
var val = $.ajax({
url:"feed/get_comments/",
type: "GET",
data:{c_id: cid}, //cid is a variable initialized above and not creating any problem
success: function(ret_json){
alert("Inside success"); //Running everytime
var sam_json = '{"stat":"Success"}'; //same as what is given in JsonResponse
var data = jQuery.parseJSON(val.responseText); //for debugging change to sam_json
alert(data); //with sam_json alerting with dictionary, with ret_json not giving any alert
},
val.responseText will have the data you are sending from view.