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.
}
Related
I am currently creating a website where we take the data of our most visited articles of our website and list them on a specific page.
Now, the way I am collecting the data is by using PHP and I am using JS to generate the result on my page. The thing is that the coding is working but it only works if the page link ends with .html (i.e. www.website.com/article.html) but it my page link is addressed like this: www.website.com/article, the results don't show.
I tried extending the link of my js (i.e. ../result.js) but that doesn't do anything.
If you could please help me figure this out, I'd greatly appreciate it!
Thanks!
Here is a sample of the js code:
var xmlhttp;
function loadXMLDoc(url,cfunc)
{
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=cfunc;
xmlhttp.open("GET",url,true);
xmlhttp.send();
}
function mostVisitedExt()
{
loadXMLDoc('mostvisited.txt',function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
var txt=xmlhttp.responseText;
var res = txt.split('*&^');
document.getElementById("mostVisitedExt").innerHTML =
"<ul class='jrecent'><div class='jname'><p class='body'>"+res[0]+"</p> </div><div class='jcontent'><a href=http://"+res[0].toLowerCase()+".website.com"+res[20]+" class='body-link' target='_blank'>"+res[10].substring(2, res[10].length-2)+"</a><p class='body'>" +
res[21] + "</p></div></ul>" +
The mostVisitedExt function is the PHP file where it is getting the data from.
I'm currently playing around with JavaScript attempting to fetch the contents of a webpage as plain text, and dump the text to a String.
I have found many ways to do this but nothing seems to happen when I do something similar to this: (In this example I use a plain text file)
var xmlhttp;
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;
}
// As you can see I'm also spamming myself with alerts, but they also
// just return blank.
alert(xmlhttp.response);
}
xmlhttp.open("GET", "http://www.cl.cam.ac.uk/~mgk25/ucs/examples/UTF-8-demo.txt", true);
xmlhttp.send();
How do I go about doing this?
You cannot because of the Same-Origin-Policy.. otherwise each webpage could load some bank website or so.. So they (Browser vendors) implemented Same-Origin Policy.. You can access only websites which have give you access to..
just try put this in you console on stackoverflow:
open devtools while you see this site
put this into the console
jQuery.get('http://www.cl.cam.ac.uk/~mgk25/ucs/examples/UTF-8-demo.txt')
I am currently trying to refresh my page title every 10 seconds to ensure that the song info changes here:
But after the song changes, I am left with the same page title:
My JavaScript setInterval function isn't working correctly.
Here's my code (what should have worked):
<script type="text/javascript">
function songToTitle() {
document.title = "BDR | <?php echo $radio_info['now_playing']; ?>";
}
songToTitle();
setInterval(songToTitle, 10000);
</script>
<title>BDR | Loading Song Title...</title>
I don't really know what's up here.
It imports the song name correctly, but does not refresh.
Can anyone help me with this?
EDIT:
I tried using this too:
<script type="text/javascript">
function songTitle(){
var xmlhttp;
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.title.innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET","http://www.x86cam.com/wp-content/plugins/songTitle.php",true);
xmlhttp.send();
}
songTitle();
setInterval(songTitle, 5000);
</script>
It won't even load the title.
You are refreshing a static piece of information. To get new information you must use AJAX.
PHP is loaded before your browser opens it.
In other words...
<?php echo $radio_info['now_playing']; ?>
turns into
'Song Name'
so when Javascript looks at it, it only sees Song Name and is none the wiser.
AJAX Reference - complete API reference with examples down the page for you to fork off of. Your responding page also needs to be programmed to respond correctly. Usually I suggest JSON but this you can probably just use a text transfer since it's so little data.
You can send the data using POST and the PHP file can have something like this at the top:
<?php if ($_POST['songcheck'] === true) { echo $songName; return; }; ?>
PS - refreshing every 10 seconds isn't very efficient. When the song is loaded, use the song length +2 or +3 seconds for the timer instead. Much better :)
You can't use that php code in there, it's not going to execute when the function runs because PHP ran at the server, the code is now running in your browser, so once the song changes, that string is still going to be the exact same string it was when the browser asked your server for that .html file
You'll have to ask your server what the current title is using an xhr call ever X seconds and then refresh the title based on that.
I guess you should do an ajax call or listen to a some event to retrieve updated song title. The document.title = "BDR | <?php echo $radio_info['now_playing']; ?>"; string is generated on initial page load.
Okay. I figured it out.
I put this in my code:
<script type="text/javascript">
function songTitle(){
var xmlhttp;
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.title=xmlhttp.responseText;
}
}
xmlhttp.open("GET","songTitle.php",true);
xmlhttp.send();
}
songTitle();
setInterval(songTitle, 5000);
</script>
In my songTitle.php, it requests the song name from the Icecast server and displays only that.
Whenever the song changes now, it also changes the title.
I just had to integrate an XMLHTTPRequest like I did with how I displayed the song info on the page.
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.
I have a text file with a lot of values and I want to know if there is a way of loading these text file values into java script so that these values van be used by the script itself. Note I'm a newbie...
You haven't provided much context, but if we assume you mean "JavaScript running in a browser via an HTML page loaded from the same server as the text file", then you want to use the XMLHttpRequest object.
(Which is well documented in many places, so rather then providing yet another tutorial here, I'll let people use Google in the unlikely event of the above link breaking).
There are no shortage of libraries that abstract XHR. e.g. YUI, a host of tiny libraries and jQuery.
Assuming the text file is on your web server and you are loading from the browser, you could use jQuery like so:
jQuery.get('http://localhost/mytextfile.txt', function(data) {
alert(data);
});
Using XMLHttpRequest, you can achieve.
Example:
function ajaxCall() {
var xmlhttp;
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
}
else if (window.ActiveXObject) {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
else {
alert("Your browser does not support XMLHTTP!");
}
return xmlhttp;
}
xmlhttp = ajaxCall();
xmlhttp.open('GET', 'YOURFILE.txt');
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4) {
alert(xmlhttp.responseText);
}
}
with jQuery:
$('#result').load('ajax/test.txt');
Html code:
<div id="result">Text loaded here</div>
After loading the text will be replaced with the text file.