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

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.

Related

Copy all text from URL and store in an object

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;

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.

javascript: How to get a XMLHttpRequest representation of the current resource

I want to be able, using javascript, to reload the currently loaded resource, but customising some header variables, before doing so.
This method is needed/should be used in 2 real cases:
As a way, to handle login via real HTTP-login, which means reloading the resource with attached authentication data
To get different media-type representations of the same resource, which means modifying the accept header, before re-sending the request.
As I would need to leave any other header fields unchanged, as the browser would send it natively, I cannot simply construct my own XMLHttpRequest, using the document.URL value. Rather I would need to get hold of a XMLHttpRequest representation of the request, the browser sent for the current resource.
Is there a way to accomplish that in JS? Preferably using pure JS without any jQuery magic.
If it was loaded via GET, you can just create an XMLHttpRequest and use document.location.href as the URL.
The browser will specify the usual cookie headers, so your request headers should be largely the same unless the GET changed cookies in non-idempotent ways.
If the current resource was loaded via POST, then you are out of luck. The POST body of the current resource is not available to JavaScript so unless you would need some other way to get it or infer it from page content.

jQuery.getJSON - Access-Control-Allow-Origin Issue

I'm jusing jQuery's $.getJSON() function to return a short set of JSON data.
I've got the JSON data sitting on a url such as example.com.
I didn't realize it, but as I was accessing that same url, the JSON data couldn't be loaded. I followed through the console and found that XMLHttpRequest couldn't load due to Access-Control-Allow-Origin.
Now, I've read through, a lot of sites that just said to use $.getJSON() and that would be the work around, but obviously it didn't work. Is there something I should change in the headers or in the function?
Help is greatly appreciated.
It's simple, use $.getJSON() function and in your URL just include
callback=?
as a parameter. That will convert the call to JSONP which is necessary to make cross-domain calls. More info: http://api.jquery.com/jQuery.getJSON/
You may well want to use JSON-P instead (see below). First a quick explanation.
The header you've mentioned is from the Cross Origin Resource Sharing standard. Beware that it is not supported by some browsers people actually use, and on other browsers (Microsoft's, sigh) it requires using a special object (XDomainRequest) rather than the standard XMLHttpRequest that jQuery uses. It also requires that you change server-side resources to explicitly allow the other origin (www.xxxx.com).
To get the JSON data you're requesting, you basically have three options:
If possible, you can be maximally-compatible by correcting the location of the files you're loading so they have the same origin as the document you're loading them into. (I assume you must be loading them via Ajax, hence the Same Origin Policy issue showing up.)
Use JSON-P, which isn't subject to the SOP. jQuery has built-in support for it in its ajax call (just set dataType to "jsonp" and jQuery will do all the client-side work). This requires server side changes, but not very big ones; basically whatever you have that's generating the JSON response just looks for a query string parameter called "callback" and wraps the JSON in JavaScript code that would call that function. E.g., if your current JSON response is:
{"weather": "Dreary start but soon brightening into a fine summer day."}
Your script would look for the "callback" query string parameter (let's say that the parameter's value is "jsop123") and wraps that JSON in the syntax for a JavaScript function call:
jsonp123({"weather": "Dreary start but soon brightening into a fine summer day."});
That's it. JSON-P is very broadly compatible (because it works via JavaScript script tags). JSON-P is only for GET, though, not POST (again because it works via script tags).
Use CORS (the mechanism related to the header you quoted). Details in the specification linked above, but basically:
A. The browser will send your server a "preflight" message using the OPTIONS HTTP verb (method). It will contain the various headers it would send with the GET or POST as well as the headers "Origin", "Access-Control-Request-Method" (e.g., GET or POST), and "Access-Control-Request-Headers" (the headers it wants to send).
B. Your PHP decides, based on that information, whether the request is okay and if so responds with the "Access-Control-Allow-Origin", "Access-Control-Allow-Methods", and "Access-Control-Allow-Headers" headers with the values it will allow. You don't send any body (page) with that response.
C. The browser will look at your response and see whether it's allowed to send you the actual GET or POST. If so, it will send that request, again with the "Origin" and various "Access-Control-Request-xyz" headers.
D. Your PHP examines those headers again to make sure they're still okay, and if so responds to the request.
In pseudo-code (I haven't done much PHP, so I'm not trying to do PHP syntax here):
// Find out what the request is asking for
corsOrigin = get_request_header("Origin")
corsMethod = get_request_header("Access-Control-Request-Method")
corsHeaders = get_request_header("Access-Control-Request-Headers")
if corsOrigin is null or "null" {
// Requests from a `file://` path seem to come through without an
// origin or with "null" (literally) as the origin.
// In my case, for testing, I wanted to allow those and so I output
// "*", but you may want to go another way.
corsOrigin = "*"
}
// Decide whether to accept that request with those headers
// If so:
// Respond with headers saying what's allowed (here we're just echoing what they
// asked for, except we may be using "*" [all] instead of the actual origin for
// the "Access-Control-Allow-Origin" one)
set_response_header("Access-Control-Allow-Origin", corsOrigin)
set_response_header("Access-Control-Allow-Methods", corsMethod)
set_response_header("Access-Control-Allow-Headers", corsHeaders)
if the HTTP request method is "OPTIONS" {
// Done, no body in response to OPTIONS
stop
}
// Process the GET or POST here; output the body of the response
Again stressing that this is pseudo-code.

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.

Categories