Trying to make a Cross domain post call in IE9 - javascript

I am trying to make a cross domain post call in IE9 below is my code:
$.support.cors = true;
var data = {"userid":uid,"email":email,"password":password};
if (isIE () && isIE () <= 9) {
$.ajax({
type: 'post',
crossDomain: true,
url: postUrl,
cache:false,
contentType: 'application/json; charset=utf-8',
dataType: 'jsonp',
data:data,
jsoncallback:'localJsonpCallback',
jsonp:false,
success: function (data) {
console.log(data);
},
error: function (status){
console.log(status);
$("#error").html("Incorrect E-mail Entered. Please Re-Enter Your E-mail ");
}
});
}
function localJsonpCallback(json) {
if (!json.Error) {
alert("success");
}
else {
alert(json.Message);
}
}
However, When I look at the call in fiddler I am getting a 405 error and the request header is showing a GET:
GET postUrl?format=json&userid=123456&email=test%40test.com&password=Password1&_=1434232587917 HTTP/1.1
Why is it if I am making a post that in the request header it is showing a Get? Am I doing anything syntactically wrong with my call?

Your request looks okay and from the server response you're describing, it's a "problem" with server, HTTP status code 405 means bad method, i.e. server doesn't allow POST requests. But it's still strange that it would translate those to GET, but I still think it's because of server implementation, not an error on your side. You could try with a tool like curl and see what response headers you get, but it won't help much if it's an server bug/error.
If you do not have control over the server, the only things remaining is to contact the owner and ask them to allow post request or send a GET request, although it's really bad to send non-encoded login data.

Related

JSONP ajax call executes error method its response is 200 ok

Here is my api calling its response is 200 OK but it not entered into the success method I have no clue where i am doing wrong. I enable CORS on server side.
$( document ).ready(function() {
$.ajax({
url: 'https://localhost:44300/api/apim/{{Product.Id}}/'+email+'/',
dataType: 'jsonp',
success: function(data) {
alert("success");
if(data===true){
$('#subscribe').prop('disabled', true);
$('#subscribe').text('Is Pending');
}
else
{
}
},
error: function(err)
{
alert("Error");
},
type: 'GET'
});
});
Image
You said dataType: 'jsonp', but the server said content-type: application/json.
JSONP is application/javascript because it isn't JSON (it's a hack to get around the same origin policy from before we had CORS, since you are using CORS, it is pointless … well, you claim you are using CORS, but I don't see an Access-Control-Allow-Origin header in the response).
Remove dataType: 'jsonp' and let jQuery work out the type of data from the content-type response header.

Response for preflight has invalid HTTP status code 400

I'm trying to make a REST call (POST) using AJAX. This is my AJAX code
<script>
var settings = {
"async": true,
"crossDomain": true,
"dataType": "json",
"url": "http://localhost:port/service/myservice",
"method": "POST",
"data": '{jsondata}',
"headers": {
"accept": "application/json",
"Authorization": "authValue"
}
}
$.ajax(settings)
.done(function (response) {
console.log(response);
});
</script>
Initially I got this error: XMLHttpRequest cannot load http://localhost:port/service/myservice. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access. The response had HTTP status code 400.
To resolve this issue I added the following code in my dropwizard application
Dynamic filter = env.servlets().addFilter("CORS", CrossOriginFilter.class);
filter.setInitParameter(CrossOriginFilter.ALLOWED_METHODS_PARAM, "GET,PUT,POST,DELETE,OPTIONS");
filter.setInitParameter(CrossOriginFilter.ALLOWED_ORIGINS_PARAM, "*");
filter.setInitParameter(CrossOriginFilter.ACCESS_CONTROL_ALLOW_ORIGIN_HEADER, "*");
filter.setInitParameter("allowedHeaders", "Content-Type,Authorization,X-Requested-With,Content-Length,Accept,Origin");
filter.setInitParameter("allowCredentials", "true");
filter.addMappingForUrlPatterns(EnumSet.allOf(DispatcherType.class), true, "/*");
After adding this my initial exception went away, but I'm getting the following exception: XMLHttpRequest cannot load http://localhost:port/service/myservice. Response for preflight has invalid HTTP status code 400
Is this issue related to CORS? What am I doing wrong here?
UPDATE
After doing more debugging I found this behavior. When sending the request without the Authorization header I'm getting 415 (Unsupported Media Type) error.
I think something wrong with my AJAX code, can someone please help me find the issue? Thanks.
You may try here mentioned as complete answer in this thread.
$.ajax({
type:"POST",
beforeSend: function (request)
{
request.setRequestHeader("Authority", authValue);
},
url: "http://localhost:port/service/myservice",
data: "json=" + escape(JSON.stringify(createRequestObject)),
processData: false,
success: function(msg) {
$("#results").append("The result =" + StringifyPretty(msg));
}
});
try to add the following to your settings?
xhrFields: { withCredentials: true }
if you need to pass JSON data in the AJAX call, you need to specify content-type as json/application, so the server knows you are trying to send JSON data. But that will change the default content-type of the call and the call will qualify for pre-flight checking, which need proper CORS enabled client & server request.
For easier use case, do not use JSON.stringify() when you pass data, just make a simple string with {key:value, key:value, ...} format, and pass the string as the data. The Ajax call serializes the data by default and does the right thing, and the call stays as a single POST call to the server, where as the pre-flight mode is two calls.

