External file fail to load on 'load' function - javascript

I want to load content of external text file (demo.txt) in my div on button click.
Text file containes text 'Demo text.'
But it shows error
XMLHttpRequest cannot load file:///C:/Users/Tom/Desktop/jQuery%20thenewboston/76.)%20Load%20function/demo.txt. Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https, chrome-extension-resource.
on my browser console.
$(document).ready(function(){
$('#button_file').on('click',function(){
$('#load_html').load('demo.txt');
});
});
<button type="button" id="button_file">Load file</button>
<br />
<div id="load_html" >
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
I am a beginner in jquery , please comment below for any query.

You cannot get the result because the remote site doesn't have CORS enabled: If you look at the console, you'll see:
(Reason: CORS header 'Access-Control-Allow-Origin' missing).
You can bypass CORS by using something like anyorigin.com, i.e.:
$.getJSON('http://anyorigin.com/get/?url=http%3A//thenewboston....&callback=?', function(data){
$('#div-data').html(data.contents);
});
PS: If it's a local file, make sure you load it on the same address as the script, (localhost, 127.0.0.1, 192.168.1.1, etc...)

You are being restricted by HTTP access control (CORS). The file you are requesting asynchronously needs to be from the same domain or the domain you are accessing it from needs to allow your domain to access it. As you are using the file:/// protocol you need to allow it, so check out this if that's the way you wish to go.
Alternatively you can create a local web server to host your site an allow access to the file on the same domain.

In order to make this work you need to use a web server instead of using just clicking on the html file.
Check XAMPP

Unfortunately, Google Chrome doesn't allow cross-origin request although Firefox does.
Alternatively, if the text file is short you can store it in an object and place it wherever you like.
text_file = {
contents = 'content';
}
$('.button_class').on('click',function(){
$('.div').html(text_file.contents);
});
I would never suggest you use this but if it's a small project, a one page application that nobody will see the code to - desperate times call for desperate measures.
The best thing to do is to use XAMPP and PHP.
Load in from your database the content you would like to show.
You can read the PHP documentation or watch online tutorials , I personally suggest TheNewBoston PHP Tutorials with Alex Garrett

Related

javascript get html content (page code) from url [duplicate]

I have a page with some D3 javascript on. This page sits within a HTTPS website, but the certificate is self-signed.
When I load the page, my D3 visualisations do not show, and I get the error:
Mixed Content: The page at 'https://integration.jsite.com/data/vis' was loaded over HTTPS, but requested an insecure XMLHttpRequest endpoint 'http://integration.jsite.com/data/rdata.csv'. This request has been blocked; the content must be served over HTTPS.
I did some research and all I found what the JavaScript will make the call with the same protocol that the page was loaded. So if page was loaded via https then the rdata.csv should also have been requested via https, instead it is requested as http.
Is this because the certificate is self-signed on the server? What I can do to fix this, other than installing a real SSL certificate?
What I can do to fix this (other than installing a real SSL certificate).
You can't.
On an https webpage you can only make AJAX request to https webpage (With a certificate trusted by the browser, if you use a self-signed one, it will not work for your visitors)
Steps to Allow Insecure Content in Chrome
To allow insecure content on individual sites within Chrome, click on the lock icon in the URL bar, then click 'Site settings'.
There you will see a list of various permissions the page has. Choose 'Allow' next to 'Insecure content'.
Now your HTTPS site can access HTTP endpoint
I had the same issue for my angular project, then I make it work in Chrome by changing the setting. Go to Chrome setting -->site setting -->Insecure content --> click add button of allow, then add your domain name
[*.]XXXX.biz
Now problem will be solved.
You will be able to solve the error by adding this code to your html file:
<meta http-equiv="Content-Security-Policy" content="upgrade-insecure-requests" />
If any solutions don't work, try this solution.
I solved the problem adding a slash at the end of the requesting url
This way: '/data/180/'
instead of: '/data/180'
As for me, I had same warning.
I fixed it at URL request.
I had excessive '/'.
Before:
const url = ${URL}search/movie/?api_key=${API_KEY}&query=${movie};
After:
const url = ${URL}search/movie?api_key=${API_KEY}&query=${movie};
I had the same problem but from IIS in visual studio, I went to project properties -> Web -> and project url change http to https
One solution here server side end point which you access via https, which then makes the call to whichever http url, and then and returns the result. In other words, making your own little HTTPS proxy to access the http resource
update core_config_data
set value='X-Forwarded-Proto'
where path='web/secure/offloader_header'
this is easy,
if you use .htaccess , check http: for https: ,
if you use codeigniter, check config : url_base -> you url http change for https.....
I solved my problem.

Page loaded over HTTPS but requested an insecure XMLHttpRequest endpoint

