The following function results in the response variable being null in Chrome and Safari but not Firefox.
function updatePage(response){ // This argument differs by browser
response = jQuery.parseJSON(response);
for(var i=0; i<response.length; i++){
// conduct magic
};
};
Error:
Uncaught TypeError: Cannot read property 'length' of null
This is because feeding jQuery.parseJSON() anything but a JSON string returns null. It seems Chrome and Safari automatically parse JSON without explicitly being requested. If I test the "response" argument before trying to parse it with jQuery, it's already a JSON object in both Chrome and Safari. However, in Firefox it's still a string.
The only solution I've come up with to handle this across browsers is to determine if "response" has already been parsed by checking its constructor:
function updatePage(response){
if(response.constructor === String){
response = jQuery.parseJSON(response);
};
for(var i=0; i<response.length; i++){
// conduct magic
};
};
Am I missing something or is this the only way to handle this currently? Seems like jQuery.parseJSON would detect the user-agent and just return the argument as-is in the case of Chrome/Safari.
Pertinent information
$.ajax({
url: API_URL + queryString + '&limit=' + limit,
type: 'GET',
cache: false,
context: document.body,
success: updatePage,
error: function(err){
console.log('ERROR: ' + err);
}
});
It's not Chrome or Safari, it's jQuery that does the parsing if it sees the appropriate Content-Type
on the response. (Update: And the Content-Type
you've added to the question is correct.) I can't immediately see why it wouldn't be doing it on Firefox.
You can force it to always do the parsing by adding dataType: 'json'
to your call, details in the jQuery.ajax
docs. Then you wouldn't call parseJSON
at all, response
would already be the deserialized object.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With