I'm executing the following code every 5 seconds, but the content appears as a block all at once, ideally it should be writing to the DOM each time it loops? So each value in the array should have its own div?
function newfunction() {
var obj;
var xmlhttp;
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
else
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
obj = JSON.parse(xmlhttp.responseText);
for (var i = 0, n = obj.length; i < n; i++) {
var divTag = document.createElement("div");
divTag.id = "div" + i;
divTag.innerHTML = obj[i];
divTag.className+="nodeclass";
document.getElementById("content").appendChild(divTag);
}
}
}
xmlhttp.open("GET","verify.php",true);
xmlhttp.send();
}
window.onload=function() {
newfunction();
setInterval("newfunction()",5000);
}
So on page load it gets some content, then it should be adding more every 5 secs.
Thanks.
I'm not seeing any setTimeout or setInterval, but I would do something like this:
function processIt(obj, i) {
var n = obj.length;
if (i < n) {
var divTag = document.createElement("div");
divTag.id = "div" + i;
divTag.innerHTML = obj[i];
divTag.className+="nodeclass";
document.getElementById("content").appendChild(divTag);
setTimeout(function () {
processIt(obj, ++i);
}, 1000);
}
}
var obj = document.getElementsByTagName("div"); // Or whatever "obj" is
processIt(obj, 0);
Updated my answer as you just updated your snippet.. What does your JSON-object from verify.php look like? Is it an object or an array or simple strings?
function retrieveContent() {
var arrayOfElements,
xmlhttp;
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
else
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
arrayOfElements = JSON.parse(xmlhttp.responseText);
insertElements(arrayOfElements);
setTimeout(retrieveContent, 5 * 1000);
}
};
xmlhttp.open("GET","verify.php",true);
xmlhttp.send();
}
function insertElements(arrayOfElements) {
var divTag,
i,
n;
for (i = 0, n = arrayOfElements.length; i < n; i++) {
divTag = document.createElement("div");
divTag.id = "div" + i;
divTag.innerHTML = obj[i];
divTag.className+="nodeclass";
document.getElementById("content").appendChild(divTag);
}
}
window.onload=retrieveContent;
jsbin snippet
Related
It will always display the "cretetion" associated link JSON as the others are overwritten. So I tried incrementing to get all of them, but it didn't work. I don't know what I am doing wrong.
var users = ["ESL_SC2", "OgamingSC2", "cretetion"];
function loadXMLDoc() {
var xmlhttp = new XMLHttpRequest();
for (var i = 0; i < users.length ; i++) {
var url = "https://wind-bow.glitch.me/twitch-api/streams/" + users[i];
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == XMLHttpRequest.DONE ) {
if (xmlhttp.status == 200) {
document.getElementById('online-id').innerHTML += (xmlhttp.responseText + "<br />");
}else if (xmlhttp.status == 400) {
console.log('There was an error 400');
}else {
console.log('Something else other than 200 was returned.');
}
}
}
xmlhttp.open("GET", url, true);
xmlhttp.send();
}
}
var onlineButton = document.getElementById('online-button-id');
onlineButton.addEventListener('click', loadXMLDoc, false);
I've fixed your code here:
https://plnkr.co/edit/VbkKc9QuVALAYLpujSdo?p=preview
First, the callback xmlhttp.onreadystatechange is overwritten every iteration of the loop so only the last element will be handled.
you should create and manage the XMLHttp object inside the loop, one for each element of your user array.
Secondy and most important you must wrap xmlhttp.onreadystatechange inside an Immediate invoked function otherwise each callback will use the last xmlhttp object then you will be getting the last result all the time, as you were saying above.
for (var i = 0; i < users.length ; i++) {
var xmlhttp = new XMLHttpRequest();
var url = "https://wind-bow.glitch.me/twitch-api/streams/" + users[i];
(function(xmlhttp){
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == XMLHttpRequest.DONE ) {
if (xmlhttp.status == 200) {
document.getElementById('online-id').innerHTML += (xmlhttp.responseText + "<br/><br/>");
}else if (xmlhttp.status == 400) {
console.log('There was an error 400');
}else {
console.log('Something else other than 200 was returned.');
}
}
}
})(xmlhttp)
xmlhttp.open("GET", url, true);
xmlhttp.send();
}
Try creating a new XMLHttpRequest for each iteration of the loop instead of re-using the same one. i.e.
function loadXMLDoc() {
for (var i = 0; i < users.length ; i++) {
var xmlhttp = new XMLHttpRequest();
...
How do I check a value in a php script for change using javascript?
I would like to do something like:
<script type="text/javascript"><!--
var innitialID = get_file_contents(lastPresentID.php); //get_file_contents(lastPresentID.php);
function myTimeout() {
var freshestID = get_file_contents(lastPresentID.php);
if(freshestID != innitialID) {
location.reload();
}
setTimeout(myTimeout, 5000);
}
window.onload = myTimeout;
</script>
the php script generates a single integer which is the last ID of a table.
Thanks!
<script type="text/javascript">
window.onload = doAjax(true);
setInterval(doAjax, 5000);
var initialID = -1, freshestID;
function doAjax(initial) {
var xmlhttp;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest(); // code for IE7+, Firefox, Chrome, Opera, Safari
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); // code for IE6, IE5
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200){
if(initial) {
initialID = xmlhttp.responseText;
} else {
freshestID = xmlhttp.responseText;
if (initialID != freshestID)
location.reload();
}
}
}
xmlhttp.open("GET", "lastPresentID.php", true);
xmlhttp.send();
}
</script>
Here we go, updated with ajax calls in there. First sets the initialId variable, then the interval code runs every 5 seconds and update the freshestId variable, and does the comparision.
EDIT: Code is now not duplicated.
The code below on load will assigns oldVal. Then using setInterval will update newVal every 5 secodns and check if newVal != oldVal.
It gets the values from lastPresentID.php using AJAX.
var oldVal = 0;
var newVal = 0;
function loadXMLDoc(old) {
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 ) {
if(xmlhttp.status == 200){
if(old)
{
oldVal = xmlhttp.responseText;
}
else
{
newVal = xmlhttp.responseText;
if(newVal != oldVal)
alert("test");
}
}
else if(xmlhttp.status == 400) {
alert('There was an error 400')
}
else {
alert(xmlhttp.status)
}
}
}
xmlhttp.open("GET", "lastPresentID.php", true);
xmlhttp.send();
}
function timeout() {
loadXMLDoc(false);
}
loadXMLDoc(true);
setInterval(timeout, 5000);
I am using JavaScript.
I amusing a setInterval timer method.
Inside that method I am changing the values of module variables.
The thing is in IE the changes to the variables are not 'saved'. But in Chrome they are.
What is the accepted practice to do what I need to do?
this is my code:
function start()
{
var myVar = setInterval(function () { GetTimings() }, 100);
}
var currentts1;
var currentts2;
var currentts3;
var currentts4;
var frameCounter;
function GetTimings() {
if (frameCounter < 1) {
frameCounter++;
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", urlTS, false);
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4) {
var nextts = xmlhttp.responseText;
var bits = nextts.split('|');
if (currentts1 != bits[0]) {
currentts1 = bits[0];
postMessage("0|" + bits[0]);
}
if (currentts2 != bits[1]) {
currentts2 = bits[1];
postMessage("1|" + bits[1]);
}
if (currentts3 != bits[2]) {
currentts3 = bits[2];
postMessage("2|" + bits[2]);
}
if (currentts4 != bits[3]) {
currentts4 = bits[3];
postMessage("3|" + bits[3]);
}
frameCounter--;
}
}
xmlhttp.send();
}
}
The variables:
currentts1
currentts2
currentts3
currentts4
frameCounter
values are not preserved...
Try this, but notice I changed the currentts* to an Array when you try to view them
function start() {
var myVar = setInterval(GetTimings, 100);
}
var currentts = [null, null, null, null];
var in_progress = 0; // clear name
function GetTimings() {
var xhr;
if (in_progress > 0) return; // die
++in_progress;
xhr = new XMLHttpRequest();
xhr.open('GET', urlTS);
function ready() {
var nextts = this.responseText,
bits = nextts.split('|'),
i;
for (i = 0; i < currentts.length; ++i)
if (currentts[i] !== bits[i])
currentts[i] = bits[i], postMessage(i + '|' + bits[i]);
--in_progress;
}
if ('onload' in xhr) // modern browser
xhr.addEventListener('load', ready);
else // ancient browser
xhr.onreadystatechange = function () {
if (this.readyState === 4 && xhr.status === 200)
ready.call(this);
};
// listen for error, too?
// begin request
xhr.send();
}
I have 2 divs.
Once 1 of the 2 divs has been selected, the 'id' of each will change to either divActive, or divInactive so the active one can be highlighted using css.
Is it possible to do this even though i already have an 'onclick' action associated with each div?
Here are my divs:
<div class="statusOption" onclick="loadXMLDoc('indexEveryone')">Everyone, everywhere</div>
<div class="statusOption" onclick="loadXMLDoc('indexFav')">Favourites Only</div>
Here is my current javascript:
<script>
function loadXMLDoc(pageName)
{
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("centreCont").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","../home/" + pageName + ".php",true);
xmlhttp.send();
}
</script>
If you don't want to use jQuery you don't have to. Here is a pure javascript version. Notice it toggles an active class, not an ID.
window.onload = function () {
var everyone = document.getElementById('everyone'),
favorites = document.getElementById('favorites');
everyone.onclick = function() {
loadXMLDoc('indexEveryone');
var myClasses = everyone.className,
otherClasses = favorites.className;
if (myClasses.contains("active"))
{
everyone.className = 'statusOption';
}
else if (otherClasses.contains("active")) {
everyone.className = 'statusOption active';
favorites.className = 'statusOption';
}
else {
everyone.className = 'statusOption active';
}
}
favorites.onclick = function() {
loadXMLDoc('indexFav');
var myClasses = favorites.className,
otherClasses = everyone.className;
if (myClasses.contains("active"))
{
favorites.className = 'statusOption';
}
else if (otherClasses.contains("active")) {
favorites.className = 'statusOption active';
everyone.className = 'statusOption';
}
else {
favorites.className = 'statusOption active';
}
}
function loadXMLDoc(event) {
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("centreCont").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","../home/" + pageName + ".php",true);
xmlhttp.send();
}
}
Edit to accommodate requests in comments: If you always want one to be active it shortens the code a lot. Here is the updated code. Just make sure you give everyone the active class to start in your HTML
window.onload = function () {
var everyone = document.getElementById('everyone'),
favorites = document.getElementById('favorites');
everyone.onclick = function() {
loadXMLDoc('indexEveryone');
var otherClasses = favorites.className;
if (otherClasses.contains("active")) {
everyone.className = 'statusOption active';
favorites.className = 'statusOption';
}
}
favorites.onclick = function() {
loadXMLDoc('indexFav');
var otherClasses = everyone.className;
if (otherClasses.contains("active")) {
favorites.className = 'statusOption active';
everyone.className = 'statusOption';
}
}
function loadXMLDoc(pageName) {
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("centreCont").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","../home/" + pageName + ".php",true);
xmlhttp.send();
}
}
Yes, you can have more that one function call in onclick.
However, you should not change the id of the elements, but add or remove a class instead.
Also, you should really consider using something like jQuery, which would make your code much more concise:
<div id="everyone" class="statusOption" onclick="loadXMLDoc('indexEveryone')">Everyone, everywhere</div>
<div id="favorites" class="statusOption" onclick="loadXMLDoc('indexFav')">Favourites Only</div>
<script>
$(document).ready(function(){
$('#everyone').on('click', loadXMLDoc, 'indexEveryone');
$('#favorites').on('click', loadXMLDoc, 'indexFav');
$('div.statusOption').on('click', function(){
$('div.statusOption').removeClass('active');
$(this).addClass('active');
});
});
function loadXMLDoc(event)
{
$.ajax({
url: "../home/" + event.data + ".php",
type: "GET",
success: function(result){ $("#centreCont").html(result); }
});
</script>
What I'm trying to do is limit the options of one select box based on what the user chooses in a prior select box. It works perfectly in Chrome and Firefox, but in IE 10 the only thing that shows up is the text "Not Found". I'm not sure, but my guess is that something is going wrong in request.status. What it is, however, I have no idea.
function prepForms() {
for (var i = 0; i<document.forms.length; i++) {
var thisform = document.forms[i];
var departCity = document.getElementById("departcity");
departCity.onchange = function() {
var new_content = document.getElementById("ajaxArrive");
if (submitFormWithAjax(thisform, new_content)) return false;
return true;
}
}
}
function getHTTPObject() {
if (typeof XMLHttpRequest == "undefined")
XMLHttpRequest = function() {
try { return new ActiveXObject("Msxml2.XMLHTTP.6.0"); }
catch (e) {}
try { return new ActiveXObject("Msxml2.XMLHTTP.3.0"); }
catch (e) {}
try { return new ActiveXObject("Msxml2.XMLHTTP"); }
catch (e) {}
return false;
}
return new XMLHttpRequest();
}
function submitFormWithAjax(whichform, thetarget) {
var request = getHTTPObject();
if (!request) {return false;}
var dataParts = [];
var element;
for (var i = 0; i<whichform.elements.length; i++) {
element = whichform.elements[i];
dataParts[i] = element.name + "=" + encodeURIComponent(element.value);
}
var data = dataParts.join("&");
request.open("POST", "flightlocationfilter.asp#ajaxArrive", true);
request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
request.onreadystatechange = function() {
if (request.readyState == 4) {
if (request.status == 200 || request.status == 0) {
var matches = request.responseText.match(/<div id="ajaxArrive">([\s\S]+)<\/div>/);
if (matches.length > 0) {
thetarget.innerHTML = matches[1];
} else {
thetarget.innerHTML = "<p>--Error--</p>";
}
} else {
thetarget.innerHTML = "<p>" + request.statusText + "</p>";
}
}
};
request.send(data);
return true;
};
Edit: After walking through with the IE Developer Tools, it looks like the request.readyState is not moving beyond 1 to 4.