I have a page with some D3 javascript on. This page sits within a HTTPS website, but the certificate is self-signed.
When I load the page, my D3 visualisations do not show, and I get the error:
Mixed Content: The page at 'https://integration.jsite.com/data/vis' was loaded over HTTPS, but requested an insecure XMLHttpRequest endpoint 'http://integration.jsite.com/data/rdata.csv'. This request has been blocked; the content must be served over HTTPS.
I did some research and all I found what the JavaScript will make the call with the same protocol that the page was loaded. So if page was loaded via https then the rdata.csv should also have been requested via https, instead it is requested as http.
Is this because the certificate is self-signed on the server? What I can do to fix this, other than installing a real SSL certificate?
What I can do to fix this (other than installing a real SSL certificate).
You can't.
On an https webpage you can only make AJAX request to https webpage (With a certificate trusted by the browser, if you use a self-signed one, it will not work for your visitors)
Steps to Allow Insecure Content in Chrome
To allow insecure content on individual sites within Chrome, click on the lock icon in the URL bar, then click 'Site settings'.
There you will see a list of various permissions the page has. Choose 'Allow' next to 'Insecure content'.
Now your HTTPS site can access HTTP endpoint
I had the same issue for my angular project, then I make it work in Chrome by changing the setting. Go to Chrome setting -->site setting -->Insecure content --> click add button of allow, then add your domain name
[*.]XXXX.biz
Now problem will be solved.
You will be able to solve the error by adding this code to your html file:
<meta http-equiv="Content-Security-Policy" content="upgrade-insecure-requests" />
If any solutions don't work, try this solution.
I solved the problem adding a slash at the end of the requesting url
This way: '/data/180/'
instead of: '/data/180'
As for me, I had same warning.
I fixed it at URL request.
I had excessive '/'.
Before:
const url = ${URL}search/movie/?api_key=${API_KEY}&query=${movie};
After:
const url = ${URL}search/movie?api_key=${API_KEY}&query=${movie};
I had the same problem but from IIS in visual studio, I went to project properties -> Web -> and project url change http to https
One solution here server side end point which you access via https, which then makes the call to whichever http url, and then and returns the result. In other words, making your own little HTTPS proxy to access the http resource
update core_config_data
set value='X-Forwarded-Proto'
where path='web/secure/offloader_header'
this is easy,
if you use .htaccess , check http: for https: ,
if you use codeigniter, check config : url_base -> you url http change for https.....
I solved my problem.

Get a file through AJAX with JQuery

I looked for an answer to my problem everywhere but I didn't found what I want to know.
Here is what I want to do:
I have an url of an image, pdf or html page from the same domain and from other domains too. Is it possible to "download" them with AJAX?
But I don't want to have them physically on my server or anywhere else, I just want to use them directly on my website without having to upload them again (to save time).
I'm also having some troubles doing "XMLHttpRequest.getAllResponseHeaders()" when the content comes from an other domain. I tried with multiples url. I received nothing: "". Is it normal?
Thank you for your help ! :)
Unfortunately it is impossible to make AJAX requests for resources on domains external to the website's host domain, edit: unless they implement a workaround, like CORS or JSONP. I recommend doing some reading on Cross Origin Resource Sharing for more details.
As for resources on the same domain, you'd be storing those on your server anyway - you'd have to, in fact, because by its very nature it would be a part of your site. If you describe what you're trying to implement specifically (perhaps post a jsfiddle with your code), we could find a solution to your specific use case. Hope this helps.
[...] image, pdf or html page [...]
The types of these requests are very different. What you mean with 'download' is a little ambigious. If you're requesting a file via AJAX, this loads the value into a variable. It doesn't save the file to your computer.
[...] I received nothing: "" Is it normal? [...]
Yes, if the remote server isn't the same as you're currently on (also the same port) and also doesn't support CORS (cross-domain requests), the result will be blank.
If it's not possible to alter the remote server's cross-domain policies [and you have the permission to use their services], you could write a PHP script on your server that acts as a proxy. But don't forget to secure it to prevent mis-use. Also keep in mind that such a script can raise your traffic dramatically, so this should only be "Plan B".
You certainly can fetch images and html pages with AJAX and display them on your webpages.
The issues you are having with the xmlHttpRequest.GetAllResponseHeaders is most likely caused by the same origin policy. The browser prohibits you from interacting with the loaded data from another domain.
The server you are fetching the data from has to explicitly indicate that it allows your domain to fetch and display his resources by setting the Access-Control-Allow-Origin response header to that of your domain.
A way arround this is by using a proxy and setting the header yourself.
The following boilerplate code ( basically taken from the jquery api page ) loads your gravatar image ( delivered in png format ) from the stackoverflow website into a callback parameter. As others have noted, the same origin policy applies to ajax requests ( The sample code therefore can onlybe successfully run from the stackoverflow site context, eg. by opening a js console on this page ).
$.ajax({
method: "GET"
, url: "https://www.gravatar.com/avatar/d85e0ad5243245aabe2d34a3c9a296a9?s=32&d=identicon&r=PG&f=1"
, cache: false
, beforeSend: function( xhr ) {
xhr.overrideMimeType( "text/plain; charset=x-user-defined" );
}
})
.done(function( data ) {
if ( console && console.log ) {
console.log( "Length of data:", data.length );
console.log( "Sample of data:", data.slice( 0, 100 ) );
}
});

Jquery load https url

