Javascript works great locally, but not on my server - javascript

I'm teaching myself javascript by creating a script for displaying an external rss feed on a webpage.
The code I patched together works great locally. This is a screen grab of the code producing exactly the desired behavior. The code is populating all the information inside the section "Blog: Shades of Gray", except for "tagged" which I hard coded:
But when I upload the site files to my server, the code doesn't work at all. This is a screen grab of the code on my site NOT producing the desired behavior...
This feels like I'm not getting something really basic about how javascript works locally vs. on the server. I did my half hour of googling for an answer and no trails look promising. So I'd really appreciate your help.
This is my site (under construction) http://jonathangcohen.com
Below is the code, which can also be found at http://jonathangcohen.com/grabFeeds.js.
/*Javascript for Displaying an External RSS Feed on a Webpage
Wrote some code that’ll grab attributes from an rss feed and assign IDs for displaying on a webpage. The code references my Tumblr blog but it’ll extend to any RSS feed.*/
window.onload = writeRSS;
function writeRSS(){
writeBlog();
}
function writeBlog(){
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET","http://blog.jonathangcohen.com/rss.xml",false);
xmlhttp.send();
xmlDoc=xmlhttp.responseXML;
var x=xmlDoc.getElementsByTagName("item");
//append category to link
for (i=0;i<3;i++)
{
if (i == 0){
//print category
var blogTumblrCategory = x[i].getElementsByTagName("category")[0].childNodes[0].nodeValue
document.getElementById("getBlogCategory1").innerHTML =
'<a class="BlogTitleLinkStyle" href="http://blog.jonathangcohen.com/tagged/'+blogTumblrCategory+'">'+blogTumblrCategory+'</a>';
//print date
var k = x[i].getElementsByTagName("pubDate")[0].childNodes[0].nodeValue
thisDate = new Date();
thisDate = formatTumblrDate(k);
document.getElementById("getBlogPublishDate1").innerHTML = thisDate;
//print title
var blogTumblrTitle = x[i].getElementsByTagName("title")[0].childNodes[0].nodeValue
var blogTumblrLink = x[i].getElementsByTagName("link")[0].childNodes[0].nodeValue
document.getElementById("getBlogTitle1").innerHTML =
'<a class="BlogTitleLinkStyle" href="'+blogTumblrLink+'">'+blogTumblrTitle+'</a>';
}
if (i == 1){
//print category
var blogTumblrCategory = x[i].getElementsByTagName("category")[0].childNodes[0].nodeValue
document.getElementById("getBlogCategory2").innerHTML =
'<a class="BlogTitleLinkStyle" href="http://blog.jonathangcohen.com/tagged/'+blogTumblrCategory+'">'+blogTumblrCategory+'</a>';
//print date
var k = x[i].getElementsByTagName("pubDate")[0].childNodes[0].nodeValue
thisDate = new Date();
thisDate = formatTumblrDate(k);
document.getElementById("getBlogPublishDate2").innerHTML = thisDate;
//print title
var blogTumblrTitle = x[i].getElementsByTagName("title")[0].childNodes[0].nodeValue
var blogTumblrLink = x[i].getElementsByTagName("link")[0].childNodes[0].nodeValue
document.getElementById("getBlogTitle2").innerHTML =
'<a class="BlogTitleLinkStyle" href="'+blogTumblrLink+'">'+blogTumblrTitle+'</a>';
}
if (i == 2){
//print category
var blogTumblrCategory = x[i].getElementsByTagName("category")[0].childNodes[0].nodeValue
document.getElementById("getBlogCategory3").innerHTML =
'<a class="BlogTitleLinkStyle" href="http://blog.jonathangcohen.com/tagged/'+blogTumblrCategory+'">'+blogTumblrCategory+'</a>';
//print date
var k = x[i].getElementsByTagName("pubDate")[0].childNodes[0].nodeValue
thisDate = new Date();
thisDate = formatTumblrDate(k);
document.getElementById("getBlogPublishDate3").innerHTML = thisDate;
//print title
var blogTumblrTitle = x[i].getElementsByTagName("title")[0].childNodes[0].nodeValue
var blogTumblrLink = x[i].getElementsByTagName("link")[0].childNodes[0].nodeValue
document.getElementById("getBlogTitle3").innerHTML =
'<a class="BlogTitleLinkStyle" href="'+blogTumblrLink+'">'+blogTumblrTitle+'</a>';
}
}
}
function formatTumblrDate(k){
d = new Date(k);
var curr_date = d.getDate();
var curr_month = d.getMonth();
curr_month++;
var curr_year = d.getFullYear();
printDate = (curr_month + "/" + curr_date + "/" + curr_year);
return printDate;
}
Thank you!

