[SOLVED] How to Fix $.ajax() Not Working ie 8, ie 9 and ie 10

 

jQuery is an great tool to use for making ajax calls. As usual MS Internet Explorer has to make things that would otherwise be standard — difficult. Setting aside any rants about how much hair one can pull out in the days it takes to accomplish something that should have been easy, here is what works.

In order for $.ajax() to work with ie, there are certain things you must make sure are in place.

Internet Explorer, in all its wisdom, insists on caching, so it is important to prevent ie from caching when making a GET call to an API.

This can be done a number of ways shown below.

In the client side jQuery code

To prevent caching universally in your jQuery code use:

$.ajaxSetup({ cache: false });

On a per call basis, use “cache: false,”  within the $.ajax() object as shown below.

In the $.ajax()  object

Be sure to specify    contentType: ‘application/json; charset=utf-8’,  within the $.ajax() object.
However, the dataType within the $.ajax() object, should remain as dataType: ‘json’,

Important Server Side configurations:

Be sure to set the response headers as follows:
“Access-Control-Allow-Origin”, “*”
“Access-Control-Allow-Headers”, “Origin, X-Requested-With, Content-Type, Accept”
‘Content-Type’, ‘text/plain’  <– this can be a gottcha for ie

Also, there is a workaround for the Cross-Domain AJAX for IE8 and IE9 mess.

If you are working with jQuery, install the script from the following git repo. It’s easy. Just include it and it works!  Be sure to install it after the jQuery script is called. You do not need to configure anything.
https://github.com/MoonScript/jQuery-ajaxTransport-XDomainRequest

Example  $.AJAX()  OBJECT that works with IE 8 – 11

var url = "http://some-api.com/some-api-call";
var urlRand = new Date().getTime(); <-- used to prevent ie caching

$.ajax({
      cache: false,
      crossDomain: true,
      type: 'GET',
      url: url,
      data:{ quanPerOrder: quanPerOrder,
             ordersPerMonth: ordersPerMonth,
             pallets: pallets,
             uniqueProds: uniqueProds,
             urlRand: urlRand},  <-- this is to prevent ie caching
      contentType: 'application/json; charset=utf-8', <-- this can be a gottcha for ie
      dataType: 'json',  <-- this can be a gottcha for ie
      success: function(data) {
          console.log('SUCESS!!!');
      },
      error: function (jqXHR, exception) {
          // Note: Often ie will give no error msg. Aren't they helpful?
          console.log('ERROR: jqXHR, exception', jqXHR, exception );
      }
}).done(function(data){

    // .. "do stuff here"
    // 
});

Leave a Reply

Your email address will not be published. Required fields are marked *