I have this problem. In external web site I have a script like this:
<div id="idtest"></div>
<script src="//example.com/widget.js" type="text/javascript"></script>
example.com is in https (allow both http and https). In the server in the script widget.js I have:
$('#idtest').load("https://example.com/index.html")
I get this error: Mixed Content: The page at 'thepage' was loaded over HTTPS, but requested an insecure XMLHttpRequest endpoint 'http://example.com/index.html'. This request has been blocked; the content must be served over HTTPS.
I don't understand: why the error and why the endpoint is in "http"?
thanks
EDIT
More information:
if in the widget.js I do this:
$('#idtest').load("./index.html")
the content is load and all works perfectly if I load the script in my site.
If I do something like:
x = "https://example.com"
$('#idtest').load(x + "/index.html")
or
$('#idtest').load("https://example.com/index.html")
I get the error (if I put the script in my site or in external site). Why?
EDIT 2
more informations:
my site is in django
EDIT 3
In firefox I load the page in https and http. It doesn't work in Chrome. I see this situation in firefox net analyzer when call the url :
302 https://example.com/index.html
200 http://example.com/index.html [mixed content]
What understand this situation (https to http)? Could be a Django redirect problem?
A mixed content error happens when:
you try to load secure content SSL(https) on a page served insecurely (http) served
Or the opposite
you try to load insecure content (http) on a page served securely SSL(https) served
Your error message is warning that your calling page has been loaded in insecure mode
You haven't explicitly explained this, but your error indicated your page is being served without SSL. When you try to load a protected resource this becomes a mixed mode problem of protected resources and insecure.
If possible, you try to serve the reference file the same way
You can serve your main page in SSL (https)
You can request the partial page in http
$('#idtest').load("http://example.com/index.html")
or
Just as you have resolved it, request the partial page without protocol. Now your loaded file will be loaded using the protocol used by your page.
About your specific resource:
I tried loading:
http://example.com/index.html
and
https://example.com/index.html
The result was the same. I got a simple page with the message:
Example Domain
This domain is established to be used for illustrative examples in documents. You may use this domain in examples without prior coordination or asking for permission.
More information...
I think it is more a problem of cross origin domain.
the $.load function of jquery use ajax to load the url and so you cannot do cross domain call if the target URL does not implement CORS headers.
In your example, the server example.com must return a header
Access-Control-Allow-Origin: *
You can also replace * with the domain of the page that want to load the content by AJAX.
A good blog post on how to use CORS:
http://www.html5rocks.com/en/tutorials/cors/
I had this issue on Ruby on Rails webpage and the the mistake was to use "_url" helper instead of "_path" helper, on a https webpage:
in a view:
wrong: borrar_linea_factura_url(l)
ok: borrar_linea_factura_path(l)
As a recap of said before:
"_url" helper generates /controller/action/params
"_path" helper generates https://controller/action/params

... this content should also be loaded over HTTPS

Good day.
Site https://mult-privet.com/
In my Chrome console, I see this error:
[blocked] The page at 'https://yandex.st/share/ya-share-cnt.html?url=
https%3A%2F%2Fmult-privet.com%2F&services=yaru,
vkontakte,facebook,twitter,odnoklassniki,moimir'
was loaded over HTTPS, but ran insecure content
from 'http://connect.odnoklassniki.ru/dk?st.cmd=extOneClickLike&uid=odklocs0&
ref=https%3A%2F%2Fmult-privet.com%2F':
this content should also be loaded over HTTPS.
Why should this URI also be loaded over HTTPS ?
Why am I getting this error, and how do I remove it?
On the right side of the Chrome address bar, click on the shield icon, then click "Load unsafe script". Done!
Why this content should also be loaded over HTTPS ?
Because:
if you have unsecured content being injected into an otherwise secure page, the unsecured content can be intercepted, replaced and thus render the secure content insecure
the browser can't honestly continue to tell the user that the page is secure when parts of it are not
Tell me please why i get this error
You are loading HTTP without SSL content into an HTTP with SSL page.
and how remove this?
Use HTTPS for everything on the page.
Why you are getting this error
Quentin's answer explains this pretty well. I would clarify that you are getting a mixed content error.
How to fix this error
Although Quentin's answer offers the most ideal fix, it is sometimes more convenient to solve mixed content errors using a protocol-relative URL, where the http[s]?: prefix is removed from the URL. For example, change this:
http://connect.odnoklassniki.ru/dk?st.cmd=extOneClickLike&uid=odklocs0&
ref=https%3A%2F%2Fmult-privet.com%2F
to this:
//connect.odnoklassniki.ru/dk?st.cmd=extOneClickLike&uid=odklocs0&
ref=https%3A%2F%2Fmult-privet.com%2F
by removing the http: prefix. It will let the browser determine the protocol. When using the protocol relative URL in the above example, if you are on an SSL encrypted page the browser will access the https://connect.odnoklassniki... URL, and on a non-SSL page, it will access the http://connect.odnoklassniki... URL, assuming that both protocols work for the URL.
There are, however, some pitfalls in using protocol-relative URLs, like ensuring that the server behind the URL is capable of serving both http and https protocols. This SO post addresses more reasons to use protocol-relative URLs.

Categories