How to get a json response from yaler

I create an account with yaler, to comunicate with my arduino yun. It works fine, and i'm able to switch on and off my leds.
Then i created a web page, with a button that calls an ajax function with GET method to yaler (yaler web server accept REST style on the URL)
$.ajax({
url: "http://RELAY_DOMAIN.try.yaler.net/arduino/digital/13/1",
dataType: "json",
success: function(msg){
var jsonStr = msg;
},
error: function(err){
alert(err.responseText);
}
});
This code seem to work fine, infact the led switches off and on, but i expect a json response in success function (msg) like this:
{
"command":"digital",
"pin":13,
"value":1,
"action":"write"
}
But i get an error (error function). I also tried to alert the err.responseText, but it is undefined....
How could i solve the issue? Any suggestions???
Thanks in advance....
If the Web page containing the above Ajax request is served from a different origin, you'll have to work around the same origin policy of your Web browser.
There are two ways to do this (based on http://forum.arduino.cc/index.php?topic=304804):
CORS, i.e. adding the header Access-Control-Allow-Origin: * to the Yun Web service
JSONP, i.e. getting the Yun to serve an additional JS function if requested by the Ajax call with a query parameter ?callback=?
CORS can probably be configured in the OpenWRT part of the Yun, while JSONP could be added to the Brige.ino code (which you seem to be using).
I had the same problem. I used JSONP to solve it. JSONP is JSON with padding. Basically means you send the JSON data with a sort of wrapper.
Instead of just the data you have to send a Java Script function and this is allowed by the internet.
So instead of your response being :
{"command":"digital","pin":13,"value":0,"action":"write"}
It should be:
showResult({command:"analog",pin:13,value:0,action:"write"});
I changed the yunYaler.ino to do this.
So for the html :
var url = 'http://try.yaler.net/realy-domain/analog/13/210';
$.ajax({
type: 'GET',
url: url,
async: false,
jsonpCallback: 'showResult',
contentType: "application/json",
dataType: 'jsonp',
success: function(json) {
console.dir(json.action);
},
error: function(e) {
console.log(e.message);
}
});
};
function showResult(show)
{
var str = "command = "+show.command;// you can do the others the same way.
alert (str);
}
My JSON is wrapped with a showResult() so its made JSONP and its the function I called in the callback.
Hope this helps. If CORS worked for you. Could you please put up how it worked here.

XmlHttpRequest status 0 even when the call to service succeeded

