why my JS can't load document from another server? - javascript

I have two web-sites and two files:
provider.com/provide.js
viewer.com/index.html
viewer.com/index.html renders information to the user, and gets this information from provider.com. The file viewer.com/index.html looks like this (jQuery is used):
<script type="text/javascript"
src="http://provider.com/provide.js"></script>
<script type="text/javascript">
provide(function() { alert('works!'); });
</script>
provider.com/provide.js looks like this (I omit unnecessary details):
function provide(callback)
{
$.ajax(
{
'url': 'http://provider.com/',
}
);
}
I'm getting this message in all browsers: Failed to load resource: cancelled.
I have a feeling that I break some security restrictions. Could anyone explain what restrictions, if any. Thanks.

Eventhough the provide.js file is loaded from the provider domtain, it's still loaded in the context of the HTML page, so it's in the viewer domain. When the code tries to make the AJAX call to get information from the provider domain, you run into the cross domain limitation.
You can't use AJAX to load information across domains. However you can use JSONP as data format, then the ajax method will not do an AJAX call, instead it will use a script tag to load the information, which is allowed.

You can't request Javascript to send requests cross domain, for security reasons.
You can however make the request to the server which can retrieve the files and print the results for you, that Javascript can then request.

A brief introduction to the same-origin policy, described in other answers, can be found here:
http://en.wikipedia.org/wiki/Same_origin_policy

Related

External file fail to load on 'load' function

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

External HTML retrieval

I am trying to get the contents of http://en.wikipedia.org through an ajax call. For this, I am using jQuery. Here is the code:
jQuery.ajax({
url:"http://en.wikipedia.org",
crossDomain: true,
dataType: "jsonp",
jsonpCallback: "myCallback"
});
function myCallBack(data){
console.log("ok");
}
The problem is that I get in Firebug this error:
SyntaxError: syntax error
<!DOCTYPE html>
So I would say that the html content is fetched, although the callback function is not run. At some point it encounters the specified tag, throws this error and stops running the script.
Do you have any idea where the problem might lie?
Is there any other way to get the contents of a html page? I do not want to use iframes, because that means I will not be able to use or modify its contents.
Its because you're Ajax function expects a json response from the provided url and it gives an html response, thats the reason you are getting a syntax error, the same error you will get from the Chrome debugger as well.
Updated:
What you're trying to do is called a Cross-Domain Request.
"For security reasons scripts aren't able to access content from other domains. Mozilla has a long article about HTTP access control, but the bottom line is that without the website themselves adding support for cross-domain requests, you're screwed."
Reference
Solution:
You can resolve this issue by having a backend script which will the external pages for you. Like a proxy server, which resides the same domain, so you wont have to face the Cross domain issues.
And you can load them, by
$.get(url, success: function(data) { // the url that will fetch the external html page for you, located on the same domain
console.log("ok");
});
Your issue your having here is that you are calling across domains. Allthough you seem to have realised this and are using jsonp for your request, the document you are trying to pull ie wikepedia is not a jsonp document. So as soon as the ajax finds the html tags it will throw an arror, as you have defined that you are expecting a jsonp response.
You cannot just pull other websites data across domain with javascript due to the cross domain issues, if you want to accomplish what you are doing here you will need to use a back end language to get the data.
Usefull link is http://json-p.org/
Hope that helps

Parse Google Latitude JSON in Javascript (without PHP)

