1

When I try to call wcf service from $.ajax method I am getting following Exceptions.

1. Failed to load resource: the server responded with a status of 405 (Method Not Allowed) 2. Failed to load resource: No 'Access-Control-Allow-Origin' header is present on the requested resource. 

AJAX Coding

 $.ajax({ type: "POST", dataType: "json", contentType: "application/json", data: JSON.stringify(request), async: false, url: "http://localhost:65201/Empservice.svc/getEmployee", crossdomain: true, success: function (data) { try { response = data; } catch (e) { alert(e); } }, error: function (XMLHttpRequest, textStatus, errorThrown) { alert("Excpetion " + errorThrown + XMLHttpRequest); } }); 
7
  • url what you specified is incorrect use url:"your url" Commented Feb 27, 2014 at 10:21
  • Have a read here Commented Feb 27, 2014 at 10:24
  • you make a request to cross domain but you defined your dataType as JSON. Change to JSONP and if you trying to access your localhost file mention your ip address inside your url ex:url"yourIpAddress/Empservice.svc/getEmployee" Commented Feb 27, 2014 at 10:25
  • when use url as string pattern in ajax call after that too we are facing the same response Commented Feb 27, 2014 at 10:25
  • we used jsonp instead of json then following method not fire it. success: function (data) { try { response = data; } catch (e) { alert(e); } }, Commented Feb 27, 2014 at 10:32

1 Answer 1

1

To avoid 405 Method not allowed error try to add following coding in wcf serivce Global.asax file.it working for me

 protected void Application_BeginRequest(object sender, EventArgs e) { if (HttpContext.Current.Request.HttpMethod == "OPTIONS") { HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "Accept, Content-Type,customHeader"); HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "POST,GET,OPTIONS"); HttpContext.Current.Response.AddHeader("Access-Control-Max-Age", "172800"); HttpContext.Current.Response.AddHeader("Access-Control-Allow-Credentials", "true"); HttpContext.Current.Response.AddHeader("Access-Control-Expose-Headers", "customHeader"); HttpContext.Current.Response.AddHeader("Content-type", "application/json"); HttpContext.Current.Response.End(); } else { HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "Accept, Content-Type,customHeader"); HttpContext.Current.Response.AddHeader("Access-Control-Expose-Headers", "customHeader"); HttpContext.Current.Response.AddHeader("Content-type", "application/json"); } } 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.