Friday, 10 January 2014

Call WCF Restful service from cross domain including IE7,8,9,10 and other well known browsers

Hello guys,

Last time i put some example code to call wcf restful service in cross domain but it was not working in IE.

My previous code of javascript was not able to call WCF service from IE because my code uses httpXMLRequest while IE only supports XDomainRequest ( earlier version of IE10 ).

Here, i improved my code and put example below that will work in all the most usable
versions of IE - IE7, IE8, IE9, IE10 and all other well know browsers.

So developers no need to worry about cross domain call making from IE.

Just refer below code:

if ($.browser.msie && window.XDomainRequest) {
            if (window.XDomainRequest) {
                var xdr = new XDomainRequest();
                var query = 'MyUrl';
                if (xdr) {
                    xdr.onload = function () {
alert(xdr.responseText);
                     }
                    xdr.onerror = function () { /* error handling here */ }
                    xdr.open('GET', query);
                    xdr.send();
                }
            }
        }
        else {
$.ajax({
                type: "GET",
                crossDomain: true,
                url: 'MyUrl',
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (data) {
alert(data);
                },
                error: function (response, textStatus, errorThrown) {
                    alert('not OK ' + response.responseText);
                    alert('not OK ' + textStatus.responseText);
                    alert('not OK ' + errorThrown);
                }
            });
}


that's it.
It was the standard method to do that.

Now one js is also available to do the same thing, you can just put below js in your page and call the wcf service by just your old code ($.ajax(...)) and you can get the result.

<script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/jquery-ajaxtransport-xdomainrequest/1.0.1/jquery.xdomainrequest.min.js"></script>

This js is responsible to convert the request as per the browser used.


One more thing if your data is not showing properly on page then set your
document mode as standard so IE will use its maximum capacity of supports.
other browsers are so intelligent so no need to explain more here.
To set document mode standard just put below line in header part of your page.

<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />

it'll work in IE7, IE8 and IE9, IE10 supports all the things so no need to put this.

Enjoy Scripting...

No comments:

Post a comment