Forwarding website to pdf file on another server using JavaScript - 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.

Related

Selenium IDE - TypeError: document.getElementById(..) is null

The situation is, that I want to use "runScript" in order to send a xmlhttprequest in the beginning when the website gets opened, find an element in the responseText, see if a specific textcontent is present and if so, I want to click on that element.
I am not allowed to show you the source of the website, but I hope your still able to (maybe) find the mistake.
My script:
javascript{
var req = new XMLHttpRequest();
req.addEventListener("load", function(event) {
if(req.status >= 200 && req.status < 300)
{
var parser = new DOMParser();
var xmlDoc = parser.parseFromString(req.responseText, "text/html");
if(document.getElementById("application_widgets__0_selectedUserLanguage_label").childNodes[0].textContent=="English")
{
document.getElementById("application_widgets__0_selectedUserLanguage_label").parentNode.click()
}
}
});
req.open("GET", "..............................");
req.send();
}
I've already tested it in the console of firebug before putting it into the Selenium IDE and it works perfectly. But I always get the same exception when running it in Selenium IDE:
My question is: why does it work in firebug but not in selenium IDE and what did I do wrong?
no there's no iframe
Thanks for the answers in advance! :)
This indicates that the page is not fully loaded yet when you call document.getElementById(). You need to wrap your code in a window.addEventListener("load", function() { ... }); to get it to work.

what is wrong with my javascript structure

I am really new on javascript. I want to read xml from an url and want to parse it on html. I have html and javascript codes like that:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<script>
function loadXMLDoc(filename)
{
if (window.XMLHttpRequest)
{
xhttp=new XMLHttpRequest();
}
else // code for IE5 and IE6
{
xhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xhttp.open("GET",filename,false);
xhttp.send();
return xhttp.responseXML;
}
xmlDoc=loadXMLDoc("http://www.w3schools.com/dom/books.xml");
x=xmlDoc.getElementsByTagName("title")[0];
y=x.childNodes[0];
document.write(y.nodeValue);
</script>
</body>
</html>
What is wrong ? thanks
This is the standard method to do this task:
Since people keep going along the path of trying to use cross domain for something other than JSONP... IT WILL NOT WORK!
The following code below is an example of what will work, as your server is allowed to get content from other network locations being its more controlled.. Your browser on the other hand can only receive JSONP or PLAIN TEXT... Most google results should explain this as well..
YOUR ONLY OPTION
Is to use a PROXY of some form to obtain what your trying to access, So you only have three choices here.
Use JSONP or Plain Text
Use a Proxy or some other method that is local to your server/website/script/page
Keep trying to use examples posted here after being told cross domain rules apply.
JAVASCRIPT:
function loadXMLDoc(sURL) {
$.post( "myproxy.php", { requrl: sURL }).done(function( data ) {
alert(data);
console.log(data);
document.write(data);
});
}
PHP: myproxy.php
<?php
header('Content-Type: application/xml; charset=utf-8');
$file = file_get_contents($_POST['requrl']);
echo $file;
?>
Please note that is you plan to use this with other types of content then you will need to change/remove the header line.
YOUR BROWSER ALLOWS YOU TO AJAX XML FROM OTHER WEBSITES
If this is the case, then you need to replace or update your web browser..
THE ABOVE SOLUTION IS NOT COMPLEX
This is virtually copy and paste code ready to go, The JS function will return the result/data/content in the three most know ways...
The PHP script is a copy and paste as well.. So if you have PHP installed.
All you would need to do is create a new text file in the same location as your html document and name it as "myproxy.php" and this example will work.
This is a proper XmlHttpRequest with a callback function to handle your XML:
<!DOCTYPE html>
<html>
<head></head>
<body>
<script type="text/javascript">
function loadXMLDoc(url){
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
callbackFunction(xmlhttp.responseText);
}
}
xmlhttp.open("GET", url, true);
xmlhttp.send();
}
function callbackFunction(response){
if (window.DOMParser){ // Non IE
var parser = new DOMParser();
var xml_doc = parser.parseFromString(response,"text/xml");
}else{ // Internet Explorer
var xml_doc = new ActiveXObject("Microsoft.XMLDOM");
xml_doc.async = false;
xml_doc.loadXML(response);
}
// Do something with your 'xml_doc' object variable here
console.log(xml_doc) // Debugging only.. to see the XML in the browser console for your own reference
var x = xml_doc.getElementsByTagName("title")[0]
var y = x.childNodes[0];
document.write(y.nodeValue);
}
// Call the function to begin code execution
loadXMLDoc('http://www.w3schools.com/dom/books.xml')
</script>
</body>
</html>
This is working code so you can just erase what you have and put this directly in place of it. Good luck!
If you're planning on hosting the file on your own server to access via XHR, the code I offered is intended for that. If w3schools.com had a 'Access-Control-Allow-Origin: *' header on the XML file your are requesting, it would also work. But they don't. So you need to have the XML file in a place where your browser's security will let you access it (same domain origin as your webpage). Otherwise your browser will continue to block the resource with a 'cross-origin-request-blocked' error in the console.