You are running into the same origin policy, which has been discussed many times on Stack Overflow.

AJAX runs on a same-origin policy, ie, you can only call your own server.
A fix would be making a call to your server which in turn calls the target server.
Here's how (to give you a general picture ;))

You are doing an XmlHttpRequest to another domain, crossing the security sandbox and going against the same-origin policy, which means the request to blog.jonathangcohen.com/rss.xml fails, and you get nothing out of it.
The only viable solutions are to either use jsonp or a proxy on your jonathangcohen.com domain, for example a simple php script that would just contain the following would do the trick:
<?php
header('Content-Type: text/xml');
echo file_get_contents('http://blog.jonathangcohen.com/rss.xml');
Then you request the data from http://jonathangcohen.com/rss-proxy.php

This seems like a permissions thing. Cross-site scripting and all. The browser is more lenient on local pages (probably) but won't allow you to do this on an actual server. You'll need to grab that data on the server and then feed it to your javascript.

It's a cross-origin policy thing, which you can read more about here: http://arunranga.com/examples/access-control/
In order for javascript on mydomain.com to fetch resources from blog.mydomain.com, blog.mydomain.com will need to send the response header Access-Control-Allow-Origin: http://mydomain.com
The only other way to do it that I know of would be to setup a script on blog.mydomain.com, such as blog.mydomain.com/feed.php, that will return a valid JSONP response. In order to use it, you would then, instead of using XMLHttpRequest, create a <script> element, and set the source to http://blog.mydomain.com/feed.php. The output from feed.php should call a javascript function and pass in the actual content of the XML feed, if that makes sense.
edit: The other answers will obviously work as well, and the specific answer about using a proxy script on your site (that reads in and spits out the content of the feed) would be even easier and would only require a URL change in your existing javascript.

Related

Is there a Simpler way to output a complete 'script' tag as text?

I'm writing some AJAX that pulls in a web page that has the potential to have scripts and/or css that I'm trying to separate out into a couple of supporting fields in a form that runs all of this.
I believe the pertinent code in this case is the AJAX finalizer.
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
var JavascriptContent = document.getElementsByName('AgendaJS')[0];
var CSSContent = document.getElementsByName('AgendaCSS')[0];
var Parser = new DOMParser();
var xmlData = Parser.parseFromString(xmlhttp.responseText, "text/html");
var ResponseBody = xmlData.getElementsByTagName('body')[0];
tinymce.activeEditor.setContent(ResponseBody.innerHTML);
var ResponseScripts = xmlData.getElementsByTagName('script');
var i = 0;
for( i = i; i <= ResponseScripts.length; i++ )
{
JavascriptContent.innerText += "\r\n" + String(ResponseScripts[i]);
}
return;
}
}
The idea here is to add any script tags ( preferably a direct copy of the full text ) to the 'AgendaJS' textarea.
The way I see it right now, is that I am almost bound to examining the individual elements of the script tag and regenerating the entire tag from 'scratch' - so my hope here is that I can find a manner in which to dump this element into that field that doesn't yield this:
[object HTMLScriptElement]
I've glanced around at a few posts here and elsewhere that claim that a particular method works - but I am yet to confirm any of them.
To be clear - I'd effectively like the resulting addition to the JS field to be the full tag and closing tag, like so:
<script type="text/javascript" src="/tinymce/js/tinymce/tinymce.min.js"></script>
Use ResponseScripts[i].outerHTML instead of String(ResponseScripts[i])

Async JavaScript Function on Client Side( how to write call back)