I'm no developer but am pretty good at copy/paste.
I'm trying to parse the Google Latitude JSON (https://latitude.google.com/latitude/apps/badge/api?user=xxxxxxxxxxxxxxxxx&type=json) in a webpage (JavaScript). Is that possible without PHP? and if so, could you show me some example code?
I've been looking but all the examples I found use PHP.
I used the following code:
<!DOCTYPE html>
<html>
<body>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(function() {
// script goes here
$.getJSON('https://latitude.google.com/latitude/apps/badge/api?&user=xxxxxxxxxxxxxxxxxxx', function(data) {
alert(data.type);
});
});
</script>
</body>
</html>
This code I have tried gave an error:
3 requests ❘ 21.38KB transferred ❘ 470ms (onload: 448ms, DOMContentLoaded: 448ms)
104ms157ms209ms261ms313ms366ms418ms470ms
OPTIONS https://latitude.google.com/latitude/apps/badge/api?&user=xxxxxxxxxxxxxxxx 405 (Method Not Allowed) jquery.min.js:19
o.extend.ajax jquery.min.js:19
o.extend.get jquery.min.js:19
o.extend.getJSON jquery.min.js:19
(anonymous function) json.html:12
o.extend.ready.o.readyList jquery.min.js:19
o.extend.each jquery.min.js:12
o.extend.ready jquery.min.js:19
(anonymous function) jquery.min.js:19
XMLHttpRequest cannot load https://latitude.google.com/latitude/apps/badge/api?&user=xxxxxxxxxxxxxxxxxxxxxx. Origin h ttp://dl.dropbox.com is not allowed by Access-Control-Allow-Origin.
In order to make a cross-domain AJAX request, you need to use either CORS or JSONP. This is something the server must support. It doesn't seem that Google Latitude supports this, so you need to use a server-side language (such as PHP) to get the data.
EDIT: If you don't want to use PHP, and you only want to use JavaScript, you can use Yahoo's YQL (you might need an API key).
var googleURL = 'https://latitude.google.com/latitude/apps/badge/api?user=xxxxxxxxxxxxxxxxx&type=json';
$.getJSON('http://query.yahooapis.com/v1/public/yql?callback=?', {
q: 'select * from json where url="'+googleURL+'"',
format: 'json'
}, function(data) {
if(data.query.count){
var gData = data.query.results.json;
alert(gData.type);
}
});
You don't need to parse the JSON, $.getJSON will do that for you, and give you back a JavaScript object. Your error is unrelated to the JSON itself - you're attempting to do a cross-site request which is being prevented by browser security policies. I'd suggest reading up on JSONP
http://json-p.org/
Cheers
Seems like you are using wrong url.
Remove "&" before "user", and add "type" parameter: https://latitude.google.com/latitude/apps/badge/api?user=xxxxxxxxxxxxxxxxxxx&type=json
Plese note that user id can start with "-" sign.
Also, seems like you tried to use dropbox as the hosting, thats prevent you to make ajax request. Try to load your html page from your local drive or from regular web server.
You have a Cross-site request.
See this last line of error: XMLHttpRequest cannot load https://latitude.google.com/latitude/apps/badge/api?&user=xxxxxxxxxxxxxxxxxxxxxx. Origin h ttp://dl.dropbox.com is not allowed by Access-Control-Allow-Origin?
Your original script is hosted at one server, say your server. It can only ask for data from that same domain. Even if you use different ports (http/https), it will not work.
You could possibly make it work with this.
Another possible solution would be to create a php script or similar on your server that will fetch the data from YAHOO and just dump the output in the result.
Then your jQuery ajax call would call your own script (on your server, hence no Cross-Site
HTTP request is happening) and it would work this way. Not a good architecture, I suppose, especially if you expect alot of load, but it would work.

Jquery not working for external domains

I have a function in Jquery, that try get html from an page:
$.ajax({
type:'GET',
url: 'http://www.google.com',
success: function( data ) {
alert( data );
}
});
why does not works?
in firebug I see the communication headers.
you are violating SOP. To avoid SOP uou would likely need a server side script (on your host) to load the external url and return the data to your client side script, or use a service that provides a JSONP results.
Well, for security reasons, Javascript don't allow a page to load a page from external domains. These security reasons are to prevent users from form hijacking, xss attacks etc. If you still want to load external pages, you can use iframes, else you will need an openId kind of thing in your backend.
Cross domain $.ajax is not permitted due to security violation. The only cross domain call that you can do in jQuery is JSONP request.
Please read my answer to this question: JavaScript: How do I create JSONP?

javascript how to load an script or data like google without ajax on any event

If i do this code
<script>
$('<img></img>').attr('src', 'someimage.jpg').appendTo($('#div'));
</script>
<div id="div"></div>
I can see GET htpp://somedomain.ext/someimage.jpg in Net Panel in Firebug.
I think google autocomplete also works pretty much the same way, since there are no asynchronous request, nothing can be seen on firebug console.
Now, is there any object (like img) that i could send http request to some domain for loading data like google.
UPDATE::
I HONESTLY DON'T SEE A THING IN XHR TAB IN NET PANEL.
WHY AM I SEEING REQEST MADE IN JS TAB IN NET PANEL.
Please correct me if i have misunderstood.
You are looking for the ajax method or one if the convenient front-ends for it: post, get, load, or getScript. There's an entire plugin written around the AJAX calls in jQuery for autocomplete. I'll note that if you are planning to get data from server outside the domain of your web page, you'll need to use JSONP against an API that supports it due to the same origin policy which disallows AJAX requests to other domains. When using JSONP as the result type, jQuery silently turns ajax, post, and get requests into script requests, i.e., adds a script tag with the url and url-encoded parameters to the data source and expects a script back that executes a callback with the returned data.

Categories