I call to Wcf Service via Jquery(JS), after a long time of trying it works.
The call to service is as follows:
function CallService() {
var request = { userName: "aaa", password: "123" };
var jsondata = JSON.stringify(request);
$.ajax({
type: "POST", //GET or POST or PUT or DELETE verb
url: "http://localhost:xxxx/Service1.svc/GetUser", // Location of the service
data: jsondata, //Data sent to server
contentType: "application/json; charset=utf-8", // content type sent to server
dataType: "json", //Expected data format from server
processdata: true, //True or False
crossDomain: true, //True or False
success: function (result) {
alert('success');
},
complete: function () {
alert('completed');
},
error: function (xhr, status, message) {
alert('error with status - ' + xhr.status);
}
});
}
I put BreakPoint in GetUser function that is in service and when I call the function CallService I go to the BreakPoint of Service (which means it works!).
Service function works great and returns the correct data, but to Jquery I get the Error function with status 0.
In addition, in the console I see a red error:(Not generally understood as an error)
POST http://localhost:xxx/Service1.svc/GetUser
What could be the problem?
It could be that you're making a cross-domain request. Note that the same host name with different ports are considered different domain. For example: http://localhost:20 and http://localhost:40 are considered different domains.
In your case, it could be that your browser supports CORS and therefore requests to a different domain are still sent. That's why when you debug on server side you see it works, but when the browser receives response from the server, the response is discarded and an error is raised because of missing Access-Control-Allow-Origin header from the response or having the Access-Control-Allow-Origin header but with a value different than your domain.
My problem was that in User object I had DateTime.
When I turned it to String it worked.

Ajax call fires error event but returns 200 ok

$.ajax({
url: 'http://intern-dev01:50231/api/language',
type: 'GET',
dataType: 'json',
success: function() {
console.log('It Works!');
},
error: function (request,status, error) {
console.log(error);
alert(status);
}
});
Why do this ajax call not work ?? if i call in browser it works fine :/.
This is what fiddler returns:
HTTP/1.1 200 OK
Content-Length: 122
Content-Type: application/json; charset=utf-8
Server: Microsoft-HTTPAPI/2.0
Date: Fri, 26 Apr 2013 06:56:40 GMT
[{"LanguageId":1,"LanguageName":"Dansk"},{"LanguageId":2,"LanguageName":"Tysk"},{"LanguageId":3,"LanguageName":"Engelsk"}]
You have to check ajax response if it is valid or not. When you specify in ajax:
dataType: 'json',
jQuery will fire the error event if the response cannot be parsed as JSON, even if server returns 200 OK. Check the data returned from the server and make sure it is valid JSON (try JSONLint service).
If the returned data is not JSON or it has syntax errors then fix them in your server side code. You can just return {} from the server side script.
Also try this.
$.ajax({
url: 'http://intern-dev01:50231/api/language',
type: 'GET',
cache: false,
complete: function (xhr, status) {
if (status === 'error' || !xhr.responseText) {
console.log(error);
alert(status);
}
else {
console.log('It Works!');.
}
}
});
There is a parsing error since the status shows 200 OK. The problem lies in the datatype:json. To test this, remove the line and it should work. In order to fix this, you can change it to the datatype:text. See this link too for similar question
Check the url parameter and make sure its the same as the loaded page. You might be doing a cross-domain ajax call. If you were wanting to make a cross-domain ajax call, notice that the only dataTypes allowed to make cross-domain requests are "script" and "jsonp".
Ran into this issue in a dev environment where the URL was an IP address and the page loaded a domain-name pointing to that ip.
I know I'm a little late, but I just ran into the same problem and this is one of the top search results on Google. I managed to fix it by moving datatype above url like this:
$.ajax({
type: 'GET',
dataType: 'json',
url: 'http://intern-dev01:50231/api/language',
success: function() {
console.log('It Works!');
},
error: function (request,status, error) {
console.log(error);
alert(status);
}
});
If you are testing locally with a different web app and web API applications , then debug your application and test API send data correctly and app calls to API via AJAX and return data.
since domains are not similar when run application AJAX call doesn't hit to success function. because browser prevents Cross Site request. If you publish both app in local and debug , it's work fine.
hope this would be helpful someone.

Categories

Resources