0

net MVC application, in which I have multiple charts. On these charts, I have applied filters and by clicking each filter, I do an ajax call which returns the result in Json and then applies to the charts.

Now its working perfectly in Firefox and Chrome, but in Internet Explorer - Ajax call is always unsuccessful. I tried hitting the web api url directly through my browser and the issue it seems is, the result json was being returned as a file to be downloaded.

This is my ajax code :

function getIssueResolvedGraphdata(control, departCode, departName) {
$.ajax(
    {
        type: "GET",
        url: WebApiURL + "/api/home/GetQueryIssueResolvedData?deptCode=" + departCode,
        dataType: "json",
        crossDomain: true,
        async: true,
        cache: false,
        success: function (myData) {
            var resolvedStartDate = myData.data.IssueResolvedStartDate;
            var issueData = myData.data.IssueData;
            var resolveData = myData.data.ResolvedData;

            //converting issueData into integer array...
            var issue = issueData.replace("[", "");
            var issue1 = issue.replace("]", "");
            var issue2 = issue1.split(",");
            for (var i = 0; i < issue2.length; i++) { issue2[i] = parseInt(issue2[i]); }

            //converting resolvedData into integer array
            var resolve = resolveData.replace("[", "");
            var resolve1 = resolve.replace("]", "");
            var resolve2 = resolve1.split(",");
            for (var j = 0; j < resolve2.length; j++) { resolve2[j] = parseInt(resolve2[j]); }

            //getting max value from array...
            var issueMaxVal = Math.max.apply(null, issue2);
            var resolveMaxVal = Math.max.apply(null, resolve2);

            //Eliminating leading zeros in issue array
            var removeIndex = 0;
            var myDate;
            var newDate;
            var arrayLength;
            if (issueMaxVal != 0) {
                arrayLength = issue2.length;
                for (var i = 0; i < arrayLength; i++) {
                    if (issue2[0] == 0) {
                        issue2.splice(0, 1);
                        removeIndex = i;
                    } else {
                        break;
                    }
                }

                //Getting days count of current month
                var monthStart = new Date(new Date().getFullYear(), new Date().getMonth(), 1);
                var monthEnd = new Date(new Date().getFullYear(), new Date().getMonth() + 1, 1);
                var monthLength = (monthEnd - monthStart) / (1000 * 60 * 60 * 24);
                var monthDays = 0;
                if (monthLength == 28) {
                    monthDays = removeIndex;
                }
                else if (monthLength == 30) {
                    monthDays = removeIndex + 1;
                }
                else if (monthLength == 31 || monthLength == 29) {
                    monthDays = removeIndex + 2;
                }

                //matching the resultant issue array with resolve array & setting start date
                var iDate = resolvedStartDate;
                var tDate = '';
                for (var i = 0; i < iDate.length; i++) {
                    if (iDate[i] == ',') {
                        tDate += '/';
                    }
                    else {
                        tDate += iDate[i];
                    }
                }
                if (removeIndex != 0) {
                    resolve2.splice(0, (removeIndex + 1));
                    var myDate = new Date(tDate);
                    myDate.setDate(myDate.getDate() + monthDays);
                    newDate = Date.UTC(myDate.getFullYear(), (myDate.getMonth() + 1), myDate.getDate());
                } else {
                    var myDate = new Date(tDate);
                     newDate = Date.UTC(myDate.getFullYear(), (myDate.getMonth() + 1), myDate.getDate());
                }

            } else {
               alert("Empty");
            }

            //updating chart here...
            var chart = $('#performance-cart').highcharts();
            chart.series[0].update({
                pointStart: newDate,
                data: issue2
            });
            chart.series[1].update({
                pointStart: newDate,
                data: resolve2
            });


            if (issueMaxVal > resolveMaxVal) {
                chart.yAxis[0].setExtremes(0, issueMaxVal);
            } else {
                chart.yAxis[0].setExtremes(0, resolveMaxVal);
            }
        },
        error: function (x, e) {
            alert('There seems to be some problem while fetching records!');
        } });}

Code from web api controller :

 [HttpGet]
 [CrossDomainActionFilter]