i m facing a problem basically i have long running task that reads encoded bytes and then parse the bytes to find data in it.
functionLongRunningTask() {
//bytes returned from office.js (GetFileAsync Method)
var documentText = OSF.OUtil.encodeBase64(resultSlice.value.data);
// Open the document, which is stored as a base64 string.
var doc = new openXml.OpenXmlPackage(documentText);
var customXMLpart = doc.getPartByUri("/customXml/item1.xml");
if (customXMLpart == 'undefined' || customXMLpart == null) {
window.location = 'Page1.aspx'
}
else {
if (window.DOMParser) {
var parser = new DOMParser();
xmlDoc = parser.parseFromString(customXMLpart.data, "text/xml");
}
var customxml = xmlDoc.getElementsByTagName("DocumentID");
var documentid = 0;
for (var i = 0; i < customxml.length; i++) {
documentid = customxml[i].textContent;
}
window.location = 'Page2.aspx?documentid=' + documentid;
}
}
all of reading and traversing done on client side no server side involved in it. now as my application running in office word 2013 (Office APP basically) when i run this long Running task in synchronous way . UI gets freezed and stop responding and it restart Office APP.
i need to do it in Asynchronous way so UI dont get freeze i am using HTML5 and IE 9+. Any help will be appreciated
Regards
You wont have access to the DOM Parser in a WebWorker, so this method is not applicable. You will need to run portions of the code on a timer event.
Here is a library that may be able to help with running code against a timer -> https://github.com/jameswestgate/taskjs

Forwarding website to pdf file on another server using JavaScript

I'm relative new to html, js etc. Till now I worked on websites in a "contained" environment, I only accessed my own resources or if I did others I'd always have a hardcoded link.
My university offers lecture schedules online using inputs for class and date.
The pdf is always saved in following format ../onxx-yyyy-ww.pdf
I want to create a website that once asks for class, then saves it in a cookie and from then on everytime you visit the website it will forward you to the pdf file with the current schedule.
I found out that this could be achieved with something called AJAX, which I don't know nothing about. This is how far I've come:
js part(excluded getWeek() by Nick Baicoianu):
window.onload = function(){
checkCookie();
}
function checkCookie(){
if(document.cookie!=''){
forwarding();
}
}
function forwarding(){
alert('Forwarding...');
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)
{
alert(xmlhttp.responseText);
}
}
var todayDate = new Date();
var weekDate = todayDate.getWeek();
a = document.cookie;
cookiename = a.substr(0,a.search('='));
cookiewert = a.substr(a.search('=')+1,a.search(';'));
if(cookiewert == '')
{cookiewert = a.substr(a.search('=')+1,a.length);}
if(cookiewert<10){
cookiewert= "0" + cookiewert;
}
for (var w=weekDate;w>0;w--){
xmlhttp.open("GET","http://pollux.dhbw-mosbach.de/cmos_extern_kurs_ext/"+cookiewert+"-"+todayDate.getFullYear()+"-"+w+".pdf",true);
xmlhttp.send();
}
}
function run(){
var d = new Date();
d = new Date(d.getTime() +1000*60*60*24*365*5); // 5 Jahre Cookie
document.cookie = 'class='+document.getElementById('class').value+'; expires='+d.toGMTString()+';';
forwarding();
}
html:
<body>
<select id="class">
<option value="on09">on09</option>
<option value="on10">on10</option>
<option value="on11a">on11a</option>
<option value="on11b">on11b</option>
<option value="on12">on12</option>
</select>
<button onclick="run()">Weiter</button>
</body>
My Forwarding Alert is shown, but then nothing more happens and I'm clueless.
If you have feedback to my code besides my problem, I would gladly accept it.
I'm off to lunch, so it'll take a while for me to respond. Thx for the help!
EDIT:
I got everything working with jQuery till the point where it could retrieve the information if the requested file exists. Nothing happens. Maybe theres an error in my code but in console it doesnt say anything. Also did I find in the jQuery API get()
http://api.jquery.com/jQuery.get/
Due to browser security restrictions, most "Ajax" requests are subject to the same origin policy; the request can not successfully retrieve data from a different domain, subdomain, or protocol.
Also this is my new forwarding():
function forwarding(){
alert('Forwarding...');
var todayDate = new Date();
var weekDate = todayDate.getWeek();
a = document.cookie;
cookiename = a.substr(0,a.search('='));
cookiewert = a.substr(a.search('=')+1,a.search(';'));
if(cookiewert == '')
{cookiewert = a.substr(a.search('=')+1,a.length);}
alert('http://pollux.dhbw-mosbach.de/cmos_extern_kurs_ext/'+cookiewert+'-'+todayDate.getFullYear()+'-'+singleWeek(weekDate)+'.pdf');
for (var w=weekDate;w>0;w--){
$.ajax({
type: 'HEAD',
url: 'http://pollux.dhbw-mosbach.de/cmos_extern_kurs_ext/'+cookiewert+'-'+todayDate.getFullYear()+'-'+singleWeek(weekDate)+'.pdf',
crossDomain: true,
success: function () {
document.location = "http://pollux.dhbw-mosbach.de/cmos_extern_kurs_ext/"+cookiewert+"-"+todayDate.getFullYear()+"-"+singleWeek(weekDate)+".pdf";
},
error: function () {
alert("Unable to connect to secure checkout.");//TODO: remove when success is working
return false;
}
});
}
function singleWeek(weekDate){
if (weekDate<10){
weekDate = "0"+weekDate;
}
return weekDate;
}
}
All I want is any method/function to give me feedback if the file exists, in this case status should send me success or error back. I could work with that if it would work...
I don't see my mistake
But that's all you do when get the answer: alert!
Is your response an html formated text? You want to redirect user or to show the content on your page?
Basicaly, you most do something with your response. Replace content of a div, for example
document.getElementById("mydiv").innerHTML = xmlhttp.responseText
or, you may change document's location(for redirect), or create a link to pdf (I am not sure how you „display” the pdf, with browser plugin, as downloadable object, or library auto-generate html from pdf and serve this instead of pdf file?)
Seems like this is impossible to achieve with JavaScript due to the same origin policy.

