Copy all text from URL and store in an object - javascript

I need to copy the text from the URL which a JSON file. I need simple javascript, I cannot use AJAX calls because I have same origin policy error.
The link is as follows:
http://webapp.armadealo.com/home.json?within=50&lng=-71.071123&lat=42.3526751
I need all the content in the above link to be stored in a variable, lets say var allText
Thanks

I cannot use AJAX calls because I have same origin policy error.
Then you cannot get the text directly, full stop, via client-side JavaScript (unless the server that's hosted on supports CORS and allows requests from your origin and you're using a CORS-enabled browser). You might be able to do something like using YQL as a proxy, but barring that, you'll need your own server-side proxy.

Try this
var pathname = window.location.pathname;

Related

How do I load a static, plaintext json file into Javascript with a GET request? [duplicate]

This question already has answers here:
Get JSON data from external URL and display it in a div as plain text
(7 answers)
Closed 6 years ago.
This is the one I am testing with, specifically:
static json data
I have run into many cross-site request errors, though I don't see how this should be different than requesting an image that is statically hosted on the same site, which I can easily load into my test html file.
I have tried the following:
$.getJSON('http://anyorigin.com/get?url=maxcandocia.com/static/blog/test_output3.json&callback=?',
function(data){
$('#output').html(data.contents);
});
var network_data
$.getJSON("http://maxcandocia.com/static/blog/test_output3.json",
function(data){
network_data = data.contents;
})
In general, you can't access a resource on another origin (in essence domain-port combination) through JavaScript unless that origin explicitly allows you to through the use of specific headers, specifically the Access-Control-Allow-Origin.
It seems that anyorigin.com, the service that you're using, for some reason fails to redirect correctly; this does not appear to be your fault, but something wrong with the service. I would recommend that you try some other, equivalent service, such as https://crossorigin.me/ (just add https://crossorigin.me/ in front of the URL):
var network_data;
$.getJSON("https://crossorigin.me/https://maxcandocia.com/static/blog/test_output3.json",
function(data){
network_data = data.contents;
})
If you control the server yourself, it would be better to just set up the server to send the Access-Control-Allow-Origin header for your JSON file.
Access-Control-Allow-Origin is not an issue with your code. It means you have an issue with security policies.
If you own maxcandocia.com you need to adjust the headers to allow your origin (where you're running the script). If not, you have no chance here unless they change their policies for you (unlikely.
You would instead be looking for a server-side solution, such as what Frxstrem has suggested. Or if you own the script send back this header with the origins you require:
Access-Control-Allow-Origin: http://yourorigin.com http://maxcandocia.com https://maxcandocia.com
I have an in depth answer here on using json with jquery: https://stackoverflow.com/a/17768384/2376468

JSONP-like cross-origin procedure: use JSON array response

I need to access a page on another domain, which returns as response a JSON array:
[{"name":"value","x":"y"},{"name":"value","x":"y"}]
Due to the cross-origin rule, I can't get this data through an XMLHttpRequest. Apparently I have to use a JSONP-like procedure:
Add script element to the page's body, with the src attribute poiting to the page
The browser does the HTTP request and gets the data
I can not edit the remote page/the response. The remote page is not meant to be accessed that way (so I can't use a JSONP callback parameter).
The remote page also requires the use of a specific cookie.
How can I access the data that has been just retrieved?
That's exactly the case the same origin policy exists for. Any possible solution would mean a security hole. If the data server unable to wrap it in your callback function, you have to proxy this through your own server-side app.

Difference jsonp and simple get request (cross domain)

I have to send (and receive) certain data to a server using JQuery and JSON.
Works so far, but not cross domain, and it has to be cross domain.
I looked how to solve this and found JSONP. As far as I see, using JSONP I have to send the callback and the data using GET (JQuery allows to use "POST" as method, but when I inspect web traffic I see it is sending actually GET and everyting as parameter).
JSONP also requires changes in the server, because they are expecting a POST request with JSON data, and they have to implement something to process the JSONP GET request.
So I'm wondering what's the difference between this and sending the data as key value parameters in GET request?
Is the difference the possibility to use a callback? Or what exactly?
Sorry a bit lost... thanks in advance
JSONP is not a form submission. It is a way of telling the server via a GET request how to generate the content for a script tag. The data returned is a payload of JavaScript (not just JSON!) with a function call to a callback which you (by convention) reference in the GET request.
JSONP works because it is a hack that doesn't use AJAX. It isn't AJAX and you should not confuse it for such because it does not use a XMLHttpRequest at any point to send the data. That is how it gets around the Same Origin Policy.
Depending on the browsers you have to support, you can implement Cross-Origin Resource Sharing headers on the server side which will let you use normal AJAX calls across trusted domains. Most browsers (IE8, Firefox 3.5+, etc.) will support CORS.
Another solution you can use if you don't want to use CORS or JSONP is to write a PHP script or Java servlet that will act as a proxy. That's as simple as opening a new connection from the script, copying all of the incoming parameters from your AJAX code onto the request and then dumping the response back at the end of your script.
I found an answer that worked for me with the cross-domain issue and JSON (not JSONP).
I simply used:
header('Access-Control-Allow-Origin: *');
inside my json file (file.php) and called it like this:
var serviceURL = 'http://your-domain.com/your/json/location.php'
$.getJSON(serviceURL,function (data) {
var entries = data;
//do your stuff here using your entries in json
});
BTW: this is a receiving process, not sending.

Load an external html to string in javascript

Is it possible to load for example google.com to a javascript variable?
var html = "the html of google.com"
Is this possible?
Update:
What about in an air application?
Not unless you send the source from the server.
From javascript, it will violate the Same Origin Policy. You can send the request, and you'll get a response, but the response will be empty.
If it's a page in the same domain you're in, then yes. Otherwise, not without some special URL provided by the target domain that sends you pages based on some form of special request.
You can always have your own server fetch the page and forward it to your client.

Cross-site AJAX requests

I need to make an AJAX request from a website to a REST web service hosted in another domain.
Although this is works just fine in Internet Explorer, other browsers such as Mozilla and Google Chrome impose far stricter security restrictions, which prohibit cross-site AJAX requests.
The problem is that I have no control over the domain nor the web server where the site is hosted. This means that my REST web service must run somewhere else, and I can't put in place any redirection mechanism.
Here is the JavaScript code that makes the asynchronous call:
var serviceUrl = "http://myservicedomain";
var payload = "<myRequest><content>Some content</content></myRequest>";
var request = new XMLHttpRequest();
request.open("POST", serviceUrl, true); // <-- This fails in Mozilla Firefox amongst other browsers
request.setRequestHeader("Content-type", "text/xml");
request.send(payload);
How can I have this work in other browsers beside Internet Explorer?
maybe JSONP can help.
NB youll have to change your messages to use json instead of xml
Edit
Major sites such as flickr and twitter support jsonp with callbacks etc
The post marked as the answer is erroneous: the iframes document is NOT able to access the parent. The same origin policy works both ways.
The fact is that it is not possible in any way to consume a rest based webservice using xmlhttprequest. The only way to load data from a different domain (without any framework) is to use JSONP. Any other solutions demand a serverside proxy located on your own domain, or a client side proxy located on the remote domain and som sort of cross-site communication (like easyXDM) to communicate between the documents.
The fact that this works in IE is a security issue with IE, not a feature.
Unfortunately cross-site scripting is prohibited, and the accepted work around is to proxy the requests through your own domain: do you really have no ability to add or modify server side code?
Furthermore, the secondary workaround - involving the aquisition of data through script tags - is only going to support GET requests, which you might be able to hack with a SOAP service, but not so much with the POST request to a RESTful service you describe.
I'm really not sure an AJAX solution exists, you might be back to a <form> solution.
The not very clear workaround (but works) is using iframe as container for requests to another sites. The problem is, the parent can not access iframe's content, can only navigate iframe's "src" attribut. But the iframe content can access parent's content.
So, if the iframe's content know, they can call some javascript content in parent page or directly access parent's DOM.
EDIT:
Sample:
function ajaxWorkaroung() {
var frm = gewtElementById("myIFrame")
frm.src = "http://some_other_domain"
}
function ajaxCallback(parameter){
// this function will be called from myIFrame's content
}
Make your service domain accept cross origin resource sharing (CORS).
Typical scenario: Most CORS compliant browsers will first send an OPTIONS header, to which, the server should return information about which headers are accepted. If the headers satisfy the service's requirements for the request provided (Allowed Methods being GET and POST, Allowed-Origin *, etc), the browser will then resend the request with the appropriate method (GET, POST, etc.).
Everything this point forward is the same as when you are using IE, or more simply, if you were posting to the same domain.
Caviots: Some service development SDK's (WCF in particular) will attempt to process the request, in which case you need to preprocess the OPTIONS Method to respond to the request and avoid the method being called twice on the server.
In short, the problem lies server-side.
Edit There is one issue with IE 9 and below with CORS, in that it is not fully implemented. Luckily, you can solve this problem by making your calls from server-side code to the service and have it come back through your server (e.g. mypage.aspx?service=blah&method=blahblah&p0=firstParam=something). From here, your server side code should implement a request/response stream model.
Just use a server side proxy on your origin domain. Here is an example: http://jquery-howto.blogspot.com/2009/04/cross-domain-ajax-querying-with-jquery.html
This can also be done using a webserver setup localy that calls curl with the correct arguments and returns the curl output.
app.rb
require 'sinatra'
require 'curb'
set :views,lambda {"views/"+self.name.to_s.downcase.sub("controller","")}
set :haml, :layout => :'../layout', :format => :html5, :escape_html=>true
disable :raise_errors
get '/data/:brand' do
data_link = "https://externalsite.com/#{params[:brand]}"
c = Curl::Easy.perform(data_link)
c.body_str
end
Sending an ajax request to localhost:4567/data/something will return the result from externalsite.com/something.
Another option would be to setup a CNAME record on your own domain to "Mask" the remote domain hostname.

Categories