13

So here is my call:

   $.ajax({
       url: url,
       headers: { 'Access-Control-Allow-Origin': '*' },
       crossDomain: true,
       success: function () { alert('it works') },
       error: function() {alert('it doesnt work')},
       datatype: 'jsonp'
   });

My url is legit. You will notice that i do not have data set. I m not sure if datatype is working properly as its actually xml being returned, but i tried that too. Its a call to sportsdata's api. On the site, they show you a request header of x-originating-ip so i have tried that where access-control-allow-origin is.

All of this still returned the access-control error. I am not clear on what data is if i set it, so i have omitted it for now. I have tried a few different things i googled, i understand why i am getting the error. I do not know how to fix it. I tried to not have to ask, but if someone could explain or show me the way, that would be greatly appreciated

SuReSh
  • 1,503
  • 1
  • 22
  • 47
dwarf
  • 445
  • 2
  • 9
  • 23
  • 5
    The server has to set the access control header, not the client. – Jason P Sep 30 '13 at 03:20
  • well am i screwing up? because its not a call to my local machine. the server is not local, but i have read that on other posts. why, if i type my url in the browser directly, the call works, but with the jquery it does not? – dwarf Sep 30 '13 at 03:24
  • Furthermore, if you tell jQuery to expect JSONP, then the server has to return JSONP, not XML. – Felix Kling Sep 30 '13 at 03:25
  • @user2070677: Because if you type the URL in the address bar, you are *not* making an Ajax request. Ajax requests are restricted to the same domain (unless the server allows access from different domains). – Felix Kling Sep 30 '13 at 03:25

2 Answers2

8

http://encosia.com/using-cors-to-access-asp-net-services-across-domains/

refer the above link for more details on Cross domain resource sharing.

you can try using JSONP . If the API is not supporting jsonp, you have to create a service which acts as a middleman between the API and your client. In my case, i have created a asmx service.

sample below:

ajax call:

$(document).ready(function () {
        $.ajax({
            crossDomain: true,
            type:"GET",
            contentType: "application/json; charset=utf-8",
            async:false,
            url: "<your middle man service url here>/GetQuote?callback=?",
            data: { symbol: 'ctsh' },
            dataType: "jsonp",                
            jsonpCallback: 'fnsuccesscallback'
        });
    });

service (asmx) which will return jsonp:

[WebMethod]
    [ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json)]
    public void GetQuote(String symbol,string callback)
    {          

        WebProxy myProxy = new WebProxy("<proxy url here>", true);

        myProxy.Credentials = new System.Net.NetworkCredential("username", "password", "domain");
        StockQuoteProxy.StockQuote SQ = new StockQuoteProxy.StockQuote();
        SQ.Proxy = myProxy;
        String result = SQ.GetQuote(symbol);
        StringBuilder sb = new StringBuilder();
        JavaScriptSerializer js = new JavaScriptSerializer();
        sb.Append(callback + "(");
        sb.Append(js.Serialize(result));
        sb.Append(");");
        Context.Response.Clear();
        Context.Response.ContentType = "application/json";
        Context.Response.Write(sb.ToString());
        Context.Response.End();         
    }
Saranya
  • 1,988
  • 16
  • 20
0

At my work we have our restful services on a different port number and the data resides in db2 on a pair of AS400s. We typically use the $.getJSON AJAX method because it easily returns JSONP using the ?callback=? without having any issues with CORS.

data ='USER=<?echo trim($USER)?>' +
         '&QRYTYPE=' + $("input[name=QRYTYPE]:checked").val();

        //Call the REST program/method returns: JSONP 
        $.getJSON( "http://www.stackoverflow.com/rest/resttest?callback=?",data)
        .done(function( json ) {        

              //  loading...
                if ($.trim(json.ERROR) != '') {
                    $("#error-msg").text(message).show();
                }
                else{
                    $(".error").hide();
                    $("#jsonp").text(json.whatever);

                }

        })  
        .fail(function( jqXHR, textStatus, error ) {
        var err = textStatus + ", " + error;
        alert('Unable to Connect to Server.\n Try again Later.\n Request Failed: ' + err);
        });     
Liam
  • 27,717
  • 28
  • 128
  • 190
yardpenalty.com
  • 1,244
  • 2
  • 17
  • 32