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
<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
$(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):
[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