XmlHttpRequest status 0 even when the call to service succeeded - javascript

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.

Related

Getting parse error while fetching text file content in JQuery

I am trying to fetch data from text file which resides on server. I have access of that location and able to see content when I put URL in browser tab.
I am trying to make AJAX call and get file content, but I am getting Error: Uncaught SyntaxError: Unexpected identifier
Code
function logResults(json){
console.log(json);
}
$.ajax({
url: u,
dataType: "jsonp",
jsonpCallback: "logResults"
});
on console,
I tried below code too, but same result,
$.ajax({
type: 'GET',
url: u,
crossDomain: true,
dataType: 'jsonp',
async: false,
headers: {
"Access-Control-Allow-Origin": "*"
},
success: function(succ) {
console.log("Success: ", succ)
},
error: function(err) {
console.log("Error: ", err)
}
});
This code is always going into error block.
You said:
dataType: "jsonp",
But the URL is responding with:
Deployment automatically finished…
Which is not JSONP, it is plain text.
You get the error when it tries to execute the plain text as JSONP.
Don't put wrong information in the dataType field.
async: false,
That's deprecated. Don't use it. It's also pointless since you are using callbacks.
It's also incompatible with JSONP so it is ignored (until you remove the incorrect dataType).
crossDomain: true,
This has no effect unless you are making a:
non-JSONP request
to the same origin
which gets redirected to a different origin
… which is very rare.
headers: {
"Access-Control-Allow-Origin": "*"
},
Access-Control-Allow-Origin is a response header. It doesn't belong the request. Trying to add it to the request will cause extra problems as it will make the request preflighted.
(At least, that would be the case if you hadn't said dataType: 'jsonp' because adding request headers is incompatible with JSONP).
All you need on the client
The only code you need on the client is:
function logResults(result){
console.log(result);
}
$.ajax({
url: u,
success: logResults
});
The server you are requesting the data from will need to use CORS to grant you permission to access it if it is a cross-origin request.
It is because you have added dataType as jsonp, so that it will try to parse the response to JSON and if the response is not a JSON it will throw error.

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.

Trying to make a Cross domain post call in IE9

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.

Ajax request using Javascript

I have to make ajax request for mobile web app, I used the following code
$.ajax({
type: type, //GET or POST or PUT or DELETE verb
url: requestURL, // Location of the service
// contentType: "application/x-www-form-urlencoded", // content type sent to server
dataType: "xml", //Expected data format from server
processData: false, //True or False
success: successCallback, //On Successfull service call
error: serviceFailed// When Service call fails
});
But it failed with error "Error: Access is denied. I am calling .aspx service from javascript
You cannot submit AJAX requests to domains other than the one serving the web page. If it is a sub domain causing the problems, you can use this code to resolve it.
document.domain = location.host.replace(/^.*?([^.]+\.[^.]+)$/g,'$1');

jQuery $.getJSON not working

I am try to get a URL from a one server and using that URL to get contents of another server.
$.ajax({url : 'http://localhost:8080/geturl.jsp?A=1&B=2,C=3',
success : function (data)
{
alert(data);
$.getJSON(data, function (mydata)
{
alert(mydata);
});
},
error : function (data, status, xhr)
{
}
});
I know that we cannot make cross-domain requests in through ajax call, thats why i am using getJSON, i have the following problems
When i simply pass the data to the url part of getJSON (as shown in the code), the alert-box show the correct URL but no get request is being performed ( get requests were monitored from FireBug).
When a hard-code the data to be "http://www.google.com" then the get request is being performed but the no response comes, although the response headers comes and response code is 200 (but it was marked as RED in the Firebug (Dont know why :( )
When I tries to fetch a webpage host in localhost domain, then it is fetched correctly although the response was not JSON.
I have the following doubts
If the getJSON function accecpts only JSON objects as reponse then why no error came when perform above 3.
Whats the correct code to perform my the required functionality.
Suggestions to what happened in each case
Thanks in advance for the answers :)
The getJSON function can only be used across domains to fetch JSONP.
It does not magically evade any security restrictions.
http://api.jquery.com/jQuery.ajax/
This should be a working example for jsonp:
var request = jQuery.ajax(
{
url: "http://Your url",
success: function (data) { console.log('success!'); console.log(data); },
error: function (data) { console.log('error!'); console.log(data); },
dataType: "jsonp",
type: "GET",
data: { key: 'value' }
});

Categories

Resources