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?
Related
I am making this call:
$.ajax({
type: 'GET',
cache: false,
timeout: 20000,
async: true,
url: "http://search.carrotsearch.com/carrot2-webapp/search",
dataType: 'text',
data: {
query:'london',
results:'100',
source:'etools',
algorithm:'lingo3g',
view:'folders',
skin:'fancy-compact',
type:'DOCUMENTS'
},
success: function(msg) {
debugger;
},
error: function(err,textStatus, errorThrown){
debugger;
}
});
`
Fiddler shows response OK 200 and returns correct gzipped contents. But in browser debugger the error callback is called:
There problem is CORS. http://search.carrotsearch.com/ doesn't allow AJAX requests.
Look for following error in console.
No 'Access-Control-Allow-Origin' header is present on the requested
resource. Origin 'http://localhost:XXX' is therefore not allowed
access.
It can be that my localhost is not listed on http://search.carrotsearch.com/ server. But, I guess in your case too this is the issue.
I am having some trouble getting a few things working. I am trying to connect through basic authentication. I am using javascript in my HTML code. I get the following error message: " Failed to load http://**********/connections?********* : Response for preflight is invalid (redirect)" where I have redacted the API endpoint. The code I wrote is the following.
var Key = "something";
var Secret = "something else";
var url = 'http://**********';
$.ajax({
headers: {
'X-******-Key':Key,
'X-**********Secret':Secret,
'Content-Type':'application/x-www-form-urlencoded'
},
type: "GET",
url: url,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(json) {
alert("Success", json);
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus, errorThrown);
},
beforeSend: function (xhr) {
xhr.setRequestHeader ("Authorization", "Basic " + btoa(Key + ":" + Secret));
},
type: 'GET',
contentType: 'json',
});
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
hi
</html>
You can substitute the API end points and secret and Key to try the code for a common basic authentication API to try the code. I don't have access to the Server. I know it is still possible to make this work because someone else said they have this working. Can anyone help me with this?
Response for preflight is invalid (redirect)
Your server doesn't handle CORS properly.
Browsers won't let fetch data via ajax if the request is made to an external domain unless the server handles CORS properly and CORS headers are available in the responses.
Please read the article:
https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS
I'm having troubles with an AJAX request. I was getting the below error:
Error: Access is denied
I tried this jQuery AJAX request:
$.support.cors = true;
$.ajax({
url: 'http://testwebsite.com/test',
type: "GET",
dataType: 'json',
contentType: 'application/json',
crossDomain: true,
headers: {
'Access-Control-Allow-Methods': 'GET, POST, OPTIONS',
'Access-Control-Allow-Origin': 'http://testwebsite/test',
'Access-Control-Allow-Headers': '*',
'Access-Control-Allow-Credentials': 'true'
},
xhrFields: {
withCredentials: true
},
success: function(data) {
alert("Data from Server" + JSON.stringify(data));
},
error: function(jqXHR, textStatus, errorThrown) {
alert("You can not send Cross Domain AJAX requests: " + errorThrown);
}
});
Can anyone kindly let me know what I am missing. Thanks in advance.
As rory-mccrossan mentioned in a comment, CORS protection is designed so that a website cannot directly access the content of another website (in a browser) unless the website being accessed agrees to it.
It would completely ruin the point of CORS if a site just has to send some headers in order to circumvent the defence
Instead, you will need to use a CORS proxy. It's a server that when given a request like yourCORSproxy.example.com/http://testwebsite/test would load the page and return it, but with CORS allowed (like a normal proxy but with CORS enabled).
One of these CORS proxies is https://crossorigin.me, but at the time of writing this it is down. It might be more stable if you simply create your own proxy.
tl;dr: testsite.test should be sending the headers on its response. You should not be sending the headers on your request.
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.');
}
});
Can anyone point out why my JavaScript function is falling into the error function rather than the success function? Firefox on Ubuntu
$(document).ready(function() {
console.log( "Start" );
$.ajax({ type: "GET", dataType: "html", url: "http://slashdot.org",
error: function(request, status) {
console.log("Error");
},
success: function(data) {
console.log("Sucess");
}
});
console.log( "End" );
});
Because of same-origin security restrictions, you cannot issue ajax calls to domains other than the domain of your current web page.
Possible work-arounds depending upon what your actual problem is:
Build a server proxy on your domain that will fetch the web page from the other site for you so you can send the request to your own domain.
Use an iframe to display the content from another domain.
It is very common issue with Cross Domain Policy. If you are using jQuery Ajax then you can use JSONP to do cross domain query. Document at http://api.jquery.com/jQuery.ajax/
$.ajax({ type: "GET", dataType: "json", url: "https://api.instagram.com/v1/tags/stackoverflow/media/recent?client_id=0324ff3396ef4ab49697505678e734f5&callback=?",
error: function(request, status) {
console.log(request, status);
},
success: function(data) {
console.log(data);
}
});