JQuery Cross Domain Error - No 'Access-Control-Allow-Origin' - c#

The POST request
var url = "http://xxx.xxx.x.x/MyServices.svc/GetOrders";
$.ajax({
type: "POST",
url: url,
crossDomain : true,
data: 'abcd',
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (result) {
data = result.data;
},
error: function (xhr, ajaxOptions, thrownError) {
debugger;
alert('error');
}
});
When the url address is localhost i am getting a response
When trying to do so across servers I am getting an Error:
405 (Method Not Allowed)
XMLHttpRequest cannot load http://xxx.xxx.x.x/MyServices.svc/GetOrders. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.
All of the answers on the web where inconclusive.

If you can deal with json in return, then try using jsonp for speaking between domains:
$.ajax({
type: "POST",
dataType: 'jsonp',
...... etc ....
As documented in official site :-
The advent of JSONP — essentially a consensual cross-site scripting
hack — has opened the door to powerful mashups of content. Many
prominent sites provide JSONP services, allowing you access to their
content via a predefined API.
and
jQuery handles all the complex aspects of JSONP behind-the-scenes —
all we have to do is tell jQuery the name of the JSONP callback
parameter specified by YQL ("callback" in this case), and otherwise
the whole process looks and feels like a normal Ajax request.

Related

Failed to load resource: net:: ERR_CONNECTION_REST

I need to get large data from database using Ajax web call.
Upto 20000 records the ajax call working fine, But when the record count is more than 20k it showing the error
"Failed to load resource: net:: ERR_CONNECTION_REST"
in console.
There is no error in DL method.
And here is the ajax call code:
$.ajax({
type: "POST",
url: serviceUrl,
async: false,
data: JSON.stringify(Data);,
contentType: "application/json", // content type sent to server
dataType: "json", //Expected data format from server
processdata: true,
success: function (data) {//On Successfull service call
bSuccess = true;
//Success code here
},
error: function (jqXHR, textStatus, errorThrown) {
//Error code here
}
});
please help me to clear the error.
How large is each record?
My first guess would be the size of the request. What kind of server are you using? If it's hosted in IIS you should check the maxAllowedContentLength in web.config.

Ember.js 2 Calls to .net API

I am building a SPA ember.js app that will hit a .net API via an ajax call.
ember.js
getData: function(){
$.ajax({
type: "POST",
url: "http://localhost:9001/controller",
dataType : "json",
headers: "Access-Control-Allow-Origin",
contentType: 'application/json; charset=utf-8',
success : function(data) {
return data;
},
error:function(data){
alert('test' + data);
}
})
}
It returns an error message : SyntaxError: Failed to execute 'setRequestHeader' on 'XMLHttpRequest': 'function () { return _emberRuntimeSystemString.fmt(this, arguments); }' is not a valid HTTP header field value.
I have been hammering away at this issue for a few hours now and I just can't seem to get around it. Also very new to ember.js.
If anyone has a better idea of whats going on...
Well,
the problem is in your headers. You are not giving "Access-Control-Allow-Origin" a value.
So you want something like
headers: {"Access-Control-Allow-Origin": 'value' }
Also, I don't think that particular header is used that way? I believe it's a header that the server sends.
Check this post out - How does Access-Control-Allow-Origin header work?
Pav

OneDrive Api GET METHOD (No One Can Fix It :S)

$.ajax({
url: 'https://login.live.com/oauth20_authorize.srf?client_id=*********&scope=onedrive.readwrite&response_type=token&redirect_uri=http://localhost:54540/Home/Dashboard',
dataType: "json",
type: "GET",
contentType: 'application/json; charset=utf-8',
async: true,
processData: false,
cache: false,
success: function(data) {
alert(data);
},
error: function(xhr) {
alert('error');
}
});
I am getting the following Error
No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:54540' is therefore not allowed access.
I know its about CORS but i cant find any simple solution.
It looks like you're trying to use ajax to get an auth token from the login server. Since this process may involve requiring the user of your app to log in or consent to giving your app access to their data, you need to navigate to that URL in the browser itself.
Here's more info about using oauth with OneDrive. You should also take a look at the javascript sample app and see how it works in practice.

WebMethod called through Jquery Ajax is doing 301 redirect

I have a webmethod in aspx page and I am calling it through jquery Ajax method.
In one server I am getting windows security prompt on ajax call (all other servers are working fine).
When I was checking using fiddler I see a 301 redirect of my method call(webmethods.aspx/GetDetails to webmethods.aspx/GetDetails/)
Not sure why the redirect is happening on one server and call to webmethod.aspx/GetDetails/ is throwing 401.
I checked all the wildcard mapping etc and not able to find any issues. Any idea where else I need to check?
Here is my code
$.ajax({
type: "POST",
url: "/webmethods.aspx/GetDetails",
data: "",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
//alert('success');
},
failure: function (response) {
alert(response);
},
error: function (jqXHR, textStatus, errorThrown) {
var errMessage = "An error occured serving your request. Please try again.";
if (jqXHR)
errMessage = $.parseJSON(jqXHR.responseText).Message;
alert(errMessage);
}
Can you check the handler order in your web.config? I have had similar issue where staticfile handler was before aspx handler. Changing the order fixed my issue (move the static file as the last element, because most of the time it will have verify whether file exists before handling).

Cross Domain AJAX POST 403 forbidden when attempting to execute a cs WebMethod

Pardon my noobiness in web development terminology.
I am trying to execute the following [WebMethod]:
public static void CreatePendingCaseFromChat(string userInputs)
{
//Do a bunch of stuff here with the userInputs string
}
With the following AJAX (which resides on another server):
$.ajax({ type: "POST",
url: "http://www.MyCoolWebDomain.com/Code/MyCode.aspx/CreatePendingCaseFromChat",
crossDomain: true,
data: JSON.stringify(parameters),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data){alert("success in ajax call")},
error: function (data){alert("error in ajax call")}
});
MyCode.aspx contains the following lines within the Page_Load() method:
Response.AppendHeader("Access-Control-Allow-Origin", "*"); //Allow Cross domain AJAX call, update the "*" to be a specific URL
Response.AppendHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
Response.AppendHeader("Access-Control-Allow-Headers", "content-type, x-requested-with");
If I do the following, instead of the ajax call:
var invocation = new XMLHttpRequest();
var url = "http://www.MyCoolWebDomain.com/Code/MyCode.aspx/CreatePendingCaseFromChat"
if (invocation) {
invocation.open('POST', url, false);
invocation.send();
}
else {
alert("no invocation");
}
Then I can confirm with FireBug that the following Response Headers are set:
Access-Control-Allow-Head... content-type, x-requested-with
Access-Control-Allow-Meth... GET, POST, OPTIONS
Access-Control-Allow-Orig... *
With the AJAX call, none of those headers are shown.
I would like to make this work either way, whether with the AJAX call, or with the XHR call.
For the XHR call I can't figure out how to send the userInputs string to the WebMethod.
For the AJAX call I can't get it passed preflight or w/e it's called (the OPTIONS call).
I've posted a bunch of code on question:
CORS - Ajax error function reports error code as 0 for an API request returning 401
It is using MVC4, but should give you everything you need to get this working.

Categories