Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is jqXHR.responseText returning a string instead of a JSON object?

I had the same problem. I returns a string because it formulated from an exception. E.g. I use a kernel listener with serialization to json on my Symfony2 project. Which is correct for proper REST headers.

Anyway, just parse it; this works for me:

$.ajaxSetup({
    "error": function(jqXHR, status, thrownError) {
        alert('error');
        var responseText = jQuery.parseJSON(jqXHR.responseText);
        console.log(responseText);
    }
});

Try

$.ajaxSetup({
    "error": function(jqXHR, status, thrownError) {
        alert('error');            
        console.log(jqXHR.responseJSON);
    }
});

You are using $.ajax in a way the docs don't describe. Using json as the dataType just means that the data passed to the success callback will be parsed. Use it like this:

$.ajax({
  dataType:'json',
  type: 'GET',
  url: "http://example.com/api/"
  success: function(data, textStatus, jqXHR) {
    // `data` contains parsed JSON
  },
  error: function(jqXHR, textStatus, errorThrown) {
     // Handle any errors
  }
});

I don't see anything in the documentation that suggests responseText would be anything other than exactly what the name implies: text.

Why not just use .getJSON? That would get rid of half of the code you wrote, and it'll convert the response to JSON. Win/win.