Javascript:How to get content of a url? - javascript

As we know, we can use the function `file_get_contents(url)` in PHP to get content of a url.
However, can it be avaible in JavaScript?
The `document.ElementById()` is only valid in current page.
Can I use JS to get a div or class in an URL?
Moreover, if these content can be displayed through PopupBubble, I will be more grateful to you.

You can make an HTTP request using XMLHttpRequest subject to the Same Origin Policy which can be bypassed using CORS

Related

Parse image url from JSON api

I am having problems getting an image URL from a Wordpress JSON API and fill in an image tag.
Here's my non-working code:
$(document).ready(function() {
$.getJSON('http://interelgroup.com/api/get_post/?post_id=4683', {format: "json"}, function(data) {
$('#thumb').attr("src", data.post.thumbnail_images.full.url);
});
});
And the HTML is like:
<img id="thumb" src="#">
What am I doing wrong?
Help appreciated.
Thanks!
NOTE: My real case is dynamic (I am getting a dynamic list of post IDs and looping through them with $.each()), but for this case I am providing an example with an hardcoded post ID, so you can check the JSON returned.
Your problem is because you can't do cross request using Javascript, say websiteA.com wants to fetch information from websiteB.com with a plain XMLHttpRequest. That's forbidden by the Access Control.
A resource makes a cross-origin HTTP request when it requests a resource from a different domain than the one which served itself. For example, an HTML page served from http://domain-a.com makes an <img> src request for http://domain-b.com/image.jpg. Many pages on the web today load resources like CSS stylesheets, images and scripts from separate domains.
For security reasons, browsers restrict cross-origin HTTP requests initiated from within scripts. For example, XMLHttpRequest follows the same-origin policy. So, a web application using XMLHttpRequest could only make HTTP requests to its own domain. To improve web applications, developers asked browser vendors to allow XMLHttpRequest to make cross-domain requests.
If you know the owner of the website you're trying to read, what you can do is asking them to add your domain to the whitelist in the page headers. If you do so, then you can do as much as $.getJSON as you want.
Another alternative could be using some sort of backend code to read that website and serve it locally. Say your website is example.com, you could have a PHP script that runs on example.com/retrieve.php where you can query that website, adding the "parameter" you need. After that, since example.com is your own website you can just do a $.getJSON to yourself. There's a simple PHP proxy you can use here with a bit of explanation on why you can do it this way.
A third option would be editing the Javascript code to use Yahoo! YQL service. Although there's no guarantee that'll work forever, you can use it to query the website on your behalf and then use it to print whatever you want to the screen. The downside is that this maybe is not ethically correct if you do not own the website you're trying to fetch (plus, they can add a robots.txt file preventing the access).
Hope that helps.
JSONP solves the problem. Just need to add a callback parameter and specify it is a JSONP, like:
$(document).ready(function() {
$.getJSON('http://interelgroup.com/api/get_post/?post_id=4683&callback=?', {format: "jsonp"}, function(data) {
$('#thumb').attr("src", data.post.thumbnail_images.full.url);
});
});
More info here: Changing getJSON to JSONP
Info on JSONP: https://en.wikipedia.org/wiki/JSONP

Getting the request origin in a Django request

So I'm trying to enable cross origin resource sharing in Django, so I can post to an external site, and it's easy to do when I set
response["Access-Control-Allow-Origin"]="*"
but I want to instead have it check whether the origin is in an allowed list of origins (essentially to restrict it to only allow specific sites) but I can't seem to find anywhere in the Django request where I can get the origin information.
I tried using request.META['HTTP_HOST'] but that just returns the site that's being posted to. Does anyone know where in the Request object I can get the origin of the request?
As for getting the url from request (which is what I was looking for), use request.META['HTTP_REFERER'] instead.
In Django,
request.headers['Origin']
answers the original question.
You can print(request.headers) to see everything available in the headers.
Use this:
origin = request.META.get("HTTP_ORIGIN")
This is the way django-cors-headers use it in the middleware:
you can get it by request.META["HTTP_ORIGIN"]
I strongly advice you to use django-cors-headers. It lets you to define CORS_ORIGIN_WHITELIST which is a list of allowed origins in more pythonic way.
To answer the question "Does anyone know where in the Request object I can get the origin of the request?", would the request.META['REMOTE_ADDR'] give you what you need?
In Django 2.2 use:
request.META.get('HTTP_REFERER')
Make sure that the request property doesn't have mode = no-cors
see:
https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Origin
"There are some exceptions to the above rules; for example, if a cross-origin GET or HEAD request is made in no-cors mode, the Origin header will not be added."

