views:

1210

answers:

5

I'm trying to return a JSON response from a Django view call via an ajax call like 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 alert box is blank (though it does not say undefined in it). Interestingly enough, $.post and $.getJSON work fine on the exact same URL. I also see the expected JSON output on my console. Any help would be appreciated!

+2  A: 

You're not setting the dataType parameter to json, and you'll need to get the json object from the success function, try this:

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

Unless I am mistaken, responseText isn't an attribute on whatever $.ajax() returns. I think you have to do something like this:

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

Because of the dataType parameter, the data yielded to the success callback is a normal JS object. If you don't specify the dataType, you'll get the string with the raw content the server returns.

August Lilleaas
Right, that's what I was expecting (string with raw contents)...Anyways, my problem was forgetting the success: function..Whoops!
sluther
+1  A: 

Although the documentation claims ResponseText will block the browser until the request is complete it appears to me like you're getting a race condition, i.e your alerting the variable before the XHR request is complete. You'll have 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
});
Daniel
+1  A: 

Try this instead:

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

I'm having the same issue but only under a specific environment. I'm wondering if your issue is the same. My environment:

  1. Running Django's internal webserver (./manage.py runserver 0.0.0.0:8080)
  2. Viewing my website in Google Chrome (v4.1.249.1025).

Under those circumstances, the following jQuery code leads to data = null, status = "success" around half the time. The other half the time 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.");
   } 
});
Aaron