I've just starting learning jQuery and AJAX. I'm able to load a local page (on my disk) into a div via jQuery.load(), but external sites don't seem to work. I've even used wireshark to check if the data is being sent from the server (it is). Sample code is below:
<html>
<head>
<script src='jquery-1.4.2.min.js'></script>
<script>
$(document).ready(function() {
// $('#test').load('localpage.htm'); works!
$('#test').load('http://www.google.com/'); // does not work!
});
</script>
</head>
<body>
<div id='test'></div>
</body>
</html>
Is it possible to do this in the first place? If so, how?
You cannot do ajax calls to a different domain than the script originates from.
For doing such a thing, you have to use a proxy page on your own page, eg:
<script>
$(document).ready(function() {
$('#test').load('ajax/getgoogle.php');
});
</script>
getgoogle.php:
<?php
echo file_get_contents("http://www.google.com/");
?>
Out of the box: no. It's a security issue. There are a few different workarounds though.
You're running into the Same Origin Policy. You can't access data from an external domain using AJAX, it's considered a security risk. The reasoning behind it is that AJAX requests work with cookies stored by the browser -- if I tried to access facebook.com, and you were logged in there, the cookie would be sent and I'd have access to your personal data.
For security reasons, you cannot use AJAX to request a page from a different domain (or protocol or port).
Instead, you can write a server-side script on your server to forward requests to another domain. (This is not possible if you're running a page from a file:// url)
Ajax? Yes. XHR? No (unless the browser implements Cross-site XHR which isn't widespread yet).
To get the data with Ajax without using XHR the external site must provide the data in the JSONP format.
Alternatively, you can proxy the data through a server side script on your server, thus making it come from the same host (as far as JavaScript is concerned).
No, it's not. Have a look at Same Origin Policy. The site you are trying to request would need to have JSONP enabled for that to work, and you would utilize a cross-domain callback. Alternatively, you could create a proxy on your own domain which grabs the page on behalf of your ajax request.
Load this PHP script instead of trying to load website directly
$filename = "http://www.sitename.com";
$handle = fopen($filename, "r");
if ($handle)
{
while (!feof($handle))
{
$text .= fread($handle, 128);
}
fclose($handle);
}
print $text;
Edit: Or simply like henchman's solution with file_get_contents
You can't call Ajax from another domain. Check JSON technique for this
Related
I would like to display a existing sub-site in an iframe.
The twist is that I would like the content to be served via a custom Websocket http proxy. The server-side of the Websocket would handle retrieving the original sub-site content via http from the origin server.
I assume that all iframe browser (and Ajax) resource loading calls would need to be intercepted and satisfied by some Javascript code, which would get the needed resources via a Websocket connection.
Is this plain impossible?
When I got your problem correctly you try to get a web document and remove all the <iframe>-Tags.
You can do this by getting reading the page by file_get_contents() and removing all <iframe>-Tags by its pattern using preg_replace()
<?php
$content = file_get_contents('http://www.w3schools.com/html/html_iframe.asp');
echo preg_replace('/<iframe(|\/)(?!\?).*?(|\/)>/','', $content);
?>
Note: As some requests without a base URL (for example <img src="...) will look the for the resources on your server the site will not render correctly.
dran you stackoverflow! one day i will know your formitting... :x
I'm using the following script to load content on the page without refreshing it. The pages that I load this way should not be accessible as stand alone pages.
<script>
$(".toLoad").click( function(event)
{
event.preventDefault();
$("#page-wrapper").load($(this).attr("href"));
});
</script>
I have this in my index.php
define('SECURE', true);
and this in the other files
!defined('SECURE') and exit("Not allowed");
This system works very well with PHP's include or require functions but it blocks me from loading the pages from my index.php using the given javascript. What's the workaround or how could I restrict the direct access but allow it trough javascript on my main page?
Thanks!
define declares a constant, which is accessible during the script operation (only to php which means only on server).
It is not a variable
It does not persist between page loads (so when You hit another php file, this is not defined).
As for disallowing hotlinking - You can check HTTP Referer for instance, but it can be fooled.
Make a php-proxy thingy.. Then you .load('jsproxy.php?url=' + $(this).attr('href'));
I don't know php very much, but you should just define secure, and include the page in the url...
You cannot send your secure variable from index page to next page and session should not be used for this purpose as it will allow direct access as session always enable on request of index page. But you can check request is xmlhttp (ajax) request or not from server with following function as load() function request with HTTP_X_REQUESTED_WITH header with 'xmlhttprequest'.
function isAjax(){
return isset($_SERVER['HTTP_X_REQUESTED_WITH']) && !empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest';
}
if(!isAjax())
{
echo "no direct access"; exit(0);
}
I'd like to know if it's possible to load a remote XML file through the <script> tag, and access the content using JavaScript.
As the XML is a result of an external website (I'm using TheTVDb API), I can't load it using AJAX.
I'm looking for something like the following, if it's possible (JQuery-like syntax):
<script id="xmlload" type="text/xml" src="...">
<script type="text/javascript">
var xmlcontent = $('#xmlload').content();
// parse xmlcontent
</script>
I don't think that this is possible - you will need to use XmlHttpRequest (AJAX) to use a HTTP-based API. However, it might still be possible to actually do cross-site requests if the TheTVDb server allows this - see HTTP access control on MDN, which describes the relevant W3C specification (Cross-Origin Resource Sharing).
So if you haven't done so yet, I'd recommend you just try if making an AJAX request works. Otherwise, it might be a good idea to ask the TheTVDb folks if they are so kind to implement the mentioned spec.
thanks for reading. I'm trying to come up with a Javascript function that would convert the HTML source of a page at an external URL into a variable, so that the whole thing would become editable. The complication is, the URL does not end with a "html, htm, aspx" extension, but instead with a string of input form variables (i.e. ?type=AAA&color=BBB...). Hence the XMLHttpRequest method is out of the question.
Is this doable in JS/jQuery at all? I've heard about the same origin policy, but the following tool manages to do just that, although in PHP: http://www.iwebtool.com/code_viewer
Same origin policy does apply in this case, however you can do it with a combination of server side code (PHP) and jQuery. Heres a little example.
PHP
<?php
$url = $_REQUEST['url'];
$curl_handle=curl_init();
curl_setopt($curl_handle,CURLOPT_URL,$url);
curl_setopt($curl_handle,CURLOPT_CONNECTTIMEOUT,2);
curl_setopt($curl_handle,CURLOPT_RETURNTRANSFER,1);
$buffer = curl_exec($curl_handle);
curl_close($curl_handle);
echo($buffer);
?>
jQuery / HTML
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript">
$.ajax({
type: "POST",
url: "yourPhpScript.php",
data: "url=http://stackoverflow.com"
}).done(function( content ) {
$('#content').html(content);
//content is your variable containing the source
});
</script>
<div id="content"></div>
XMLHttpRequest works with any valid url, just give it the appropriate url and you can get the response as text.
However, there is the restriction of the same-origin policy. There are different workarounds to this for different situations, but if you want to be able to manipulate the text you receive then there is really only one option. Use the same javascript as you currently have, just add this as the first line of getUrl:
url='/path/to/proxy.php?url='+encodeURIComponent(url);
Then, on your server (the same one that's serving the page and its javascript), write proxy.php:
<?php
echo file_get_contents($_GET['url']);
?>
This will make every ajax request you make go to your server, which does not have the restriction of loading from only one domain. The server will load the url you asked for, and reply to you with the response it got from the page it loaded. Note that the above script will only give you the content body (what you see when you view-source) - if you need to access HTTP headers you can relay those too, it will just be more complicated.
Created javascript widget. Testing on my own domain and its working fine. However when posting on a 3rd party site it looks like it's not connecting to the database and getting the data.
Here is the part of the js file where I get the data:
/******* Load HTML *******/
var jsonp_url = "http://www.example.com/widget/data.php";
$.getJSON(jsonp_url, function(data) {
When I test on example.com everything is fine. I set the permissions on data.php to 777 and it still isn't working. Please help!
you cannot make an ajax call across different domains:
let's say your domain is 'example.com', and the third party site has 'thirdparty.com'. you install the widget on thirdparty.com. The widget code on thirdparty.com will try to make an ajax request to 'example.com'. Which is forbidden by the browser.
You can always replace the ajax call with a straight < script > tag. This doesn't have any restriction.
Hope it helps
You have a variable called jsonp_url, but the URL you use doesn't include the string callback=? which the documentation says triggers jsonp mode.
You need to include that in the URL and make sure that your server side script is outputting JSONP (using $_GET['callback'] (with suitable sanitisation) to determine the function name you wrap the JSON in).
they need to enable cross orgin resource sharing. http://enable-cors.org/