Get text from a link in javascript

I am trying to get text from a service on the same server as my webserver. The link is something like this:
http://<OwnIPadres>:8080/calc/something?var=that
This is my code:
function httpGet(theUrl)
{
alert(theUrl);
var doc = new XMLHttpRequest();
doc.onreadystatechange = function() {
if (doc.readyState == XMLHttpRequest.DONE) {
alert("text: " + doc.responseText );
document.getElementById('ctm').text = doc.responseText;
}
}
doc.open("get", theUrl);
doc.setRequestHeader("Content-Encoding", "UTF-8");
doc.send();
}
The url that i print in my first alert is the good one if i test in my browser, it is an html page with a table in it. But the alert of my text is empty? Is it a problem that the text is html?
Actually, its quite ok that your 'text' is 'html'. The problem is that using a different port counts as cross-site scripting. Therefore, your XMLHttpRequest is being stopped by the browser before it actually reaches your page across port 8080.
I'm not sure what else you're doing before and around this code snippet, but you could try an iframe call to your url to get your data, or you could add an
Access-Control-Allow-Origin: http://:8080/
in your header (however that will only get you the most modern browsers).
Finally, you could pull in a JS framework like JQuery which could help you with pulling in this service data.

Trying to make my first ajax, but stuck on javascript

I'm trying to make my first AJAX web tool. Javascript is my kryptonite though. I'm not sure where I've gone wrong, but any help would be great!
function MyFunc() {
var xmlhttp;
var type = getElementById("type");
var agency = getElementById("agency");
var location = document.getElementById("location");
location = location.options[location.selectedIndex].value;
type = type.checked;
agency = agency.checked;
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","view.php?location=" + location + "&type=" + type + "&agency=" + agency,true);
xmlhttp.send();
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
document.getElementById("list").innerHTML = xmlhttp.responseText;
}
}
// setTimeout(refresh, 300000);
}
You can see the "live" site at tol1dc.homedns.org On the "Job Searcher" page (http://tol1dc.homedns.org/modules/navigator/navto.php?unique_ID=3)
Now I'm really clueless about Javascript. I don't know if this should be in the head of the document, or if it's ok in the body?
Also you can see the "setTimeout" I'm trying to get the page to auto reload the table every 5 minutes.
I don't really know what problem I'm getting either, just that it's not responding. I can't see a connect attempt on my server logs, I couldn't get the button to even do a document.write("hello world");
Your help would be greatly appreciated if you can get me on the right track!
Thanks
A syntax error is occurring on line 38.
Do you mean?
var type = document.getElementById("type");
var agency = document.getElementById("agency");
Noting the variable assignment and calling the getElementById function of the document object.
The location of the code in the markup is fine, but it might be cleaner to either place it at the bottom of the body (last thing before ) or in the head. Also, wrapping it in window's on load event:
window.addEventListener('load', function() {
// Grab input and AJAX.
}

Javascript works great locally, but not on my server

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.

Categories