ajax call to webservice always results in error [duplicate] - javascript

This question already has answers here:
Ways to circumvent the same-origin policy
(8 answers)
Closed 7 years ago.
I'm making the following call to a webservice:
$.ajax({
dataType:'json',
cache:false,
type: "GET",
url: url,
success: function (data) {
alert("success");
},
error: function (xhr, ajaxOptions, thrownError){
alert('Failed to subscribe.');
}
});
The webservice is hit and definitely returns json - I can hit it via the browser and get what I expect. In my site, the error function is always called.
using Fiddler I can see there is a 200 result - the only thing I notice is that in the response fiddler says
Response is encoded and may require decoding before inspection. Click here to transform.
When I click it, the response goes from being a load of random symbols to being my expected json.
Upon Googling this, I see suggestions of adding contentType: "application/json;charset=UTF-8", to my call.
This stops my webservice function from being hit at all.
I tried changing it to POST also, just to see if that was the issue...still doesn't work.
Can anyone point out what I', doing wrong?
EDIT:
I've just noticed I'm getting this in Chrome
Refused to set unsafe header "Accept-Encoding"
XMLHttpRequest cannot load http://localhost:57631/Api/Products/SubscribeEmailMeWhenAvailable/203/wrfw#wrwq.com?_=1447757623275. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:50217' is therefore not allowed access.

This message seems related to gzip compression.
Have you tried this ?
headers: { "Accept-Encoding" : "gzip,deflate,sdch" }
Result :
$.ajax({
headers: { "Accept-Encoding" : "gzip,deflate,sdch" }
contentType: "application/json; charset=utf-8",
dataType:'json',
cache:false,
type: "GET",
url: url,
success: function (data) {
alert("success");
},
error: function (xhr, ajaxOptions, thrownError){
alert('Failed to subscribe.');
}
});

Related

Why is my Ajax Request Containing dataType: "jsonp" erroring? [duplicate]

