Using JSON in Internet Explorer with jQuery


Using JSON in Internet Explorer with jQuery

Ok, so you’ve been working on a project and decided to get fancy with some jQuery Ajax magic. Awesome! You do all your work in FireFox or maybe even Chrome so you can use Firebug or other Developer tools, and everything seems good, right? Well, since you’re a good developer you want to make sure everyone can enjoy in your hard work so you open up Internet Explorer to test and *cue music* DUN DUN DUN, it doesn’t work…. Hmm… Ok, let’s start debugging and seeing why. 1st you check for syntax errors.

$.ajax({
   type: "GET",
   url: "/events",
   dataType: "json",
   success: function(data) {
     //do stuff with data
    },
   error: function(xhr, status, error) {
     alert(status);
   }
});


Ok, looks like everything is ok with the syntax. What is the status that is being “alerted”? In my case it was “parsererror”. If you’re like me, you’re thinking.. “WHAT DOES THAT EVEN MEAN?!?”. It’s ok, it just means there was an error while trying to parse the target document. So, just out of curiosity, lets see what the value of the xhr.status is, shall we?


$.ajax({
   type: "GET",
   url: "/events",
   dataType: "json",
   success: function(data) {
     //do stuff with data
   },
   error: function(xhr, status, error) {
     alert(xhr.status);
   }
});


And what do we get?? 200!! Wait… what? My first guess was that the server wasn’t returning json properly. Go check your server side code and make sure it’s formatted properly. Basically, no extra commas at the end of an object. Go ahead, I’ll wait…

this..

"item" : { "one":1, "two":2, "three":3, }

should be

"item" : { "one":1, "two":2, "three":3 }


Done? Still no luck? Then let’s move onto the next step. It’s time to get CRAZY!


$.ajax({
   type: "GET",
   url: "/events",
   dataType: "json",
   cache: false, // don't cache the result
   contentType: "application/json", //tell the server we're looking for json
   success: function(data) {
     //do stuff with data
   },
   error: function(xhr, status, error) {
     alert(xhr.status);
   }
});


Now I want to force the content type, and make sure that it doesn’t cache the ajax request.
Note: at this point, it *may* or *may not* work for you. (For me, this didn’t work. So, let’s move on.)

It turns out, IE does like to cache the ajax requests. Sometimes it might not play well with headers though. So what you see passed through to one of the other browsers, might not be the same thing being passed here. There is only 1 more thing I need to add to this to make it work the way I want. I have trust issues when it comes to the whole cacheing thing. Never can tell if clicking the “clear cache” and “always refresh from server” buttons are actually working. For anyone who has used Ruby on Rails before may have seen something that looks like

...src="javascripts/all.js?412847289374"

So, using that idea, let’s add that to our URL and explicitly tell it that it’s json. With that said, we have…


var date = new Date(); // grabbing the date as of this second it gets run
$.ajax({
   type: "GET",
   url: "/events.json?_="+date.getTime(), //add the time stamp and specified format to the end
   dataType: "json",
   cache: false,
   contentType: "application/json",
   success: function(data) {
     //do stuff with data
   },
   error: function(xhr, status, error) {
     alert(xhr.status);
   }
});


Alright, code is place, we run it, and BAM! It’s working! Now, there are small variations here that you can mess with to get it working, but let’s recap to make sure we understand everything.

  • 1. Check ALL syntax
  • 2. Look to see if the xhr object in your error function is returning a status 200
  • 3. Set cache to false and contentType to “application/json”
  • 4. Add a .json extension and the timestamp to the URL

As of this writing, jQuery 1.4 was just released, so things might change. If anyone knows of a “cleaner” fix to this, please feel free to let me know.

  • del.icio.us
  • StumbleUpon
  • Facebook
  • Google Bookmarks
  • Technorati
  • Digg
  • Mixx
  • Reddit
  • Slashdot
  • Design Float
  • email
  • RSS
post tags

Tags: , , , , ,


author name

About Jeremy Woertink (Sr. Developer)

