Click here to Skip to main content
15,886,873 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I trying to get the ajax function to request data from a url, however the scripts throws the error alert. in the console log window, it shows the following message:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://test.domain.com/test2.aspx. This can be fixed by moving the resource to the same domain or enabling CORS.

I added the following headers in my web.config page, but when I request from the host (test.domain.com/test2.aspx), I get the following message in my console log with the a 404 response - not found:

config headers in test.domain.com/test2.aspx
HTML
<system.webServer>
 <httpProtocol>
  <customHeaders>
   <add name="Access-Control-Allow-Origin" value="*" />
   <add name="Access-Control-Allow-Headers" value="Content-Type" />
  </customHeaders>
 </httpProtocol>
</system.webServer>


Ajax function
JavaScript
$(document).ready(function () {
     $.support.cors = true;
     $.ajax({
         type: "Post",
         crossDomain: true,
         contentType: "application/json; charset=utf-8",
         url: "http://wwww.test.domain.com/test2.aspx/BindDatatable",
         data: "{}",
         dataType: "json",
         success: function (data) {
             alert(data.toSource());
             console.log(data);
             var myData = JSON.parse(data.d)
              for (var i = 0; i < myData.length; i++) {
                  $("#tbDetails").append("<tr><td>" + myData[i].Name + "</td><td>" + myData[i].Loan + "</td><td>" + myData[i].Evnt + "</td></tr>");
             }
         },
         error: function (result) {
             alert("Error");
         }
     });
 });


server side code (test.aspx.cs):
C#
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
    [WebMethod()]
    public static string BindDatatable()
    {
        DataTable dt = new DataTable();
        List<UserDetails> details = new List<UserDetails>();

        using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["#####"].ConnectionString))
        {
            using (SqlCommand cmd = new SqlCommand("######", con))
            {
                con.Open();
                SqlDataAdapter da = new SqlDataAdapter(cmd);
                da.Fill(dt);
                foreach (DataRow dtrow in dt.Rows)
                {
                    UserDetails user = new UserDetails();
                    user.Name= dtrow["###"].ToString();
                    user.Loan = dtrow["###"].ToString();
                    user.Evnt = dtrow["###"].ToString();
                    details.Add(user);
                }
            }
        }
         JavaScriptSerializer serializer = new JavaScriptSerializer();
         return serializer.Serialize(details);
    }

   public class UserDetails
    {
        public string Deal { get; set; }
        public string LoanProperty { get; set; }
        public string Events { get; set; }
    }


How can I make my function work, by using the url host to call the data?

Thank you
Posted
Updated 23-Mar-15 2:18am
v2
Comments
Kornfeld Eliyahu Peter 23-Mar-15 6:59am    
Can you show the code for test2.aspx?
miss786 23-Mar-15 8:19am    
Thank you for your reply. I have updated my original post showing the server side code behind test2.aspx, for further reference. many thanks for any further help.
F-ES Sitecore 23-Mar-15 7:25am    
The headers have to be sent with test2.aspx, not your page, so the config change needs to happen on test.domain.com
miss786 23-Mar-15 8:24am    
apology for the late response.
the cors headers are already in place under the host domain files - test.domain.com/test2.aspx.

i would like to clarify, if the need to define the cors header in the head tag of the text.aspx page as well.
thank you for your feedback.

1 solution

Apparently jQuery adds another header to CORS requests. Try:

XML
<system.webServer>
 <httpProtocol>
  <customHeaders>
   <add name="Access-Control-Allow-Origin" value="*" />
   <add name="Access-Control-Allow-Headers" value="Content-Type" />
   <add name="Access-Control-Allow-Headers" value="x-requested-with" /> <!-- Add me! -->
  </customHeaders>
 </httpProtocol>
</system.webServer>


As per answer on http://stackoverflow.com/questions/5750696/how-to-get-a-cross-origin-resource-sharing-cors-post-request-working[^].
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900