Cross Domain http get requests [duplicate] - javascript

This question already has answers here:
Ways to circumvent the same-origin policy
(8 answers)
Closed 9 years ago.
I need to make a cross domain ajax call to a server I own but the problem is that the request must come from the client not the server so proxies wont work for me. Our server will be behind a vpn so it won't be able to reach the internet but the client will be able to so we wanted to do a call home from the client to our metrics server to validate a product key.
My remote domain has a php script that simply writes either a 0, 1, or 2. I need my javascript to read this value in and react to it.
I want to do something simple like this but clearly it won't work. Any suggestions?
$.ajax({
url: callHomeUrl,
type: 'GET',
success: function(res) {
document.write($(res.responseText).text());
}
});

You can use a JSONP style implementation for that to get access to your server which works across all browser without CORS!
Example -
var script=document.createElement('script'):
script.type='text/javascript'; script.src='path/to/the/file';
document.getElementsByTagName('head')[0].appendChild(script);
Note that the file in the server should output the javascript function along with any relevant data.

Related

Get CSV via Ajax avoiding CORS [duplicate]

This question already has answers here:
Ways to circumvent the same-origin policy
(8 answers)
Closed 6 years ago.
I have a page that uses a ZingChart and loads the data via Ajax from multiple URLs in other domains. The data are in CSV files such as:
1, 2, 3, 4, 5
Or:
2.34,1.01,4.56
What I need is to access these files and construct a JSON for ZingChart in this way:
{"data":[THE_CSV_GOES_HERE], "name":"WHATEVER"}
My first problem is that I ran into the usual CORS problem (whose usefulness I still don't understand very well), and since I don't have control on the servers hosting the CSVs, I used this workaround as explained here:
$.ajax({
url:"http://otherdomain/test.csv", // This is dynamically placed
dataType: 'jsonp',
success:function(res){
return res;
},
error:function(r, error){
alert("Error " + error);
}
});
This raises a parsererror, I suppose because the CSV is not in json format.
If I use "text" instead of "jsonp" I get the CROS error (No 'Access-Control-Allow-Origin' header is present on the requested resource.) If I use "jsonp text" as in the documentation, I still get the parsererror. If I use crossDomain: true, dataType: 'text' to force a crossDomain but specifying it is text, I still get the CORS error.
It seems that I am having a similar problem as this person.
How can I overcome this? I cannot believe that in the modern Web it is not possible to get a string of text from a distributed server without refreshing the page. It looks like a strong limitation. In fact, I would think it is the client who should be able to allow cross domains, not the external servers (which are normally outside the client's control).
You could try getting the csv file with a server side request as outlined here and then just make your ajax call to your server side web method to get the csv string.
What are you using for the backend/hosting environment for your site? You could simply access the CSVs and return them from your backend as you shouldn't have this problem accessing them from the server side...

No 'Access-Control-Allow-Origin' header is present on the requested resource error when cross domain set to true [duplicate]

This question already has answers here:
How does the 'Access-Control-Allow-Origin' header work?
(19 answers)
Closed 6 years ago.
Im attempting to make an AJAX request using this url http://api.adorable.io/avatars/285/sd I've set crossDomain to true but still the request fails each time with this error.
No 'Access-Control-Allow-Origin' header is present on the requested resource.
It's not possible to make the request using http://www.api.adorable.io/avatars/285/sd. What am I dong wrong here? Please help
$(document).ready(function(){
$.ajax({
url: "http://api.adorable.io/avatars/285/sd",
type: "GET",
crossDomain: true, // enable this
success: function (data) {
console.log(data);
}
});
});
It's not enough to set it in your Ajax call, the file you're calling (http://api.adorable.io/avatars/285/sd) needs the header to allow cross domain calling.
header('Access-Control-Allow-Origin: *');
Would be the code to add for PHP to allow all origins. Change the * to your domain if you only want to allow a specific domain.
Since you don't have control over that URL, you need a good workaround. What you can do is create a PHP file locally that you control that uses cURL to get the resource you're calling from adorable.io through their API, and use your Ajax request to call that local PHP script. Then you don't need to worry about cross domain issues in the Ajax, and everything will work. Adds a small amount of overhead to the process, but is an easy workaround.

Ajax post not working to external domain [duplicate]

This question already has answers here:
$.ajax call working fine in IE8 and Doesn't work in firefox and chrome browsers
(3 answers)
Closed 9 years ago.
Maybe I'm the Nth user that ask this question, but I can't figure it out.
The data string of the ajax call seems to be empty or what? Either I don't get any feedback on the succes or error function.
$.ajax({
type:'POST',
url:'http://www.example.com/test.php',
data:'lid=test',
succes: function(data){
console.log(data);
},
error:function(data){
console.log(data);
}
});
I hope someone can help me out with it?
Kind regards,
Frank
There's no succes function. You probably mean success.
This is because of the Same origin policy. you cannot use ajax to call external sites. if you really want to use, you have to use JSONP. Or you can use serverside proxy for this. means, call external site in the server side and do ajax call to the that webservice.
for more information please refer this link and this answer
https://stackoverflow.com/a/8698786/880434
Try this
$.ajax({
type:'POST',
url:'http://www.example.com/test.php',
crossDomain: true,
data:'lid=test',
success: function(data){
console.log(data);
},
error:function(data){
console.log(data);
}
});
AJAX requests are generally limited to same domain. Here is some information I found on another Stack Overflow Answer, Using Access-Control-Allow-Origin header
Alternatively, if your response is of the right format, you could try a JSONP request
You're being blocked by the browser "Same origin policy". That is, you cannot do ajax requests to other than the same domain that the script was loaded from. There are, however, some workarounds:
Use JSONP. This is probably the most cross browser compatible solution
Configure your application to support CORS. This works in most modern browsers, but not in some older.
Create a proxy service on your own server. That is, mount an endpoint, e.g. /externalService that proxies the request on the server side to the remote endpoint. It also will work in all browsers, but will involve more work on the server side.
The server www.example.com should have the cross-domain.xml which will contain the domain names allowed to request and get response. So add your domain from which the request is coming or just add the doamin name as '*' to accept all doamins

XMLHttpRequest not containing web page even though web page was received successfully [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Ways to circumvent the same-origin policy
I am making a personal web page that extracts the lottery powerball numbers and displays them. I have had success for all but this one link:
var xmlHttp = null;
xmlHttp = new XMLHttpRequest();
xmlHttp.open( "get", "http://www.powerball.com/powerball/pb_numbers.asp", false );
xmlHttp.send(null);
document.body.innerHTML = xmlHttp.responseText;
I checked the xmlHTTP.status and it is 0. However, using Live HTTP headers app I see that the request is sent and I do get a successful HTTP/1.0 200 OK where the page was received on my end. But, there is nothing received in the xmlHTTP object. No responseText, just status 0 for get not initialized.
EDIT: I do not see a Access-Control-Allow-Origin: directive in the return header. Why is this if I am being restricted because I am from a different domain?
You can't use XHR to read data from different origins. Since the request is made as the user of the browser, it is done with everything that might authenticate the user so might retrieve confidential information (which you could then use XHR to copy to your own server).
See this stackoverflow question for work arounds.
I'm not sure how it works nor it's capabilties but you seem to have an answer above on why it doesn't work. I recommend you to use ajax instead, it's simple and works just great.
Here's an example where I use it:
var site = $.ajax({
url: "http://google.com",
type: "GET",
dataType: "html",
async: false
}).responseText;
document.body.innerHTML = site;
Good luck,
Your problem here is the same origin policy. You won't be able to get any data from that website using AJAX unless that website provides a JSONP API (and even then it's not technically AJAX).
You can achieve what you are doing to some extent with an iframe but you will have to include the entire page and not just the relevant part of it.
If what you need to do is Web scraping then you will have some server-side proxy to do it.
Some tools that might help you:
YQL
Yahoo Pipes
Notable Web scraping tools on Wikipedia
Alternative to cross domain ajax is:
write proxy which will request the remote server using CURL
call that proxy file from ajax call

How to POST data to an HTTP page from an HTTPS page

I know this is a long shot, but I figured I'd ask the question anyway.
I have an HTTPS page and am dynamically creating a form. I want to POST the form to an HTTP page. Is this possible without the browser popping up a warning? When I do this on IE8, I get the following message:
Do you want to view only the webpage content that was delivered securely?
Essentially, I'm asking about the inverse of question 1554237.
Sadly, I know of absolutely no way to not get warned when posting from HTTPS to HTTP. If you serve the form securely, the browser expects to submit the data securely as well. It would surprise the user if anything else was possible.
Nope, can't be done. Our good friend IE will always pop up that warning.
There is a way to do this if you write a back-end service of your own. So lets say you want to post an HTTP request to s1 using your front-end service fs1.
If you use Spring, you can use an ajax call from fs1 to a 'uri' that is recognized by your spring back-end, say bs1. Now, the service bs1 can make the call to the s1.
Pictorial representation here: http://i.stack.imgur.com/2lTxL.png
code:
$.ajax
({
type: "POST",
uri:/json/<methodName>
data: $('#Form').serialize(),
success: function(response)
{
//handle success here
},
error: function (errorResponse)
{
//handle failure here
}
})
You can solve this by either acting as a proxy for the form destination yourself (i.e. let the form submit to your server which in turn fires a normal HTTP request and returns the response), or to let access the page with the form by HTTP only.
If you don't need to actually redirect to the insecure page, you can provide a web service (authenticated) that fires off the request for you and returns the data.
For example:
From the authenticated page, you call doInsecure.action which you create as a web service over https. doInsecure.action then makes a manual POST request to the insecure page and outputs the response data.
You should be able to do this with the opensource project Forge, but it sounds like overkill. The Forge project provides a JavaScript interface (and XmlHttpRequest wrapper) that can do cross-domain requests. The underlying implementation uses Flash to enable cross-domain (including http <=> https) communication.
http://github.com/digitalbazaar/forge/blob/master/README
So you would load the Forge JavaScript and swf from your server over https and then do a Forge-based XmlHttpRequest over http to do the POST. This would save you from having to do any proxy work on the server, but again, it may be more work than just supporting the POST over https. Also, the assumption here is that there's nothing confidential in the form that is being posted.

Categories

Resources