As a Ruby programmer, and E-commerce professional, Jeremy helped Just Professionals get to where it is today. He provides the programming muscle to Just Professionals, and plays the bass guitar in a local band for fun.
follow me on twitter


  • http://www.caelum.com.br/ Sergio Lopes

    I had some problems today with JQuery 1.4 and IE6/7. After hours of debugging I discovered that my JSON was “invalid” (even with all other browsers working ok and JSONLint sayong it was ok).

    My problem was a single n before the JSON string…

  • justpros

    Thanks for posting that! There are a few quirks in jQuery 1.4. Yehuda Katz posted a good fix for handling malformed JSON with 1.4.

    http://yehudakatz.com/2010/01/15/jquery-1-4-and...

  • Bhoomi

    My code is still not working..

    function GetMe() {
    $.ajax({
    url: “ajaxify.aspx/abc”,
    type: “GET”,
    contentType: “application/json;”,
    data: “{}”,
    dataType: “json”,
    cache: false,
    success: function(data)
    {
    alert('here');
    alert('here' + data);
    },
    error: function(xhr, data, a)
    {
    alert('error' + data);
    alert('error' + a);
    alert('error'+ xhr.status);
    }
    });
    }

    On Server side it is :

    [WebMethod]
    static public object abc()
    {
    //return “abc”;
    return @” [{ ""Name"": ""abc"",
    ""Name"": ""pqr"",
    ""Name"": ""xyz"" }]“;
    }
    It is a valid json format. Throws same parsererror, xhr is 200. Pl help..

  • justpros

    Well, I'm not familiar with C, but IE is trying to look for a .json extension regardless the of content type. I've found adding .json to the url fixes this. Can you try adding “ajaxify.aspx/abc.json”?

  • Fkrueger

    Wasn’t my issue, but very nice written :-)

    Finally I discovered that a jquery call before a form.serializeArray causes the IE to produce JSON parser errors.
    After modifying the order my script works.

  • Jwoertink

    Do you have an example you could post? I would like to see some other options for readers looking for an answer. Thanks!

  • Renan Augusto

    thanks!!!

  • Netplayer

    Thank you! i had suspected that but didnt know how to make the declration. Your instructions are perfectly clear and saved some of my last few hair :)

  • http://twitter.com/mindless_pixie Elsabe Lessing

    Very nice post, hopefully this will sort out my AJAX issues!

  • Eli

    thanks for the help!!! 

  • Info

    What about when you are posting and the response contains the JSON and IE8 still says parsererror as well as invalid JSON  but all the other browsers are fine?

  • Daniel Bologna

    maybe later, but thanks for your post .. I can add my experience about this. I pretend fill an array with some json objects (where your id field start with “lang_”), then .. 

    $(domxml).find(“msg”).each(function() {
    id = $(this).attr(“id”) ;
    subid = id.replace(“lang_”,”");
    if (id && typeof id==”string” && id.indexOf(“lang_”)>-1 &&
      availables.indexOf( subid )>-1 ){
    item = {“id” : id.replace(“lang_”,”"), “msg” : $(this).attr(“msg”) };
    avaiLangs.push(item);
    }});

    oop’s !! .. surprise: I connt use “item” as variable for an json object in IE. 
    solution: 
    iread={“id” : id.replace(“lang_”,”"), “msg” : $(this).attr(“msg”) };
    avaiLangs.push(iread);

    thanks again.

  • Dengfan

     Thank you for your post. It help me

  • Minotaurus

    Thank you for this great post! I didn´t know that the IE caches Ajax-Requests, so the timestamp solution helped me very much!

  • http://twitter.com/jessizanelato Jessica Zanelato

    Thank you! It save me ;)  

  • http://www.facebook.com/vladutcornel Vladut Cornel Borina

    That’s nice,
    but I think it would be better if you send no cache headers from the server directly.
    Something like:
    Cache-Control:post-check=0, pre-check=0Cache-Control:no-store, no-cache, must-revalidateConnection:keep-alivePragma:no-cache

  • Axel Salas

    Hi Jeremy, You made a great work but in my case my code is still not working, i am using POST, this is the code,

    var options = {
    type: “POST”,
    url: “procesa.php”,
    data: $(‘#form_upload’).serialize(),
    dataType: “json”,
    cache: false,
    contentType: “application/json”,
    beforeSubmit: mostrarLoader, // pre-submit callback
    success: mostrarRespuesta, // post-submit callback
    error: function(xhr, status, error) {
    alert(error);
    }
    };
    // bind form using ‘ajaxForm’
    $(‘#form_upload’).ajaxForm(options);

    from my php code i am sending this.
    header(‘Content-Type: application/json; charset=utf-8′);
    $arr = array(‘file_name’ => $nombre, ‘email’ => $email, ‘file_size’ =>$tamano, ‘amount’ =>$tot,’res’ =>’yes’);
    echo json_encode($arr);

    I get a this: SyntaxError: Syntaxerror

    I hope you can help me.

    Best Regards!!

  • mrku

    i love you!!!!
    You save my day!!!

  • Lon Jaurigue

    NICE! Thanks alot! This help alot! Woooot! :D

  • Anonymous

    Hi sir . I have the same problem. Sorry but How did you managed to solve it?

    Please aswer to my mail if it possible please… denebasecas@gmail.com

  • Anonymous

    Hi,

    I am using ASP MVC in my project. Here I have on JSON object which I need to SAVE at server side. Following is my AJAX call:

    jQuery.ajax({
    type: “POST”,
    url: “Controller Action”,
    data: JSONObj,
    dataType: “json” ,
    success: function (response, textStatus, xhr) {
    if (0 == response.length) {
    alert(“Exception is Occured at Server Side”);
    }
    else {
    alert(“Successfully Updated”);
    }
    return true;
    }
    },
    error: function (xhr, textStatus, errorThrown) {
    alert(errorThrown);
    }
    });

    Above mentioned ‘JSONObj’ is going to mapped with one Model at server side and then it will get updated into database.

    Now above call works on Firefox and Chrome but the same code is not working on IE 10 only (On IE9 also it is working).

    On IE 10 this ‘JSONObj’ is not getting parsed but same ‘JSONObj’ send through FF & GC is getting parsed at server side.

    Please let me if any one know the solution.

  • John

    Very good. Worked for me.

blog comments powered by Disqus
Just Professional - MMA Web Design

JustProfessionals J

PostDraw.com gives Draw Something fanatics a place to showoff
OMGPOP, recently bought by Zynga Inc. (NASDAQ:ZNGA) shell-shocked the mobile gaming ...

Believe In The Value of Your Product
When Just Professionals opened its doors in the middle of a ...

New Yahoo! Store from Just Professionals
Just Professionals is excited to announce the launch of our latest ...

JUST PROFESSIONALS Sponsors Frank Mir at UFC 119 versus Cro Cop
Just Professionals and its staff are huge fans of the MMA ...

Just Slide – jQuery Content Slider
What is it? A jQuery slider plugin. Used to take a list ...