Related
This question already has answers here:
Detect the Internet connection is offline?
(22 answers)
Closed 8 years ago.
How do you check if there is an internet connection using jQuery? That way I could have some conditionals saying "use the google cached version of JQuery during production, use either that or a local version during development, depending on the internet connection".
The best option for your specific case might be:
Right before your close </body> tag:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script>window.jQuery || document.write('<script src="js/vendor/jquery-1.10.2.min.js"><\/script>')</script>
This is probably the easiest way given that your issue is centered around jQuery.
If you wanted a more robust solution you could try:
var online = navigator.onLine;
Read more about the W3C's spec on offline web apps, however be aware that this will work best in modern web browsers, doing so with older web browsers may not work as expected, or at all.
Alternatively, an XHR request to your own server isn't that bad of a method for testing your connectivity. Considering one of the other answers state that there are too many points of failure for an XHR, if your XHR is flawed when establishing it's connection then it'll also be flawed during routine use anyhow. If your site is unreachable for any reason, then your other services running on the same servers will likely be unreachable also. That decision is up to you.
I wouldn't recommend making an XHR request to someone else's service, even google.com for that matter. Make the request to your server, or not at all.
What does it mean to be "online"?
There seems to be some confusion around what being "online" means. Consider that the internet is a bunch of networks, however sometimes you're on a VPN, without access to the internet "at-large" or the world wide web. Often companies have their own networks which have limited connectivity to other external networks, therefore you could be considered "online". Being online only entails that you are connected to a network, not the availability nor reachability of the services you are trying to connect to.
To determine if a host is reachable from your network, you could do this:
function hostReachable() {
// Handle IE and more capable browsers
var xhr = new ( window.ActiveXObject || XMLHttpRequest )( "Microsoft.XMLHTTP" );
// Open new request as a HEAD to the root hostname with a random param to bust the cache
xhr.open( "HEAD", "//" + window.location.hostname + "/?rand=" + Math.floor((1 + Math.random()) * 0x10000), false );
// Issue request and handle response
try {
xhr.send();
return ( xhr.status >= 200 && (xhr.status < 300 || xhr.status === 304) );
} catch (error) {
return false;
}
}
You can also find the Gist for that here: https://gist.github.com/jpsilvashy/5725579
Details on local implementation
Some people have commented, "I'm always being returned false". That's because you're probably testing it out on your local server. Whatever server you're making the request to, you'll need to be able to respond to the HEAD request, that of course can be changed to a GET if you want.
Ok, maybe a bit late in the game but what about checking with an online image?
I mean, the OP needs to know if he needs to grab the Google CMD or the local JQ copy, but that doesn't mean the browser can't read Javascript no matter what, right?
<script>
function doConnectFunction() {
// Grab the GOOGLE CMD
}
function doNotConnectFunction() {
// Grab the LOCAL JQ
}
var i = new Image();
i.onload = doConnectFunction;
i.onerror = doNotConnectFunction;
// CHANGE IMAGE URL TO ANY IMAGE YOU KNOW IS LIVE
i.src = 'http://gfx2.hotmail.com/mail/uxp/w4/m4/pr014/h/s7.png?d=' + escape(Date());
// escape(Date()) is necessary to override possibility of image coming from cache
</script>
Just my 2 cents
5 years later-version:
Today, there are JS libraries for you, if you don't want to get into the nitty gritty of the different methods described on this page.
On of these is https://github.com/hubspot/offline. It checks for the connectivity of a pre-defined URI, by default your favicon. It automatically detects when the user's connectivity has been reestablished and provides neat events like up and down, which you can bind to in order to update your UI.
You can mimic the Ping command.
Use Ajax to request a timestamp to your own server, define a timer using setTimeout to 5 seconds, if theres no response it try again.
If there's no response in 4 attempts, you can suppose that internet is down.
So you can check using this routine in regular intervals like 1 or 3 minutes.
That seems a good and clean solution for me.
You can try by sending XHR Requests a few times, and then if you get errors it means there's a problem with the internet connection.
I wrote a jQuery plugin for doing this. By default it checks the current URL (because that's already loaded once from the Web) or you can specify a URL to use as an argument. Always doing a request to Google isn't the best idea because it's blocked in different countries at different times. Also you might be at the mercy of what the connection across a particular ocean/weather front/political climate might be like that day.
http://tomriley.net/blog/archives/111
i have a solution who work here to check if internet connection exist :
$.ajax({
url: "http://www.google.com",
context: document.body,
error: function(jqXHR, exception) {
alert('Offline')
},
success: function() {
alert('Online')
}
})
Sending XHR requests is bad because it could fail if that particular server is down. Instead, use googles API library to load their cached version(s) of jQuery.
You can use googles API to perform a callback after loading jQuery, and this will check if jQuery was loaded successfully. Something like the code below should work:
<script type="text/javascript">
google.load("jquery");
// Call this function when the page has been loaded
function test_connection() {
if($){
//jQuery WAS loaded.
} else {
//jQuery failed to load. Grab the local copy.
}
}
google.setOnLoadCallback(test_connection);
</script>
The google API documentation can be found here.
A much simpler solution:
<script language="javascript" src="http://maps.google.com/maps/api/js?v=3.2&sensor=false"></script>
and later in the code:
var online;
// check whether this function works (online only)
try {
var x = google.maps.MapTypeId.TERRAIN;
online = true;
} catch (e) {
online = false;
}
console.log(online);
When not online the google script will not be loaded thus resulting in an error where an exception will be thrown.
var xhttp=new XMLHttpRequest();
xhttp.open('GET', 'foo.xml', false);
F12 pops back: SCRIPT5: Access is denied. on Line 95, which is the xhttp.open line.
My JavaScript seems well-formed, and Firefox does what I think it should.
I've read a lot of questions very similar to this one, so I've checked out the Same Origin Policy, but I can't see how it'd apply considering foo.xml is in the same directory as the html file. I opened up the scripting permissions on my local intranet, and told McAfee to take a five-minute break, just to be sure. I even tried running IE as admin, so this can't really be a permissions issue can it? Why else would IE be denied access to a local file?
Maybe you like to check the links below:
Making cross domain JavaScript requests using XMLHttpRequest or XDomainRequest
XMLHttpRequest – Mozilla Developer Network
A good summary of the jQuery x-domain requests
Which browser supports x-domain?
You likely have a Mark-of-the-Web on the local file. See http://blogs.msdn.com/b/ieinternals/archive/2011/03/23/understanding-local-machine-zone-lockdown-restricted-this-webpage-from-running-scripts-or-activex-controls.aspx for an explanation.
This example illustrate how to use AJAX to pull resourcess from any website. it works across browsers. i have tested it on IE8-IE10, safari, chrome, firefox, opera.
if (window.XDomainRequest) xmlhttp = new XDomainRequest();
else if (window.XMLHttpRequest) xmlhttp = new XMLHttpRequest();
else xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
xmlhttp.open("GET", "http://api.hostip.info/get_html.php", false);
xmlhttp.send();
hostipInfo = xmlhttp.responseText.split("\n");
var IP = false;
for (i = 0; hostipInfo.length >= i; i++) {
if (hostipInfo[i]) {
ipAddress = hostipInfo[i].split(":");
if (ipAddress[0] == "IP") {
IP = ipAddress[1];
}
}
}
return IP;
On IE7, IE8, and IE9 just go to Settings->Internet Options->Security->Custom Level and change security settings under "Miscellaneous" set "Access data sources across domains" to Enable.
This error message (SCRIPT5: Access is denied.) can also be encountered if the target page of a .replace method is not found (I had entered the page name incorrectly). I know because it just happened to me, which is why I went searching for some more information about the meaning of the error message.
Most likely, you need to have the Javascript served over SSL.
Source: https://www.parse.com/questions/internet-explorer-and-the-javascript-sdk
I think that the issue is that the file is on your local computer, and IE is denying access because if it let scripts have access to files on the comp that the browser is running on, that would be a HUGE security hole.
If you have access to a server or another comp that you could use as one, maybe you could try putting the files on the that, and then running the scripts as you would from a website.
Probably you are requesting for an external resource, this case IE needs the XDomain object. See the sample code below for how to make ajax request for all browsers with cross domains:
Tork.post = function (url,data,callBack,callBackParameter){
if (url.indexOf("?")>0){
data = url.substring(url.indexOf("?")+1)+"&"+ data;
url = url.substring(0,url.indexOf("?"));
}
data += "&randomNumberG=" + Math.random() + (Tork.debug?"&debug=1":"");
var xmlhttp;
if (window.XDomainRequest)
{
xmlhttp=new XDomainRequest();
xmlhttp.onload = function(){callBack(xmlhttp.responseText)};
}
else if (window.XMLHttpRequest)
xmlhttp=new XMLHttpRequest();
else
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200){
Tork.msg("Response:"+xmlhttp.responseText);
callBack(xmlhttp.responseText,callBackParameter);
Tork.showLoadingScreen(false);
}
}
xmlhttp.open("POST",Tork.baseURL+url,true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send(data);
}
I had faced similar issue on IE10. I had a workaround by using the jQuery ajax request to retrieve data:
$.ajax({
url: YOUR_XML_FILE
aync: false,
success: function (data) {
// Store data into a variable
},
dataType: YOUR_DATA_TYPE,
complete: ON_COMPLETE_FUNCTION_CALL
});
$.ajax({
url: '//freegeoip.net/json/',
type: 'POST',
dataType: 'jsonp',
success: function(location) {
alert(location.ip);
}
});
This code will work https sites too
Open the Internet Explorer Developer Tool,
Tools -> F12 developer tools. (I think you can also press F12 to get it)
Change the Document Mode to Standards. (The page should be automatically refresh, if you change the Document Mode)
Problem should be fixed.
Enjoy
var xhttp=new XMLHttpRequest();
xhttp.open('GET', 'foo.xml', false);
F12 pops back: SCRIPT5: Access is denied. on Line 95, which is the xhttp.open line.
My JavaScript seems well-formed, and Firefox does what I think it should.
I've read a lot of questions very similar to this one, so I've checked out the Same Origin Policy, but I can't see how it'd apply considering foo.xml is in the same directory as the html file. I opened up the scripting permissions on my local intranet, and told McAfee to take a five-minute break, just to be sure. I even tried running IE as admin, so this can't really be a permissions issue can it? Why else would IE be denied access to a local file?
Maybe you like to check the links below:
Making cross domain JavaScript requests using XMLHttpRequest or XDomainRequest
XMLHttpRequest – Mozilla Developer Network
A good summary of the jQuery x-domain requests
Which browser supports x-domain?
You likely have a Mark-of-the-Web on the local file. See http://blogs.msdn.com/b/ieinternals/archive/2011/03/23/understanding-local-machine-zone-lockdown-restricted-this-webpage-from-running-scripts-or-activex-controls.aspx for an explanation.
This example illustrate how to use AJAX to pull resourcess from any website. it works across browsers. i have tested it on IE8-IE10, safari, chrome, firefox, opera.
if (window.XDomainRequest) xmlhttp = new XDomainRequest();
else if (window.XMLHttpRequest) xmlhttp = new XMLHttpRequest();
else xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
xmlhttp.open("GET", "http://api.hostip.info/get_html.php", false);
xmlhttp.send();
hostipInfo = xmlhttp.responseText.split("\n");
var IP = false;
for (i = 0; hostipInfo.length >= i; i++) {
if (hostipInfo[i]) {
ipAddress = hostipInfo[i].split(":");
if (ipAddress[0] == "IP") {
IP = ipAddress[1];
}
}
}
return IP;
On IE7, IE8, and IE9 just go to Settings->Internet Options->Security->Custom Level and change security settings under "Miscellaneous" set "Access data sources across domains" to Enable.
This error message (SCRIPT5: Access is denied.) can also be encountered if the target page of a .replace method is not found (I had entered the page name incorrectly). I know because it just happened to me, which is why I went searching for some more information about the meaning of the error message.
Most likely, you need to have the Javascript served over SSL.
Source: https://www.parse.com/questions/internet-explorer-and-the-javascript-sdk
I think that the issue is that the file is on your local computer, and IE is denying access because if it let scripts have access to files on the comp that the browser is running on, that would be a HUGE security hole.
If you have access to a server or another comp that you could use as one, maybe you could try putting the files on the that, and then running the scripts as you would from a website.
Probably you are requesting for an external resource, this case IE needs the XDomain object. See the sample code below for how to make ajax request for all browsers with cross domains:
Tork.post = function (url,data,callBack,callBackParameter){
if (url.indexOf("?")>0){
data = url.substring(url.indexOf("?")+1)+"&"+ data;
url = url.substring(0,url.indexOf("?"));
}
data += "&randomNumberG=" + Math.random() + (Tork.debug?"&debug=1":"");
var xmlhttp;
if (window.XDomainRequest)
{
xmlhttp=new XDomainRequest();
xmlhttp.onload = function(){callBack(xmlhttp.responseText)};
}
else if (window.XMLHttpRequest)
xmlhttp=new XMLHttpRequest();
else
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200){
Tork.msg("Response:"+xmlhttp.responseText);
callBack(xmlhttp.responseText,callBackParameter);
Tork.showLoadingScreen(false);
}
}
xmlhttp.open("POST",Tork.baseURL+url,true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send(data);
}
I had faced similar issue on IE10. I had a workaround by using the jQuery ajax request to retrieve data:
$.ajax({
url: YOUR_XML_FILE
aync: false,
success: function (data) {
// Store data into a variable
},
dataType: YOUR_DATA_TYPE,
complete: ON_COMPLETE_FUNCTION_CALL
});
$.ajax({
url: '//freegeoip.net/json/',
type: 'POST',
dataType: 'jsonp',
success: function(location) {
alert(location.ip);
}
});
This code will work https sites too
Open the Internet Explorer Developer Tool,
Tools -> F12 developer tools. (I think you can also press F12 to get it)
Change the Document Mode to Standards. (The page should be automatically refresh, if you change the Document Mode)
Problem should be fixed.
Enjoy
I have an iframe using the jQuery 1.4.2 script. The same iframe is injected into both http and https sites. The jQuery script is included in the main HTML file as a relative path (e.g., /scripts/jquery-1.4.2.min.js).
When an AJAX call is made, Internet Explorer denies access. The AJAX is calling on another subdomain, but it's using the right protocol. All other browsers work but Internet Explorer gives the following error:
SCRIPT5: Access is denied.
jquery-1.4.2.min.js, line 127 character 344
I heard this error is from cross-domain AJAX calls. But why is IE the only one giving me crap? Is there an IE solution?
Also, this is my AJAX:
$.ajax({
url: thisURL,
dataType: "json",
data: {cmd : 'getMessage', uurl: urlVar, t: Math.random()},
success: function(ret){
callback(ret)
}
});
IE requires you to use XDomainRequest instead of XHR for cross site, you can try something like...
if ($.browser.msie && window.XDomainRequest) {
// Use Microsoft XDR
var xdr = new XDomainRequest();
xdr.open("get", url);
xdr.onload = function() {
// XDomainRequest doesn't provide responseXml, so if you need it:
var dom = new ActiveXObject("Microsoft.XMLDOM");
dom.async = false;
dom.loadXML(xdr.responseText);
};
xdr.send();
} else {
// your ajax request here
$$.ajax({
url: thisURL,
dataType: "json",
data: {cmd : 'getMessage', uurl: urlVar, t: Math.random()},
success: function(ret){
callback(ret)
}
});
}
Reference
http://forum.jquery.com/topic/cross-domain-ajax-and-ie
not sure whether it fits your scenario
xdr = new XDomainRequest();
xdr.onload=function()
{
alert(xdr.responseText);
}
xdr.open("GET", thisUrl); //thisURl ->your cross domain request URL
//pass your data here
xdr.send([data]);
you can find some more guidance here
This solved the issue gracefully for me:
https://github.com/MoonScript/jQuery-ajaxTransport-XDomainRequest
Just install/compile after jQuery and before your script and use the $.ajax method as you normally would, the rest is handled behind the automatically.
Have you try to use the lastest of JQuery(> jquery-1.8.0)? Since the version 1.8.0, they solved some IE9's bugs. Perhaps this one too.
http://blog.jquery.com/2012/08/30/jquery-1-8-1-released/
I had a similar problem and the solution for me was to use jsonp instead of json. That way I didn't have to break out a customer version for IE.
You can only do this if the json server host supports the callback request variable or you have access to the server and can add support. Here is a page that helped me understand the process. Its .net mvc focused, but it gives a good over view of the diffrence between json and jsonp.
http://blogorama.nerdworks.in/entry-EnablingJSONPcallsonASPNETMVC.aspx
Check the domain you are accessing, following response headers should be there
"Access-Control-Allow-Methods" : "POST, GET, OPTIONS"
"Access-Control-Allow-Origin" : "http://www.mydomain.com" or "*"
the other domain should allow your script request. One more header to be added to your response is P3P header.
"p3p" : "CP=IDC DSP COR ADM DEVi TAIi PSA PSD IVAi IVDi CONi HIS OUR IND CNT"
it should help you out.
I was facing similar issue.
I was using file upload control but it was hidden and I had another element trying to control the file upload and events to upload file in ajax way
try using the file upload control directly. this solved issue in my application.
I get this bug (and thus google here) but the reason was very different. So if you don't have cross site and still get this access denied error: double check the value sent
let's say that you affect one of you variable with the bad following expression:
urlVar = $("theID").val // without () this was the error!
[...]ajax call:
data: {cmd : 'getMessage', uurl: urlVar, t: Math.random()},
Google/FF have no problem with this (check what is receive server side...) BUT IE refuse to send this!
I changed my JQuery from version 1.10.1 to 1.10.2 and it seems to have solved this problem for me.
It seems that MS is finding its own way of doing things, rather than adopting industry recommendations. I found the solution here:
https://github.com/MoonScript/jQuery-ajaxTransport-XDomainRequest/blob/master/jQuery.XDomainRequest.js
Simply add 'callback=?' on your ajax URL request like here:
http://wsvdmeer.blogspot.com.es/2012/08/bugfix-getjson-not-working-in-ie.html
How can I make requests to other server(s) (i.e. get a page from any desired server) with a JavaScript within the user's browser? There are limitations in place to prevent this for methods like XMLHttpRequest, are there ways to bypass them or other methods?
That is a general question, specifically I want to check a series of random websites and see if they contain a certain element, so I need the HTML content of a website without downloading any additional files; all that in a JavaScript file, without any forwarding or proxy mechanism on a server.
(Note: one way is using Greasemonkey and its GM_xmlhttpRequest.)
You should check out jQuery. It has a rich base of AJAX functionality that can give you the power to do all of this. You can load in an external page, and parse it's HTML content with intuitive CSS-like selectors.
An example using $.get();
$.get("anotherPage.html", {}, function(results){
alert(results); // will show the HTML from anotherPage.html
alert($(results).find("div.scores").html()); // show "scores" div in results
});
For external domains I've had to author a local PHP script that will act as a middle-man. jQuery will call the local PHP script passing in another server's URL as an argument, the local PHP script will gather the data, and jQuery will read the data from the local PHP script.
$.get("middleman.php", {"site":"http://www.google.com"}, function(results){
alert(results); // middleman gives Google's HTML to jQuery
});
Giving middleman.php something along the lines of
<?php
// Do not use as-is, this is only an example.
// $_GET["site"] set by jQuery as "http://www.google.com"
print file_get_contents($_GET["site"]);
?>
update 2018:
You can only access cross domain with the following 4 condition
in response header has Access-Control-Allow-Origin: *
Demo
$.ajax({
url: 'https://api.myjson.com/bins/bq6eu',
success: function(response){
console.log(response.string);
},
error: function(response){
console.log('server error');
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
use server as bridge or proxy to the target
Demo:
$.ajax({
url: 'https://cors-anywhere.herokuapp.com/http://whatismyip.akamai.com/',
success: function(response){
console.log('server IP: ' + response);
},
error: function(response){
console.log('bridge server error');
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
using browser addon to enable Allow-Control-Allow-Origin: *
disable browser web security
Chrome
chrome.exe --args --disable-web-security
Firefox
about:config -> security.fileuri.strict_origin_policy -> false
end
noob old answer 2011
$.get(); can get data from jsbin.com but i don't know why it can't get data from another site like google.com
$.get('http://jsbin.com/ufotu5', {},
function(results){ alert(results);
});
demo: http://jsfiddle.net/Xj234/
tested with firefox, chrome and safari.
Write a proxy script that forwards along the http request from your domain, this will bypass the XMLHttpRequest restrictions.
If your using PHP, simply use cURL to request and read the page, then simply spit out the html as if it was from you domain.
This is rather easy... if you know the 'secret' trick almost nobody shares..
It's called Yahoo yql...
So in order to regain 'power to the user' (and returning to the convenient mantra: 'never accept no'), just use http://query.yahooapis.com/ (instead of a php? proxy serverside script).
jQuery would not be strictly needed.
EXAMPLE 1:
Using the SQL-like command:
select * from html
where url="http://stackoverflow.com"
and xpath='//div/h3/a'
The following link will scrape SO for the newest questions (bypassing cross-domain security bull$#!7):
http://query.yahooapis.com/v1/public/yql?q=select%20title%20from%20html%20where%20url%3D%22http%3A%2F%2Fstackoverflow.com%22%20and%0A%20%20%20%20%20%20xpath%3D%27%2F%2Fdiv%2Fh3%2Fa%27%0A%20%20%20%20&format=json&callback=cbfunc
As you can see this will return a JSON array (one can also choose xml) and calling the callback-function: cbfunc.
Indeed, as a 'bonus' you also save a kitten every time you did not need to regex data out of 'tag-soup'.
Do you hear your little mad scientist inside yourself starting to giggle?
Then see this answer for more info (and don't forget it's comments for more examples).
Good Luck!
You can also use a iframe to emulate an ajax request. This saves you the mess of having to code a Backend solution for a Frontend problem. Here is an example:
function setUploadEvent(typeComponet){
var eventType = "";
var iframe = document.getElementById("iframeId");
try{
/* for Mozilla / Opera9 */
if (/(?!.*?compatible|.*?webkit)^mozilla|opera/i.test(navigator.userAgent)) {
eventType = "onload";
}else{
/* IE */
eventType = "onreadystatechange";
}
iframe[eventType] = function(){
var doc = iframe.contentDocument || iframe.contentWindow.document;
var response = doc.body.innerHTML; /* or what ever content you are looking for */
}
}
catch(e){
alert("Error loading content")}
}
That should do the trick. Please note that the Browser detection line is not the cleanest, you should absolutely use the ones provided in all the most common JS frameworks (Prototype, JQuery, etc)
You will need to write a proxy on the server to do this. And all requests will be to your server and then your server will load html and send it back to client. And there are no good way to implement this via javascript only.
jQuery contains functionality to load JSON data or external scripts using XmlHttpRequest but this functionality can not be used for html pages. Also you may check this thread of jQuery mailing list.
<script language="JavaScript" type="text/javascript" src="http://www.example.com/hello.js"></script>
You add the data into hello.js in as an array, JSON or similar. Example:
var daysInMonth = new Array(31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);
Getting a JavaScript from another server doesn't much simpler.. :-)
Thanks a lot, this is really a good trick. I did in this way:
test.html
<!DOCTYPE html>
<html>
<head>
<script>
function loadXMLDoc()
{
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","sp.php",true);
xmlhttp.send();
}
</script>
</head>
<body>
<h2>Using the XMLHttpRequest object</h2>
<div id="myDiv"></div>
<button type="button" onclick="loadXMLDoc()">Change Content</button>
</body>
</html>
sp.php
<?php
print file_get_contents("http://your.url.com/you-can-use-cross-domain");
?>