Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery 1.9 .ajax() datatype default changed?

Given an ajax call such as:

$.ajax(
{
    url:"MyWebService.blah",
    data: {"data":"awesome"},
    success : function(responseText)
    {
       var myJsonObj = $.parseJSON(responseText);
       //do stuff with myJsonObj
    }
});

This was working fine. I updated jQuery to 1.9 today (I was on 1.6 for a while) as a possible fix to Safari all of the sudden not supporting various toggle functionality (something about eventLayer.X no longer supported), and now all my ajax calls are throwing the following javascript error:

Uncaught Syntax Error: Unexpected token o

After a little research and some testing, I discovered that "responseText" in my code above is now a JSON object, not a string. So the error makes sense, but I'm trying to wrap my head around this. Did jQuery really change the default return type? I checked the documentation:

http://api.jquery.com/jQuery.ajax/

and dataType is defaulted to "Intelligent Guess". I can see how that might be convenient, but I also don't like it.

So here are my questions:

  1. Is this a new(ish) change in jQuery?
  2. Was it version 1.9 that did this, or has it been this way before and I'm a fossil having been using 1.6?
  3. What are some suggestions to handle this and sort of "future-proof" my code?

This is a pretty fundamental change that affects a lot of code. I will go through my code and remove any instance of parsing my returned data to JSON, but this whole thing is a little unnerving. Was I mistaken in not specifying a dataType? I suppose it is a good practice to enforce a dataType instead of relying on default, but... wow. Am I alone on this, or was that a tad presumptuous of a change on the part of jQuery?

like image 874
AceCorban Avatar asked Apr 12 '13 17:04

AceCorban


1 Answers

jQuery automatically detects what the dataType is based on what was returned if no dataType was set. Most likely 1.9 just improved that detection to properly detect what you are returning as json. It's best to always give a datatype to ensure you'll always get consistent results.

like image 95
Kevin B Avatar answered Nov 23 '22 23:11

Kevin B