public Response<GraphIssueResolvedWrapper> GetQueryIssueResolvedData(string deptCode)
{
  Response<GraphIssueResolvedWrapper> objResponse = new Response<GraphIssueResolvedWrapper>();
  GraphIssueResolvedWrapper objGraphIssueResolvedWrapper = new GraphIssueResolvedWrapper();
    try
    {
        ....code.....
        objResponse.isSuccess = true;
        objResponse.errorDetail = string.Empty;
        objResponse.data = objGraphIssueResolvedWrapper;
    }
    catch (Exception ex)
    {
        objResponse.isSuccess = false;
        objResponse.errorDetail = ex.Message.ToString();
        objResponse.data = null;
    }
    return objResponse;
}

Reponse Class :

public class Response<T>
{
    public bool isSuccess { get; set; }
    public string errorDetail { get; set; }
    public T data { get; set; }
}

I am stuck at this for hours now. Any help will be appreciated.

NewbieProgrammer
  • 874
  • 2
  • 18
  • 50
  • Nah, IE just does that when you try to view a JSON stream. Open IE, hit F12, and familiarize yourself with its developer tools which will let you see the network traffic: http://msdn.microsoft.com/en-ca/library/ie/gg589507(v=vs.85).aspx My guess however, is your success handler has an incompatibility with IE - can you add that code? – Mister Epic Jul 15 '14 at 11:54
  • I see, well I am using IE8 and I don't see network traffic option in developer's tool. Also, I have added Response class, is that what you wanted? – NewbieProgrammer Jul 15 '14 at 12:10
  • Ugh, IE8... What's in `success: function (myData) {` ? – Mister Epic Jul 15 '14 at 12:11
  • @ChrisHardie added complete code. – NewbieProgrammer Jul 15 '14 at 12:21
  • When you have developer tools open, can you click "Start Debugging" and refresh the page? See if an error is thrown. – Mister Epic Jul 15 '14 at 12:25
  • Is there a reason to return your data as generic class instead of returning JsonResult, which is actually one of number of proper ways to return data from WebApi? – Dmitry Zaets Jul 15 '14 at 12:33
  • for IE8 this link should help [How can I convince IE to simply display application/json rather than offer to download it?](http://stackoverflow.com/questions/2483771/how-can-i-convince-ie-to-simply-display-application-json-rather-than-offer-to-dow) – NicoD Jul 15 '14 at 12:42
  • @ChrisHardie No, I am not getting any errors. – NewbieProgrammer Jul 15 '14 at 12:43
  • @U10 I tried returning Json but VS was unable to pick Json as a return method. – NewbieProgrammer Jul 15 '14 at 12:45
  • My bad, there is no Json return method in WebApi. It will be returned as Json by default. The problem is in ContentType for IE8. Can you check it also in IE9+? – Dmitry Zaets Jul 15 '14 at 12:46

2 Answers2

0

You've missed contentType: 'text/html' which is pretty important for IE7-8:

$.ajax(
    {
        type: "GET",
        url: WebApiURL + "/api/home/GetQueryIssueResolvedData?deptCode=" + departCode,
        dataType: "json",
        contentType: 'text/html'
        crossDomain: true,
        async: true,
        cache: false,
        success: function (myData) {
            var result = JSON.parse(myData);
            ///...code...
        },
        error: function (x, e) {
            alert('There seems to be some problem while fetching records!');
        }
    }
);

To make it works in IE7-8 you also need to be sure that you've writing Conrent-Type Header into your response on server side. Add this line right before return statement;

response.Content.Headers.ContentType = new MediaTypeHeaderValue("text/html; charset=iso-8859-1");

And in code probably you will need to parse result in success method by using JSON.parse(myData);

Dmitry Zaets
  • 3,289
  • 1
  • 20
  • 33
  • unfortunately, I have already tried that but I am still getting that error. How do I add Content-Type Header into server-side response? – NewbieProgrammer Jul 15 '14 at 12:23
  • Where should I paste this `HttpContext.Current.Response.AppendHeader("Content-type", "text/html; charset=iso-8859-1");` ? In my controller ? – NewbieProgrammer Jul 15 '14 at 12:31
0

I have solved my problem by using the following code : ( I guess it needed CORS support)

function isIE() {
            var ua = window.navigator.userAgent;
            var msie = ua.indexOf("MSIE");
            if (msie > 0)
                return true;
            return false;
        }

Then in document.ready function of my binding script :

    $(document).ready(function () {
        if (isIE())
            $.support.cors = true;
    });

Note : it still download Json stream as a file but now my AJAX call is successful upon each hit.

NewbieProgrammer
  • 874
  • 2
  • 18
  • 50