external java script file not working - javascript

I'm doing a project for school and so far it's been a lot of copy this script and paste it here to make things "work". I don't really have any idea what I'm doing besides comparing one line of code to another and looking for the differences.
I've got javascript that is returning some values to me and it works fine when it's in a simple webpage format but when I insert it into a more complicated page it stops working.
At the very end of the page it should give a line of numeric values and be updated every 1000 milliseconds but what happens is it just sits there displaying Temp()...
I've checked the data.xml and those values are being updated when I push buttons and stuff on my PIC protoboard.
I'm using the same ajax.js file for both the simple webpage and the complicated page.
I'm thinking it is something simple like a missed </p> or </div> tag but my eyes don't seem to see it.
Could some take a look at the code and see what I've missed? Thanks!
ajax.js
var xhr;
function getXMLHttpRequest(){
try { return new ActiveXObject("Msxm12.XMLHTTP"); } catch(e){};
try { return new ActiveXObject("Microsoft.XMLHTTP"); } catch(e){};
try { return new XMLHttpRequest(); } catch(e){};
return null;
}
function parseHttpResponse(){
if(xhr.readyState == 4){
if(xhr.status == 200){
document.getElementById("T0").innerHTML=xhr.responseText;
}
else
{
}
}
}
function getTemp(){
xhr = getXMLHttpRequest();
xhr.open("GET", "data.xml", true);
xhr.onreadystatechange = parseHttpResponse;
xhr.send(null);
}
setInterval("getTemp()", 1000);
Simple webpage - this works great
<html>
<head><title>Ajax test - index1</title>
<script src="ajax.js" type="text/javascript">
</script>
</head>
<body onload="getTemp();">
<h2>Headline</h2>
<p>Paragraph</p>
<div id='T0'>Loading Temp0...</div>
</body>
</html>
"Complicated" webpage - when this is used I get no joy
<!DOCTYPE html>
<html>
<head>
<title>Elex267-Webpage</title>
<script src="ajax.js" type="test/javascript">
</script>
<link rel="stylesheet" href="myStyle.css" type="text/css" >
</head>
<body onload="getTemp();">
<!-- Banner at Top of Page ***********************************-->
<div style="background-color:blue; color:white;font-size:30px;">
<img src="Pics/camosun-white.png" alt="CamosunPNG" width="200" height="70" align="left">
<div align="center"style="margin-left:50%">Elex 267 Web Demo
<br>
Microchip TCP/IP Stack v3.02</div>
</div>
<!--*********************************************************-->
<!--NavBar Code *********************************************-->
<div class="nav">
<ul>
<li>Home</li>
<li>Features</li>
<li>About</li>
</ul>
</div>
<!--***************************************************-->
<p>
Welcome to the Elex 267 Demo Web Server for [Name Here].<br>
</p>
<p>
This web page is being run on the NM101 NorthMicro Pic Prototype Board with the LCD/Keypad and Network modules.
<br>
This web page refreshes the data every 3 seconds.
</p>
<center>
<img border="5" src="http://www.northmicro.com/GFX/nm110nm120onproto.jpg" alt="NM110 Proto Pic" width="200" height="200" >
</center>
<br>
<div id="feedback" style="width:500px;float:left;">
Pot RA0: 1022 <br>
Pot RA1: 223
<br><br>
Switch RA2: <img src="Pics/SwitchUp.gif" alt="SwitchOff" width="20" height="20" align="top">
<br><br>
LEDs: RB6 <img src="Pics/LEDOff.gif" alt="LED_Off" width="20" height="20" align="top"> RB5 <img src="Pics/LEDOn.gif" alt="LED_On" width="20" height="20" align="top">
</div>
<div id="input" style="width=50%;margin-left:50%;">
<b>Commands</b><br>
<button align="left" type="button" onclick="alert ('RB5 Activated')">Toggle RB5</button>
<br>
<button align="left" type="button" onclick="alert ('RB6 Activated')">Toggle RB6</button>
</div>
<br><br>
<div id='T0'>Loading Temp0...</div>
</body>
</html>