Getting Embed code from Youtube Pages

I am using a link that returns a youtube pages HTML. From here i would like to get the id of the video or the whole youtube embed code (as i can make one from the other)
The code I have now is not working and i am unsure why, but i am only a student learning JS for the first time. The code is then to be used in a Windows 8 Application.
//This Contains the HTML DATA from the website.
var str = response.responseText;
var str1 = str.search("http://www.youtube.com/embed/");
var str2 = str.search("\" frameborder=\"0");
var str3 = str2 - str1;
var ans = str.substr(str1 + 29, str3);
document.getElementById("frame1").src = "";
var n = str.split("=");
var url = "http://www.youtube.com/embed/" + n[1];
document.getElementById("frame1").src = url;
The Same Origin Policy prevents the host page from seeing the content of an Iframe from a different domain. This is a security feature built into the browser to prevent cross-domain scripting attacks.

Reading external plain text content into string

I have a simple CGI script that would generate plain text content on demand. For example, http://1.2.3.4/hello.cgi?name=Joe would return Hello Joe!.
How can I read this into a string in Javascript?
name = "Joe";
url = "http://1.2.3.4/hello.cgi?name=" + name;
greeting = loadThis(url);
I'm new to Javascript, so even naive approach (i.e. no need to URL escape...) will be helpful for me :)
Based on this FAQ on JavaScriper.net, I have found solution that works for me. However, the called script must be on the same machine as the caller, otherwise I get security errors from browsers.
Apparently this is what #Makkes mentioned. However, I'm perfectly happy with having the hello.cgi on the same machine for now.
Here is the code:
function loadThis(localuri) {
var oRequest = new XMLHttpRequest();
var sURL = 'http://'
+ self.location.hostname
+ localuri;
oRequest.open('GET',sURL,false);
oRequest.setRequestHeader('User-Agent',navigator.userAgent);
oRequest.send(null);
if (oRequest.status==200) return(oRequest.responseText);
else alert('Error executing XMLHttpRequest call!');
}
name = "Joe";
localuri = "/hello.cgi?name=" + name;
greeting = loadThis(localuri);
(Of course, this would not handle names with spaces or special characters correctly, but that's another story.)

Categories