This question already has answers here:
What are the differences between JSON and JSONP?
(8 answers)
Closed 2 years ago.
I have the following Ajax call:
var baseurl = Office.context.mailbox.restUrl;
var getMessageUrl = baseurl + "/v2.0/me/messages/" + rest_id + "?$select=SingleValueExtendedProperties&$expand=SingleValueExtendedProperties($filter=PropertyId eq 'String 0x007D')";
$.ajax({
url: getMessageUrl,
dataType: "jsonp",
headers: {
"Authorization": "Bearer " + rest_token,
"Accept": "application/json; odata.metadata=none"
},
error: function (xhr, ajaxOptions, thrownError) {
$('.resultsScore').text(xhr.statusText);
}
}).done(function (item) {
However, this always throws an error (the error function is always entered). If I used dataType: "json", it works fine. What am I doing wrong? Why can I not use jsonp in this way?
The error is almost certainly because the response isn't JSONP.
There are several reasons that might be. The service you are calling might simply not support it. In addition, JSONP requests do not support the setting of custom headers, so your Authorization will be missing.

PhoneGap - Sending JSON encoding data error

I am using Phonegap to connect to a server to authenticate a user. The server expects the data to be Json encoded, and I will get the response back from the server.
var serviceURL = "http://appdev/PEPS-CS-Services/";
The serviceURL (APPDEV) is hosted on our network within the office.
var loginData = {
'strUniqueID' : '123',
'UserName' : 'User123',
'Password' : 'Password123'
};
I have checked the login credentials and they are fine. When I try the following:
$.ajax({
type: "POST",
url: serviceURL + "services/AuthenticationServices/authenticateUser",
data: loginData,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data) {
alert(data);
},
failure: function(errMsg) {
alert(errMsg);
}
});
I get the Access-Control-Allow-Origin error in my console.
XMLHttpRequest cannot load http://appdev/PEPS-CS-Services/services/AuthenticationServices/authenticateUser.
No 'Access-Control-Allow-Origin' header is present on the requested resource.
Origin 'http://localhost' is therefore not allowed access.
I had a look around, and I was suggested to use Jsonp as the dataType in the ajax request, which does give me back the response I was looking for. However, it isn't alerted out as it should be, the console shows the url with the parameters used in the loginData variable, as below
Resource interpreted as Script but transferred with MIME type application/xml:
http://appdev/PEPS-CS-Services/services/AuthenticationServices/authenticateUser?callback=jQuery164017807046906091273_1396515434941&strUniqueID=123&UserName=Mark&Password=Password1&_=1396515434963"
When I open the link in a browser i get the correct response, as below
<ns:authenticateUserResponse xmlns:ns="http://services">
<ns:return>SESSION ID HERE</ns:return>
</ns:authenticateUserResponse>
However, I also get the Uncaught SyntaxError: Unexpected token < error below it.
I have tried to change to data: loginData to data: {'data':$.toJSON(loginData)}, but still the same error.
My questions are the following:
Am I sending the data over correctly? Why does the jQuery164017807046906091273_1396515434941 get added to the URL before the parameters?
And why am I getting the Uncaught SyntaxError too?
Is this because the server is sending back the incorrect format of the data? It is currently sending back XML
Any help would be greatly appreciated, thanks
This is a familiar cross context issue, you are not allowed to request resource from another domain with simple ajax call and expect a result.
Instead, use a jsonp call and regiter a callback function to call when return result:
var success = function(data){
/* parse JSON */
data = $.parseJSON(data);
/* show json parsed data */
alert(data);
};
$.ajax({
url: serviceURL + "services/AuthenticationServices/authenticateUser",
dataType: 'jsonp', //use jsonp data type in order to perform cross domain ajax
crossDomain: true,
data: loginData,
success: success,
error: function(errMsg) {
alert(errMsg);
}
});

Cross domain issue with jsonp and HTTPS

I have a web page build through HTML, Javascript and ajax. I need to request resource from another domain. The request is through HTTPS. My website is on HTTP. To address cross domain issue I used Jsonp as the data type. Here is my request method.
$.ajax({
url: 'http://xxx.xxx.xxx.xxx:yyyy/service/sv1',
type: "GET",
contentType: "application/json",
async: false,
crossDomain: true,
data: { 'parm': parmval },
dataType: 'jsonp',
success: function (json) {
alert(json.info);
},
error: function(xhr, statusText, err) {
alert("Error:" + xhr.status);
}
});
Still I am not getting any response! Chrome says Failed type and status pending.
Is there anything wrong in the above code? Did i addressed cross domain issue?

Detect HTTP 301 status code from JavaScript

I need to detect client side if a requested file (with XMLHttpRequest) had a 301 response. The reason of doing this is because I need to request other files related to the file where user has been redirected and not related to the first one requested.
Any way to detect this response status code using JavaScript or JQuery?
Thanks.
jQuery ajax callback function gives out a lot of info
$.ajax({
url: "test.php",
type: "GET",
data: {},
dataType:"json",
success: function(resp, textStatus, xhr) {
//status of request
console.log(xhr.status);
},
complete: function(xhr, textStatus) {
console.log(xhr.status);
}
});
You can use $.ajax with jquery
It has everything you need here : http://api.jquery.com/jQuery.ajax/
If you look at "statusCode" explaination, you will see you can make something for every code

JSON ajax response outputed to screen

Our server is located in europe.
Now and then an american based user reports a problem when he uses the $.getJSON function.
His browser just displays the json response instead of catching it and passing it to javascript.
The ajax call just looks like:
$.getJSON(url, function(json_data){ ... });
Any ideas?
More info:
The the same user has the problem in FF and IE.
I use Ruby On Rails render :json. which response type is application/json.
Try using the $.ajax() method so you can handle errors and debug the success callback.
$.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
data: {},
dataType: "json",
url: url,
success: function(json_data) {
// parse json_data object
},
error: function (xhr, status, error) {
// check for errors
}
});
Aside from that using an XHR viewer like Firebug or Chrome's built-in utility (CTRL+SHIFT+I) can be very helpful.
XHR DOM reference: http://www.w3schools.com/dom/dom_http.asp

Categories