Why is my jQuery.ajax answer empty with Django

I am trying to return a JSON response from a Django view call using an ajax call, as shown below:

var tab = 'test'; var response = $.ajax({ url: "/" + tab + "/" }).responseText; alert(response); 

Here is my Django view:

 if request.is_ajax() == True: req = {} req['html'] = '<b>This is a test</b>' response = simplejson.dumps(req) print response return HttpResponse(response, mimetype="application/json") else: return render_to_response("ajax/pingpong.html", {'ajax': ajax}) 

For some odd reason, the warning field is empty (although it doesn't specify undefined). Interestingly, $ .post and $ .getJSON work fine on the same URL. I also see the expected JSON output on my console. Any help would be appreciated!

+4
source share
5 answers

If I am mistaken, responseText not an attribute when returning $.ajax() . I think you need to do something like this:

 $.ajax({ url: "/test", dataType: "json", success: function(data) { // use data } }); 

Because of the dataType parameter dataType data received for the success callback is a regular JS object. If you do not specify dataType , you will get a string with raw content that the server returns.

+1
source

You do not set the dataType parameter to json , and you need to get the json object from the success function, try the following:

 var tab = 'test'; $.ajax({ url: "/" + tab + "/", dataType: "json", success: function(json){ alert(json); } }); 
+2
source

Despite the fact that the documentation claims that ResponseText blocks the browser until the request is completed, it seems to me that you are getting a race condition, that is, you are warning the variable until the XHR request is completed. You will need to do something like this:

 var complete = function(data) { console.log(response.responseText); } var tab = 'test'; var response = $.ajax({ url: "/" + tab + "/", dataType: "json", success : complete }); 
+1
source

Try this instead:

 var tab = 'test'; var response = $.ajax({ url: "/" + tab + "/", success: function(data, textStatus) { alert(data); } }); 
+1
source

I have the same problem, but only in a specific environment. I am wondering if your problem will be the same. My environment:

  • Starting the internal Django web server (./manage.py runningerver 0.0.0.0:8080)
  • View my site in Google Chrome (v4.1.249.1025).

In these circumstances, the following jQuery code yields data = null, status = "success" in about half the time. The other half of the time when it returns a valid object for data.

 $.ajax({ type:"POST", url:"response/"+q.id+"/", cache:false, dataType:"json", data:{response:$(this).val()}, success:function(data, status) { alert(data+","+status); }, error:function() { $(".main_container").text("Error. Please check your internet connection."); } }); 
0
source

All Articles