setInterval("getTemp()", 1000);
does not make sense at this line, and it might be the cause of your problems. This call causes getTemp to be called every second, starting from after this call as returned. In the getTemp function you are reusing the xhr variable, creating a new XMLHttpRequest instance each time. That alone is not necessarily a problem (aside from the "Msxm12.XMLHTTP" which appears to be wrong; should probably be "Msxml2.XMLHTTP").
But in each call of getTemp you are issuing a new request, regardless if the previous request has received a response (the third argument being true means asynchronous request-response handling). Consider this: The readystatechange listener might not have been called (or its readyState == 4 part has not be executed) because the client is waiting for the server to respond. Now your one-second timer kicks in, calls getTemp again and thus overwrites the xhr value that is to be used in the listener code. There is a closure, xhr is a bound variable, and therefore there is a race condition already.
Further, an HTTP client SHOULD NOT (per RFC 2616), and a well-designed Web browser will not, keep more than a specified number of persistent HTTP connections (default: 2 to 8) open to the same server or proxy. So the more complex the document, and the more resources need to be loaded in parallel, the more likely that this approach will fail.
You should remove the setInterval(…) call and add a getTemp() call below the line where you update the innerHTML property (when the request was successful, status == 200), so that only then a new request is issued. You should at least wait for the readyState to become 4 (FINISHED) before you issue a new request. Since you want to wait one second before the next call, use window.setTimeout("getTemp()", 1000).
It should help your understanding if you pretty-print that code, that is, indent function body and block content with a reasonable amount of white-space, and add some white-space, for example between ) and {. There are editors like Eclipse JavaScript Development Tools which can automate much of the code formatting.
Afterwards you should learn to use a debugger (use Firebug for Firefox, newer versions of other browsers have one built-in) and set breakpoints in your code, particulary in getTemp and parseHttpResponse. Step through the code (caveat: step over send(), then continue so that execution halts at the breakpoint in parseHttpResponse) to see what is going on. Good luck.

Related

jQuery Load XML and Refresh Based on XML Variable

I am building a player for an online radio station. The stream is providing an XML file that displays the current song information. This XML file is hosted on the stream server which is NOT the server the website is running on.
Here is a sample of whats in the XML. Lets pretend it comes from http://randomserver/station.xml
<playlist>
<stationCallSign>KCXR</stationCallSign>
<programType>PGM</programType>
<mediaType>AUD</mediaType>
<title>Break Free</title>
<artist>Decyfer Down</artist>
<album>End of Grey</album>
<cover>
http://cdnrf.securenetsystems.net/file_radio/album_art/O/1/5/51Oo0rBqATL.jpg
</cover>
<duration>199</duration>
<campaignId/>
<fileId/>
<programStartTS>30 Sep 2015 17:48:22</programStartTS>
<adBlockPos>1</adBlockPos>
</playlist>
I need to pull that data to display it on the webpage and then refresh everything based on how many seconds are in the "duration" field. Essentially refresh all of this when the song changes.
Here is the html output I need.
<div id="playerDiv" class="player-div" style="display: block;">
<div id="album-art">
<img id="now-playing-album-art" src="http://cdnrf.securenetsystems.net/file_radio/album_art/e/1/5/51eeZTxMYuL.jpg" class="player-div-img cP" width="250" height="250" title="">
</div>
<div id="now-playing" class="now-playing tS">
<span id="now-playing-title" class="menuHeader f15em">Lights Out</span> - <span id="now-playing-artist">Silverline</span>
<div id="now-playing-album">Lights Out</div>
</div>
[playercode]
</div>
I was hoping to use the mobile jquery so that this functions well on mobile devices.
It sounds like you might need to do a little more research into ajax requests.
setTimeout(function() {
jQuery.ajax('http://randomserver/station.xml', {
success: function() { //Parse xml and update document },
error: function() { //handle error }
}
}, songDuration);
With jQuery you can easily download your xml file and update the song
In the above code setTimeout(callback,timeInMillis) allows you to set a time in milliseconds for the callback to occur. The callback then makes an XMLHTTPRequest to the url of your choice and then updates the page if it is successful in getting the page.
You can use the default Javascript XML parser to parse the response you get from the server.
Resources Used:
https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers/setTimeout
http://api.jquery.com/jquery.ajax/

function variable not passing to global variable

Good day all, I've two pages of php file and an external javascript file. I want to pass a selected radio button's value to a jquery global variable so that I can view the div element which has the same id as selected radio button's value. Whenever I click PLAY! button I don't see my div element on the next page. Here are my codes:
player-choose.php script:
<head>
<script src="js/jquery-1.9.1.min.js"></script>
<script src="js/mycustom.js"></script>
</head>
<body>
<div id="player-list">
<input type="radio" name="player" value="fighter" id="fighter-radio"><label for="fighter-radio"><img src="images/heroes/fighter-01.png" width="74" height="70"></label>
<input type="radio" name="player" value="pakhi" id="pakhi-radio"><label for="pakhi-radio"><img src="images/heroes/pakhi.png" width="95" height="70"></label>
</div>
<button id="play">PLAY!</button>
</body>
mycustom.js script:
var playerID;
function start(){
spawnhero();
}
$(function(){
$("#play").click(function(){
window.location.href = 'index.php';
playerID = $('input[name=player]:checked').val();
});
})
function spawnhero () {
$("#content").append($("<div>").attr('id', playerID));
}
index.php script:
<head>
<script src="js/jquery-1.9.1.min.js"></script>
<script src="js/mycustom.js"></script>
</head>
<body onload="start()">
<div id="content">
<div id="galaxy"></div>
</div>
</body>
It's a very simple thing but I don't know why it's not working. Am I doing something wrong here? Please if anyone finds a solution enlighten me. Tnx!
If you're moving to a new page (window.location = ...), you'll need some slightly more complicated way of transferring information between those pages - for the most part, HTTP/HTML is "stateless", with the exception of technologies like cookies. JavaScript variables get wiped out entirely - it's actually re-parsing the entire JQuery library on each new page (not to say that's something to avoid)
For a video game, as long as player information doesn't include server components (I could be wrong) my recommendation would be saving player information in sessionStorage.
https://developer.mozilla.org/en-US/docs/Web/Guide/API/DOM/Storage
However, if this is a server-based game in which your choice of player matters beyond the local computer, you'd likely want to send the player ID to the server, either by structuring the page request differently:
window.location.href = 'index.php?playerId=' + playerId;
Or by POSTing the data as a form; most easily accomplished by structuring your submit button as an <input type="submit">, and wrapping all your <input> elements in a <form method="POST"> object.
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/form
From there, your server software could write the second page's response out differently based on the given information - you can even customize what JavaScript is written inside of a <script> tag using PHP directives.
var playerId = "<?php print($_POST['playerId']); ?>";
Hopefully that helps get you started.
global variables are not persistent across pages. Once you load your index.php , it will have the new global scope(window variable).
I suggest passing a parameter.
$("#play").click(function(){
playerID = $('input[name=player]:checked').val();
window.location.href = 'index.php?id=' + playerID;
});
afterward, inside your index.php script , read the parameter and assign accordingly.
Alternative solution is you could you use JavaScript or jQuery cookie or localstorage. You can get/set values across page loads/redirects but these are not passed to server.
jQuery Cookie
var playerID = $('input[name=player]:checked').val();
$.cookie("playerId", playerID);
LocalStorage
var playerID = $('input[name=player]:checked').val();
localStorage.setItem("playerId", playerID);

login screen page getter and setter

Can anyone help me? Basically I need a page that asks for a user's name on the first page of my website. This will then allow you to the home page. How can I use the person's name on the home page at the minute the home page is being over write with just a white page with what ever the person inputs on the screen before?
Login page code
<link href="CSS.css" rel="stylesheet" type="text/css" />
<div id="image">
<img src="../images/logo.jpg"/>
</div>
<div id="login">
<script type="text/javascript">
// Called on form's `onsubmit`
function tosubmit() {
// Getting the value of your text input
var mytext = document.getElementById("mytext").value;
// Storing the value above into localStorage
localStorage.setItem("mytext", mytext);
return true;
}
</script>
</head>
<body>
<center>
<!-- INLCUDING `ONSUBMIT` EVENT + ACTION URL -->
<form name="myform" onsubmit="tosubmit();" action="index.html">
<input id="mytext" type="text" name="data">
<input type="submit" value="Submit">
</form>
</div>
</body>
</html>
the home page code
<script>
// Called on body's `onload` event
function init() {
// Retrieving the text input's value which was stored into localStorage
var mytext = localStorage.getItem("mytext");
// Writing the value in the document
document.write(" "+mytext);
}
</script>
<body onload="init();">
</body>
The page is being overwritten by document.write. You shouldn't use it,
see the warning in the spec:
Warning! This method has very idiosyncratic behavior. In some cases,
this method can affect the state of the HTML parser while the parser
is running, resulting in a DOM that does not correspond to the source
of the document (e.g. if the string written is the string
"<plaintext>" or "<!--"). In other cases, the call can clear the
current page first, as if document.open() had been called. In yet more
cases, the method is simply ignored, or throws an exception. To make
matters worse, the exact behavior of this method can in some cases be
dependent on network latency, which can lead to failures that are very
hard to debug. For all these reasons, use of this method is strongly
discouraged.
Your case is this one:
In other cases, the call can clear the current page first, as if document.open() had been called.
To avoid that, you can use DOM methods:
document.body.appendChild(document.createTextNode(mytext));

Javascript global variable does not persist when navigate to another page (which also uses same js file) [duplicate]

This question already has answers here:
Persist variables between page loads
(4 answers)
Closed 7 years ago.
I have shared js code like this in angus.js
var g_colour;
function getcolour() {
return g_colour;
}
function setcolour(colour) {
g_colour = colour;
}
Which is accessed by html pages 1 and 2 like this:
1.html:
<html>
<head>
<title>Global javascript example</title>
</head>
<body>
Page2
<script src="angus.js"></script>
<form name="frm">
<input type="button" value="Setblue" onclick="setcolour('blue');" />
<input type="button" value="Setyellow" onclick="setcolour('yellow');" />
<input type="button" value="getcolour" onclick="alert(getcolour());" />
</form>
</body>
</html>
2.html:
<html>
<head>
<title>Global javascript example page 2</title>
</head>
<body>
Page1
<script src="angus.js"></script>
<form name="frm">
<input type="button" value="Setblue" onclick="setcolour('blue');" />
<input type="button" value="Setyellow" onclick="setcolour('yellow');" />
<input type="button" value="getcolour" onclick="alert(getcolour());" />
</form>
</body>
</html>
If I set a colour in one page and navigate to page 2, and THEN access the colour, it returns undefined. ie I it seems that a new instance of g_colour is created on loading a new html page.
I want to be able to access a sort of top-level variable which I can set in page 1 and access in page 2. How can I do that in Javascript?
JS variables never have been persistent, but there are two ways around this:
Cookies
Storage
Cookies are supported in all but the most ancient browsers, but they can be very unwieldly and difficult to use. On top of that, your browser sends cookies to the server with every pageload, so if it's only used by JavaScript then it's very inefficient.
Instead, you should probably look at the Storage option.
Saving an item is as simple as localStorage.itemname = value; Reading is as easy as localStorage.itemname, and deleting is as literal as delete localStorage.itemname
These values are saved across pageloads, but not sent to the server.
Use localStorage:
localStorage.setItem('name', 'value');
var something = localStorage.getItem('name');
setItem on your first page, then getItem on your second.
The localStorage persists across pageloads, as opposed to "normal" JavaScript variables.
"Normal" variables are initialized as soon as the JS file is loaded (And runs), but are destroyed when the file unloads, so when the user leaves a page.
You could also use Cookies, but they're a bit of a pain to work with in JS, since they're stored in a string like:
'name=value; name1=value1; name2=value2';
Each page request will request the script and execute its copy of it, even if the request stops at the client because of the cache, the current page still executes it from scratch. They are working with the same code, yes, but different instances (i.e. you have two copies of that variable in two different contexts).
The problem is that your page 1 is loading the JavaScript file and your page 2 is loading it again therefore whatever you have set in a variable on that JS file will be lost when page 2 is loaded since page 2 will initialize again the JS file. If you want you can use cookie to store the value or if it simple to you combine page 1 and page 2 but put them in a different div and show/hide the div according to your logic.

jQuery $.ajax response empty, but only in Chrome

I've exhausted every avenue of research to solve this one so hopefully someone else will think of something I just didn't.
Relatively straight forward setup, I have a html page with some javascript that makes an ajax request to a URL (in the same domain) the java web app in the background does its stuff and returns a partial html page (no html, head or body tags, just the content) which should be inserted at a particular point in the page.
All sounds pretty easy and the code I have works in IE, Firefox and Safari, but not in Chrome. In Chrome the target element just ends up empty and if I look at the resource request in Chromes developer tools the response content is also empty.
All very confusing, I've tried a myriad of things to solve it and I'm just out of ideas. Any help would be greatly appreciated.
var container = $('#container');
$.ajax({
type: 'GET',
url: '/path/to/local/url',
data: data('parameters=value&another=value2'),
dataType: 'html',
cache: false,
beforeSend: requestBefore,
complete: requestComplete,
success: requestSuccess,
error: requestError
});
function data(parameters) {
var dictionary = {};
var pairs = parameters.split('&');
for (var i = 0; i < pairs.length; i++) {
var keyValuePair = pairs[i].split('=');
dictionary[keyValuePair[0]] = keyValuePair[1];
}
return dictionary;
}
function requestBefore() {
container.find('.message.error').hide();
container.prepend('<div class="modal"><div class="indicator">Loading...</div></div>');
}
function requestComplete() {
container.find('.modal').remove();
}
function requestSuccess(response) {
container.empty();
container.html(response);
}
function requestError(response) {
if (response.status == 200 && response.responseText == 'OK') {
requestSuccess(response);
} else {
container.find('.message.error').fadeIn('slow');
}
}
All of this is executed in a $(document).ready(function() {});
Cheers,
Jim
#Oleg - Additional information requested, an example of the response that the ajax call might receive.
<p class="message error hidden">An unknown error occured while trying to
retrieve data, please try again shortly.</p>
<div class="timeline">
<a class="icon shuttle-previous"
rel="max_id=16470650733&page=1&q=something">Newer Data</a>
<a class="icon shuttle-next"
rel="max_id=16470650733&page=3&q=something">Older Data</a>
</div>
<ol class="social">
<li class="even">
<div class="avatar">
<img src="sphere_normal.gif"/>
</div>
<p>
Some Content<br/>
<span class="published">Jun 18, 2010 11:29:05 AM</span> - <a
target="_blank" href="">Direct Link</a>
</p>
</li>
<li class="odd">
<div class="avatar">
<img src="sphere_normal.gif"/>
</div>
<p>
Some Content<br/>
<span class="published">Jun 18, 2010 11:29:05 AM</span> - <a
target="_blank" href="">Direct Link</a>
</p>
</li>
</ol>
<div class="timeline">
<a class="icon shuttle-previous"
rel="max_id=16470650733&page=1&q=something">Newer Data</a>
<a class="icon shuttle-next"
rel="max_id=16470650733&page=3&q=something">Older Data</a>
</div>
I just resolved a similar problem, and thought I'd post my solution in case it's of use for anyone else.
Only Firefox and Chrome were showing an empty ajax response, so it seemed to be a cross domain problem, yet everything was on the same domain.
It turned out that the 'www.', which I had superfluously and stupidly hard-coded into my ajax url was to blame. Had I been using a relative path, everything would've been fine.
I had my test site open at that particular moment as "http://domain.com", with no 'www.', so Firefox and Chrome treated it as a different domain. Navigating to "http://www.domain.com" resulted in the ajax call working in all browers.
So, given that you wrote:
url: '/path/to/local/url'
..as is the convention when we don't want to disclose our paths, I couldn't help but wonder if in fact you had written an absolute path, just as I had...?
Chrome stepped onto its own foot with local files security, so no AJAXing local files with relative paths:
http://code.google.com/p/chromium/issues/detail?id=47416
I took your source code and set up a quick test scenario but fail to replicate your problem. It is working for me just fine in both Firefox (3.6.3) and Chrome (5.0.375.70). I tried it both locally and on a remote server.
So your code is most likely not to blame. But I would also think that it's not generally a Chrome related issue.
Other people seem to have come across this though. Changing the content type had no effect in my test scenario though. It even works when I set the Content-Type to image/jpeg.
On the JQuery forums someone indicated differing behavior depending on whether he runs his application locally or on a remote server. If this was the case for you, you could compare HTTP request and response headers to track down the issue.

Categories