I am trying to return a JSONP object from a django view by appending the callback to the response as below:
def complete(request):
prefix = request.GET.get('q','')
mode = request.GET.get('mode','')
callback = request.GET.get('callback', '')
response = completer_func(prefix, inv_indices, trie)
if callback != None:
response = '{0}({1})'.format(callback, response)
return JsonResponse(response, safe=False)
which returns something like "jQuery11110037170758636331014_1499222434194([u'information technology', u'interior design', u'international', u'industrial design', u'information technology services'])"
when I check the response under inspect/network in chrome. However, at the client side, it is throwing an error, which I logged to the console and shows that
readyState: 4
demo.html:91 responseText: undefined
demo.html:92 status: 200
demo.html:93 text status: parsererror
demo.html:94 error: Error: jQuery11110037170758636331014_1499222434194 was not called
I saw a couple of other posts like this explaining how one should add the callback to the response (which I did). But somehow it doesn't seem to work. I have included the jquery ajax call below
$('#ajax-demo').autoComplete({
minChars: 1,
source: function(term, response){
$.ajax({
dataType: "jsonp",
type: "GET",
url: 'http://localhost:8000/complete/',
data: {
q: term
},
success: function (data) {
},
error: function(xhr,textStatus,err){
console.log("readyState: " + xhr.readyState);
console.log("responseText: "+ xhr.responseText);
console.log("status: " + xhr.status);
console.log("text status: " + textStatus);
console.log("error: " + err);
}
});
}
});
Update 1
I was able to fix this problem following this answer and allowing CORS headers at my server side and using JSON instead of JSONP. But I am still wondering what was wrong in my first approach.