2

i am having problem with my Jqueryajax call that will consume one of my web service method via cross domain. i have been trying all the possible way to accomplish but still no success. please help me with what i am doing wrong. may be i need to configure web server for some security settings? below is my code. please let me know if you have any question regarding with my code.

//Using Ajax Post
//Webservice will return JSON Format
//Doesn't work in both FF and IE when host to live server , work in local
//Error : Access is denined in xxxx.js in IE
//Http 403 Forbidden in FF , FF request header is OPTION
//this approach is the simplest and best way for me to use


    var myID = $("myID").val();
   $.ajax({
    type: "POST",        
    url: "http://www.mywebsite.com/webservice/Webservice.asmx/getInfo",
    data: "{myID:'"+ myID + "'}",
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function(data) {

           Dostuff(data);
        },

    error: FailureCallBack

});

My webservice will look like this

using System.Web.Script.Services;
[WebService(Namespace = "http://www.mywebsite.com/webservice/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[ScriptService]
public class Webservice : System.Web.Services.WebService
{
    [WebMethod]
    [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
    public object getInfo(string myID)
    {       
            //Do stuff here
            return getJSONDataFromDataSet(_DS); 
    } 


}

 

//second Approch <br/>
//Using Ajax GET , webservice will return XML Format <br/>
//Doesn't work in both FF and IE when host to live <br/>
//Error : Access is denined in xxxx.js in IE <br/>
//returning XML data in FF but showing nothing in page <br/>

var myID = $("myID").val();
     $.ajax({

        type: "GET",

        url: "http://www.mywebsite.com/webservice/Webservice.asmx/getInfo?myID="myID"&callback=?",    

        success: function(data) {

                Dostuff(data);
            },

        error: FailureCallBack

    });

Webservice

public SerializableDictionary<string, object> getInfo(string myID)
    {         
     //Do stuff here
            SerializableDictionary<string, object> obj = getJSONFromDataTable(_DS);            
            return obj;            
    }

 

//third Approch
//Using normal GET , webservice will return XML Format
//same problem with second approch



var myID = $("myID").val();
    var xmlhttprequest = createRequestObject();
    var url = 'http://www.mywebsite.com/webservice/Webservice.asmx/getInfo?myID='myID'';
    xmlhttprequest.open("GET", url, true);
    xmlhttprequest.onreadystatechange = getData;
    xmlhttprequest.send(null);
function getData() 
{
  if ((xmlhttprequest.readyState == 4) &&( xmlhttprequest.status == 200))
  {    
    var myXml = xmlhttprequest.responseXML;
    Dostuff(myXml);
  } 
}
function createRequestObject() 
{
      if (window.XMLHttpRequest) 
      {
                return xmlhttprequest = new XMLHttpRequest(); 
      } 
      else if (window.ActiveXObject) 
      {  
            return xmlhttprequest = new ActiveXObject("Microsoft.XMLHTTP"); 
      } 
}

Webservice is same with second approach

EDIT: now i am getting Access is denied , javascript error for both POST and GET request in IE. in fiddler i can see Firefox returning the Xml data but nothing showing in page, so i put a alert box in getData function, myXml variable value is always null, strange i only put 1 alert box and it show alert 3 times. below is my code

  var myID = $("myID").val();
    var xmlhttprequest = createRequestObject();
    var encodeUrl = escape(_utf8_encode("http://www.mywebsite.com/webservice/Webservice.asmx/getInfo?myID="myID)); 
    var url = 'http://www.mywebsite.com/webservice/proxy.aspx?url='+encodeUrl;
    xmlhttprequest.open("GET", url, true); //**ACCESS IS DENIED HERE in this line!!!!**
    xmlhttprequest.onreadystatechange = getData;
    xmlhttprequest.send(null);


function getData() 
{
    var myXml = xmlhttprequest.responseXML;
    alert(myXml); //ALWAYS NULL and show alert 3 times????
    DoStuff(myXml);
}

Please help. best regards

Community
  • 1
  • 1
sillyCat
  • 21
  • 1
  • 1
  • 2

3 Answers3

3

For security reasons, the ajax requests will not work cross domain. There are two solutions to this.

  1. Make the request to the same server, and use a server based proxy mechanism to then make the request to the other domain.

  2. Use "JSONP", which is an alternative cross way of making ajax like requests. jQuery supports this via the dataType: jsonp rather than json, and there is further explanation via their api docs. This blog entry may be useful - http://bloggingabout.net/blogs/adelkhalil/archive/2009/08/14/cross-domain-jsonp-with-jquery-call-step-by-step-guide.aspx

leebriggs
  • 3,187
  • 1
  • 20
  • 17
  • 1
    In order for jsonp to work the "other" server must accept cross domain requests and respond accordingly. but jsonp is not SOAP so that option is out unless the OP is able/willing to change from SOAP to JSON/JSONP. Using a server side proxy is the solution to this problem as you stated/ – Shiv Kumar Jan 29 '11 at 03:58
  • hi leeeb, the problem is i want to pass one of my Dictionary from webservice not just a simple string. if i use ajax post , very easy, but if i use get, i got error saying "Error generating xml" in fiddler. so i tried to Serializ my Ditionary before sending, now is ok but it only work in local. – sillyCat Jan 29 '11 at 05:04
1

you will need to create proxy on your domain and pass through the request, explain here: http://www.johnchapman.name/aspnet-proxy-page-cross-domain-requests-from-ajax-and-javascript/

Kris Ivanov
  • 10,476
  • 1
  • 24
  • 35
  • Hi KIvanov, just now i tested using your link. Proxy.aspx but no luck. the errors are extectly the same. i can get the xml result and Http response status is 200 OK. but nothing show in FF and access denined error in IE. – sillyCat Jan 29 '11 at 04:57
  • 1
    I have used it that way successfully, I am not aware if any other easy way to do it – Kris Ivanov Jan 29 '11 at 05:15
0

thanks so much for all the reply and help. i have solved the problem :D solution is to use JSONP and Javascript dynamic injection to html page. below is code

HTML

<body>
<script type="text/javascript">
var url = "http://www.mywebsite.com/Javascript/MYJS.js";

var script = document.createElement("script");       
script.setAttribute("src",url);
script.setAttribute("type","text/javascript");                
document.body.appendChild(script);
</body>
</script>

MYJS.js

var myID = $("#myID").val();
var url = "http://www.mywebsite.com/Webservice.aspx/getInfo?myID="+myID+"";

   if (url.indexOf("?") > -1)
            url += "&jsonp=" ;
        else
            url += "?jsonp=" ;
        url += "ShowInfoCallback" + "&" ; //Important put ur callback function to capture the JSONP data

       url += new Date().getTime().toString(); // prevent caching        




var script = document.createElement("script");        
    script.setAttribute("src",url);

    script.setAttribute("type","text/javascript");                
    document.body.appendChild(script);


function ShowInfoCallback(data)
{
 DoWhateverYouWant(data);    
}

Webservice.aspx.cs

using System.Web.Script.Serialization;
public partial class Webservice : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!string.IsNullOrEmpty(Request.QueryString["myID"]))
            this.getInfo();
        else
            this.getInfoDetails();

    }
    public void getInfo()
    {
        string Callback = Request.QueryString["jsonp"];
        string encryptedID = Request.QueryString["myID"];

        //Dowhateveryouwanthere

        object obj = getJSONFromDataTable(myDataSet.Tables[1]);
        JavaScriptSerializer oSerializer = new JavaScriptSerializer();
        string sJSON = oSerializer.Serialize(obj);
        Response.Write(Callback + "( " + sJSON + " );");
        Response.End();
    }
    public void getInfoDetails()
    {
        //Same as above
 //returning 2 tables , Info and InfoDetails
        Response.Write(Callback + "( { 'Info' : " + sJSONDetails +",'InfoDetails' : "+ sJSONService + " } );");
        Response.End();
    }
}

Thanks again

bluebird
  • 53
  • 1
  • 1
  • 5