I want to provide a piece of Javascript code that will work on any website where it is included, but it always needs to get more data (or even modify data) on the server where the Javascript is hosted. I know that there are security restrictions in place for obvious reasons.
Consider index.html hosted on xyz.com containing the following:
<script type="text/javascript" src="http://abc.com/some.js"></script>
Will some.js be able to use XMLHttpRequest to post data to abc.com? In other words, is abc.com implicitly trusted because we loaded Javascript from there?
Will some.js be able to use XMLHttpRequest to post data to abc.com? In other words, is abc.com implicitly trusted because we loaded Javascript from there?
No, because the script is loaded on to a seperate domain it will not have access...
If you trust the data source then maybe JSONP would be the better option. JSONP involves dynamically adding new SCRIPT elements to the page with the SRC set to another domain, with a callback set as a parameter in the query string. For example:
function getJSON(URL,success){
var ud = 'json'+(Math.random()*100).toString().replace(/\./g,'');
window[ud]= function(o){
success&&success(o);
};
document.getElementsByTagName('body')[0].appendChild((function(){
var s = document.createElement('script');
s.type = 'text/javascript';
s.src = URL.replace('callback=?','callback='+ud);
return s;
})());
}
getJSON('http://YOUR-DOMAIN.com/script.php?dataName=john&dataAge=99&callback=?',function(data){
var success = data.flag === 'successful';
if(success) {
alert('The POST to abc.com WORKED SUCCESSFULLY');
}
});
So, you'll need to host your own script which could use PHP/CURL to post to the abc.com domain and then will output the response in JSONP format:
I'm not too great with PHP, but maybe something like this:
<?php
/* Grab the variables */
$postURL = $_GET['posturl'];
$postData['name'] = $_GET['dataName'];
$postData['age'] = $_GET['dataAge'];
/* Here, POST to abc.com */
/* MORE INFO: http://uk3.php.net/curl & http://www.askapache.com/htaccess/sending-post-form-data-with-php-curl.html */
/* Fake data (just for this example:) */
$postResponse = 'blahblahblah';
$postSuccess = TRUE;
/* Once you've done that, you can output a JSONP response */
/* Remember JSON format == 'JavaScript Object Notation' - e.g. {'foo':{'bar':'foo'}} */
echo $_GET['callback'] . '({';
echo "'flag':' . $postSuccess . ',";
echo "'response':' . $postResponse . '})";
?>
So, your server, which you have control over, will act as a medium between the client and abc.com, you'll send the response back to the client in JSON format so it can be understood and used by the JavaScript...
The easiest option for you would be to proxy the call through the server loading the javascript. So some.js would make a call to the hosting server, and that server would forward the request to abc.com.
of course, if that's not an option because you don't control the hoster, there are some options, but it seems mired in cross browser difficulties:
http://ajaxian.com/archives/how-to-make-xmlhttprequest-calls-to-another-server-in-your-domain
You could use easyXSS. Its a library that enables you to pass data, and to call methods across the domain boundry. Its quite easy and you should be able to use it.
There are many examples on the code.google.com site
Related
Can I perform something like this?
Situation
I want to check the URL. if URL equal to http://sample.com, do this, otherwise, do that.
What I did:
In Web.config -
<add key="ServerURLCloud" value="sample.com" />
In C# -
public static string GetURL()
{
string[] url = ConfigurationManager.AppSettings["ServerURLCloud"];
return url;
}
In Javascript -
if(varURL.indexOf('#ClassName.GetURL()') > 0){
urlToCall = 'sub.sample.com';
}else{
urlToCall = 'sub.not-sample.com';
}
$ajax(
url = urlToCall,
data = .........
....
)
I tested it, it is working very well. But, I want to know, will it be any problem if:
Internet connection slow
EDITED:
My Question
Is this practice (get Server side information at JavaScript) is good? Or bad?
i believe this code sample can be altered slightly to make it a little easier to maintain.
You could create a variable in your layout which could contain ConfigurationManager.AppSettings["ServerURLCloud"]
var siteSettings = {};
siteSettings.serverUrlCloud = '#ConfigurationManager.AppSettings["ServerURLCloud"]';
siteSettings.subSampleUrl = 'url';
siteSettings.subNotSampleUrl = '';
This site settings can hold anything useful as well (like base url etc)...
Also, try not to use magic strings in your code... instead, prefer to create variables/consts etc which hold these.
These changes wont impact the speed of your application but they will make it slightly easier to manage.
Also, the speed of the response from your ajax request is completely down to the executed code within that request, the length of the response and the internet connection speed... if the code is complex and doing a lot then it will naturally take longer. If the response is big, it will take longer to download. If the internet connection is slow, it will take longer to send the request and download the response.
Hope this helps
I am new to jQuery and JavaScript. I am trying to read the content of a .doc file and display it in a textarea.
var url = "D:\\way2Jobs\\way2jobz\\WebContent\\pages\\Resumes\\";
var firstName = $("#first").val();
var extn=".doc";
jQuery.ajax({
url : url+firstName+extn,
dataType : "doc",
success : function(data){
alert(firstName);
document.getElementById("candResume").innerHTML = data;
}
});
You just can't (thanks god) make an ajax request to your local filesystem. It's a safety restriction and you can't bypass this.
1 - You have to at least use a webserver like apache
2 - You never will sucessfuly make a request to D:\
3 - You CAN request a DOC file and process it using javascript. But it's not that easy because DOC file isn't a plain text and javascript was not made for it. Maybe it's easier for you to do it using a server side language such as PHP or JAVA or even NodeJS if you are familiar with javascript.
I was trying to read an info.json file, using the jQuery API. Please find the code below, which is part of test.html.
$.getJSON('info.json', function(data) {
var items = [];
$.each(data, function(key, val) {
items.push('<li id="' + key + '">' + val + '</li>');
});
The test.html file resides on my local machine and when I try to open it in the browser, the Ajax call is not getting triggered and the info.json file is not read.
Is it not working because I don't have a web server? Or am I doing anything wrong in the code? (I don't see any errors in the Firebug console though).
Thanks in advance.
You will always have to host your site from where you are making AJAX call. Otherwise it will throw this exception.
origin null is not allowed by access-control-allow-origin
Host your page on localhost server and I guess everything will work nicely.
While technically you don't need a web server for this, some of the libraries you use to abstract network access may not work with local files and some browsers don't let local files do a lot, so something like a little test web server for static files would be very useful for your development and testing.
Install a small webserver like http://jetty.codehaus.org/jetty/
easy to install, and small download ;)
By putting your JSON string into a text file and loading it in a iframe, you can extrapolate the data. (Most browsers can load .txt files in iframes.)
var frame = document.createElement("IFRAME"); //Create new iframe
var body = document.body;
frame.onload = function() { //Extrapolate JSON once loaded
data = JSON.parse(frame.contentDocument.documentElement.innerText); //Loads as a global.
body.removeChild(frame); //Removes the frame once no longer necessary.
}
frame.style.display = "none"; //Because the frame will have to be appended to the body.
body.appendChild(frame);
frame.src = "your JSON.txt"; //Select source after the onload function is set.
I display favicon's from other sites on my page.
About half the time they are here:
hostname.com/favicon.ico
But the other half they are not. For ecample in my own site I link to my .ico file like this. FAVICON is just a PHP definition of the path.
<link rel="SHORTCUT ICON" href="<?php echo FAVICON ?>" />
How do I get the URL of a site's favicon using the the link in the html?
This is site sais you can do a google search like this where you enter the domain you need the favicon for.
http://www.google.com/s2/favicons?domain=domain
Which is one solution but seems less efficient than just reading the html from the path.
I think google cached "ALL" icons into .png format and made them searchable -
per this site
Load the page using Ajax and a proxy page. For the Ajax:
// Create a request object:
var rq = new XMLHttpRequest(); // Not IE6-compatible, by the way.
// Set up the request:
rq.open('GET', 'proxy.php?url=' + encodeURIComponent(thePageURL), true);
// Handle when it's loaded:
rq.onreadystatechange = function() {
if(rq.readyState === 4) {
// The request is complete:
if(rq.status < 400) {
// The HTML is stored in rq.responseText; you could use a regular expression to extract the favicon, like /shortcut icon.+?href="(.+?)"/i.
} else {
// There was an error fetching the page; fall back?
}
}
};
And the proxy page (you'll probably want to add some security):
<?php
echo file_get_contents($_REQUEST['url']);
?>
Google "Ajax" and you'll find lots of information on how to do that sort of thing.
The reason you need to proxy the page is that browsers don't allow Ajax requests from JavaScript to go across domains unless the target allows it, which it must do explicitly. This is for security reasons, since the JavaScript could be maliciously impersonating the user. So instead, you proxy the content using a server-side script and avoid such problems.
Parsing HTML is nasty - you probably want to use a library like: http://www.controlstyle.com/articles/programming/text/php-favicon/ or let google do it for you: http://www.google.com/s2/favicons?domain=domain (much more efficient - you don't have to parse all the HTML on your server, and it's just one tag). If you want something like google's functionality on your server, check out the link above.
I have some code in a javascript file that needs to send queries back to the server. The question is, how do I find the url for the script that I am in, so I can build a proper request url for ajax.
I.e., the same script is included on /, /help, /whatever, and so on, while it will always need to request from /data.json. Additionally, the same site is run on different servers, where the /-folder might be placed differently. I have means to resolve the relative url where I include the Javascript (ez-publish template), but not within the javascript file itself.
Are there small scripts that will work on all browsers made for this?
For this I like to put <link> elements in the page's <head>, containing the URLs to use for requests. They can be generated by your server-side language so they always point to the right view:
<link id="link-action-1" href="${reverse_url ('action_1')}"/>
becomes
<link id="link-action-1" href="/my/web/root/action-1/"/>
and can be retrieved by Javascript with:
document.getElementById ('link-action-1').href;
document.location.href will give you the current URL, which you can then manipulate using JavaScript's string functions.
There's no way that the client can determine the webapp root without being told by the server as it has no knowledge of the server's configuration. One option you can try is to use the base element inside the head element, getting the server to generate it dynamically rather than hardcoding it (so it shows the relevant URL for each server):
<base href="http://path/to/webapp/root/" />
All URLs will then be treated as relative to this. You would therefore simply make your request to /data.json. You do however need to ensure that all other links in the application bear this in mind.
If the script knows its own filename, you can use document.getElementsByTagName(). Iterate through the list until you find the script that matches yours, and extract the full (or relative) url that way.
Here's an example:
function getScriptUrl ( name ) {
var scripts = document.getElementsByTagName('script');
var re = RegExp("(\/|^)" + name + "$");
var src;
for( var i = 0; i < scripts.length; i++){
src = scripts[i].getAttribute('src');
if( src.match(re) )
return src;
}
return null;
}
console.log( 'found ' + getScriptUrl('demo.js') );
Take into consideration that this approach is subject to filename collisions.
I include the following code in my libraries main entry point (main.php):
/**
* Build current url, depending on protocal (http/https),
* port, server name and path suffix
*/
$site_root = 'http';
if (isset($_SERVER["HTTPS"]) && $_SERVER["HTTPS"] == "on")
$site_root .= "s";
$site_root .= "://" . $_SERVER["SERVER_NAME"];
if ($_SERVER["SERVER_PORT"] != "80")
$site_root .= ":" . $_SERVER["SERVER_PORT"];
$site_root .= $g_config["paths"]["site_suffix"];
$g_config["paths"]["site_root"] = $site_root;
$g_config is a global array containing configuration options. So site_suffix might look like: "/sites_working/thesite/public_html" on your development box, and just "/" on a server with a virtual host (domain name).
This method is also good, because if somebody types in the IP address of your development box, it will use that same IP address to build the path to the javascript folder instead of something like "localhost," and if you use "localhost" it will use "localhost" to build the URL.
And because it also detects SSL, you wont have to worry about weather your resources will be sent over HTTP or HTTPS if you ever add SSL support to your server.
Then, in your template, either use
<link id="site_root" href="<?php echo $g_config["paths"]["site_root"] ?>"/>
Or
<script type = "text/javascript">
var SiteRoot = "<?php echo $g_config["paths"]["site_root"]; ?>";
</script>
I suppose the latter would be faster.