Read a text file from the url using Jquery

I am trying to read a text file from the server using the below code. I am not able to access it but when I just have that text file local then its working fine. Please let me know what to do
$(document).ready(function(){
$.get('http://.../admin/ReleaseNotes/FY13/UpcomingChanges.txt', function(contents) {
$("#contentArea").val(contents);
},'text');
});
You are trying to request a document on a different domain to the one the request is being made from. Same Origin Policy will stop this request completing. There are ways to circumvent this policy though. You can find information in this answer: Ways to circumvent the same-origin policy
You could also try the following tutorial which will show you how to do a cross domain ajax request with YQL and jQuery.
http://net.tutsplus.com/tutorials/javascript-ajax/quick-tip-cross-domain-ajax-request-with-yql-and-jquery/

Understand cross domain stuff and AJAX

I am a bit confused about 2 things related to cross domain stuff.
Say I have 2 domains; mydomain.com and otherdomain.com
Now on mydomain.com, what all are the allowed things that can be accessed from otherdomain.com ?
I mean can we have
<img src="otherdomain.com/xyz.jpg">
Similarly can we directly use otherdomain.com in iframe src ? What all are allowed by default?
What can be done to prevent access from otherdomain.com's perespective ?
2nd part is related to JavaScript/AJAX.
Is otherdomain stuff blocked by default in script related thing ?
Using AJAX, can I by default make a requst to otherdomain.com ? Is it allowed? What can be done to get response from otherdomain.com, if it is not allowed ?
Thanks a lot.
Read Wikipedia.
You cannot read from another domain (unless it allows you to).
You can display or execute content from another domain (eg, using an image, frame, or script tag), but you can't read it directly from your code.
Thus, you cannot send an AJAX request to another domain, and you cannot read the contents of an image, frame, or script tag that was loaded from another domain.
can we have <img src="otherdomain.com/xyz.jpg">
Yes we can have this and any of other resources like images, videos and audio files, zip, pdf ...
can we directly use otherdomain.com in iframe src ?
can I by default make a requst to otherdomain.com ? Is it allowed?
No. For security reasons
What can be done to get response from otherdomain.com, if it is not
allowed ?
if you own the otherdomain.com you can use jsonp and some php stuffs.
http://remysharp.com/2007/10/08/what-is-jsonp/
what all are the allowed things that can be accessed from otherdomain.com? I mean can we have <img src="otherdomain.com/xyz.jpg">
You need to distinguish between "show" and "access". You can include the image, but you cannot access it's data because of the same-origin-policy (SOP).
Similarly can we directly use otherdomain.com in iframe src? What all are allowed by default?
You can include everything that can be linked, from stylesheets, scripts, images to whole pages via frames. Executing scripts from other domains is actually a standard method for getting data, called JSONP; and including resources from third-party-CDNs is common as well.
What can be done to prevent access from otherdomain.com's perespective?
You can use the X-FRAME-OPTIONS-header to prevent inclusion via frames, which should be respected by the most browsers.
You could try to avoid answering requests (sending 404 content) with the wrong REFERER header, but that's not a reliable method since REFERER is often disabled by browsers or blocked by firewalls.
2nd part is related to JavaScript/AJAX. Is otherdomain stuff blocked by default in script related thing ? Using AJAX, can I by default make a requst to otherdomain.com ? Is it allowed?
No, the access to the data is blocked. You can send the request, but the response will not be available to your script unless CORS headers are sent to explicitly allow it.
What can be done to get response from otherdomain.com, if it is not allowed ?
You can use a proxy on mydomain.com.

How can I get HTTP response header using JS?

I tried so many tutorials online but everything I try is really old and fails - I can't even create an XMLHTTPRequest object!
I just want to get the header from google.com - how can I do that?
You would use xhr.getResponseHeader() to get a single header, or xhr.getAllResponseHeaders() to read all of the headers from an XMLHttpRequest response.
The reasons this won't work for you:
XMLHttpRequest is case sensitive. If you are using HTTP in all caps, it will fail.
Unless you are a google employee adding code to google.com, your request falls victim to the same origin policy. You'll have to use your server as a proxy to get headers from a google request.
You cant simply do this by JS. You'll have to use AJAX and do a server request to PHP,ASP, Java or whatever. The XMLHTTPRequest should do it - if you really want to do it manually. But it will really not work with foreign domains, so you are forced to do the XMLHTTTPRequest to a page on your server which will deliver the header.

Categories

Resources