I want the XML doc to get read on a fixed interval, and avoid full page refresh everytime it looks for updates. The code below which is commented out works, but messes up the JQuery cycle. (which is based on http://buildinternet.com/project/totem/ )
Need some help with this.
//function refresh()
// {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
myFunction(this);
}
};
xhttp.open("GET", "drift.xml", true);
xhttp.send();
// }
function myFunction(xml) {
var xmlDoc = xml.responseXML;
var item = xmlDoc.getElementsByTagName("item");
var itemlength = item.length;
var i;
var html='';
var today = new Date();
var aktuella = [];
$("#wrapper").append('<ul id=\'wrap\'></ul>');
for (i = 0; i < itemlength; i++) {
var postDate = xmlDoc.getElementsByTagName("expires")[i].childNodes[0].nodeValue;
var date = postDate.substring(8, 10);
var month = postDate.substring(5, 7);
var year = postDate.substring(0, 4);
var expiredDate = new Date(year, month - 1, date);
if (expiredDate > testDate) {
aktuella.push(i);
}
};
if (aktuella.length == 0 ) {
var none = "<p>Info</p>";
$('#wrapper').prepend(none);
};
if (aktuella.length == 1) {
var expires = '<p>' + xmlDoc.getElementsByTagName("expires")[0].parentNode.childNodes[1].textContent + '</p>';
$('#wrapper').prepend(expires);
};
if (aktuella.length > 1) {
for (i = 0; i < aktuella.length; i++) {
var expires = '<li id="' + i + '">' + xmlDoc.getElementsByTagName("expires")[i].parentNode.childNodes[1].textContent + ' - Se Driftinfo</li>';
$('#wrap').prepend(expires);
};
};
$(function(){
$('#wrap').totemticker({
row_height : '120px',
next : '#ticker-next',
previous : '#ticker-previous',
stop : null,
start : null,
mousestop : true,
});
});
}
// refresh();
// setInterval("refresh()", 5000);
</script>
Simple:
Add this ti your script:
setInterval(function(){
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
myFunction(this);
}
};
}, milliseconds);
try now with this. There where a mistake. funtion instead function and the interval after the function to call
function myFunction(xml) {
var xmlDoc = xml.responseXML;
var item = xmlDoc.getElementsByTagName("item");
var itemlength = item.length;
var i;
var html='';
var today = new Date();
var aktuella = [];
$("#wrapper").append('<ul id=\'wrap\'></ul>');
for (i = 0; i < itemlength; i++) {
var postDate = xmlDoc.getElementsByTagName("expires") [i].childNodes[0].nodeValue;
var date = postDate.substring(8, 10);
var month = postDate.substring(5, 7);
var year = postDate.substring(0, 4);
var expiredDate = new Date(year, month - 1, date);
if (expiredDate > testDate) {
aktuella.push(i);
}
};
setInterval(function(){
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
myFunction(this);
}
};
xhttp.open("GET", "drift.xml", true);
xhttp.send();
}, milliseconds);
Here is the site without any attempt to refresh the ajax:
http://socialsiberia.com/dash/test1.html
And here is the weird behaviour that occurs when I add the code below:
http://socialsiberia.com/dash/test2.html
setInterval(function(){
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
myFunction(this);
}
};
xhttp.open("GET", "test.xml", true);
xhttp.send();
}, 5000);
var xhttp = new XMLHttpRequest();
function myFunction(xml) {
var xmlDoc = xml.responseXML;
var item = xmlDoc.getElementsByTagName("item");
var itemlength = item.length;
var i;
var html='';
var today = new Date();
var aktuella = [];
$("#wrapper").append('<ul id=\'wrap\'></ul>');
for (i = 0; i < itemlength; i++) {
var postDate = xmlDoc.getElementsByTagName("expires")[i].childNodes[0].nodeValue;
var date = postDate.substring(8, 10);
var month = postDate.substring(5, 7);
var year = postDate.substring(0, 4);
var expiredDate = new Date(year, month - 1, date);
if (expiredDate > testDate) {
aktuella.push(i);
}
};
if (aktuella.length == 0 ) {
var none = "<p>Info</p>";
$('#wrapper').prepend(none);
};
if (aktuella.length == 1) {
var expires = '<p>' + xmlDoc.getElementsByTagName("expires")[0].parentNode.childNodes[1].textContent + '</p>';
$('#wrapper').prepend(expires);
};
if (aktuella.length > 1) {
for (i = 0; i < aktuella.length; i++) {
var expires = '<li id="' + i + '">' + xmlDoc.getElementsByTagName("expires")[i].parentNode.childNodes[1].textContent + ' - Se Driftinfo</li>';
$('#wrap').prepend(expires);
};
};
$(function(){
$('#wrap').totemticker({
row_height : '120px',
next : '#ticker-next',
previous : '#ticker-previous',
stop : null,
start : null,
mousestop : true,
});
});
}
funtion makeinterval(){
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
myFunction(this);
}
};
xhttp.open("GET", "drift.xml", true);
xhttp.send();
}
setInterval(function(){
makeInterval();
}, 5000);
makeinterval()
Related
I am using basic javascript and trying to upload a file appx 500Mb, but my browser is getting stuck. Below is my javascript code
main.js
'use strict';
var singleUploadForm = document.querySelector('#singleUploadForm');
var singleFileUploadInput = document.querySelector('#singleFileUploadInput');
var singleFileUploadError = document.querySelector('#singleFileUploadError');
var singleFileUploadSuccess = document.querySelector('#singleFileUploadSuccess');
var multipleUploadForm = document.querySelector('#multipleUploadForm');
var multipleFileUploadInput = document.querySelector('#multipleFileUploadInput');
var multipleFileUploadError = document.querySelector('#multipleFileUploadError');
var multipleFileUploadSuccess = document.querySelector('#multipleFileUploadSuccess');
var asyncMltipleUploadForm = document.querySelector('#asyncMltipleUploadForm');
var asyncMultipleFileUploadInput = document.querySelector('#asyncMltipleUploadInput');
var asyncMultipleFileUploadError = document.querySelector('#asyncMultipleFileUploadError');
var asyncMultipleFileUploadSuccess = document.querySelector('#asyncMultipleFileUploadSuccess');
function uploadSingleFile(file) {
var formData = new FormData();
formData.append("file", file);
var xhr = new XMLHttpRequest();
xhr.open("POST", "http://localhost:8080/uploadFile");
xhr.onload = function() {
console.log(xhr.responseText);
// var response = JSON.parse(xhr.responseText);
if(xhr.status == 200) {
singleFileUploadError.style.display = "none";
// singleFileUploadSuccess.innerHTML = "<p>File Uploaded Successfully.</p><p>DownloadUrl : <a href='" + response.fileDownloadUri + "' target='_blank'>" + response.fileDownloadUri + "</a></p>";
singleFileUploadSuccess.style.display = "block";
} else {
singleFileUploadSuccess.style.display = "none";
singleFileUploadError.innerHTML = (response && response.message) || "Some Error Occurred";
}
}
xhr.send(formData);
}
function resolveAfter2Seconds(file) {
return new Promise(resolve => {
// setTimeout(() => {
resolve(uploadSingleFile(file));
// }, null);
} );
}
async function asynchUploadMultipleFiles(files) {
var formData = new FormData();
for(var index = 0; index < files.length; index++) {
// formData.append("files", files[index]);
var startDate = new Date();
await resolveAfter2Seconds(files[index]);
var endDate = new Date();
var diff = endDate - startDate;
asyncMultipleFileUploadSuccess.innerHTML = "time taken :::: " + diff;
asyncMultipleFileUploadSuccess.style.display = "block";
}
}
function uploadMultipleFiles(files) {
var startDate = new Date();
var formData = new FormData();
for(var index = 0; index < files.length; index++) {
formData.append("files", files[index]);
}
var xhr = new XMLHttpRequest();
xhr.open("POST", "http://localhost:8080/uploadMultipleFiles");
xhr.onload = function() {
console.log(xhr.responseText);
// var response = JSON.parse(xhr.responseText);
if(xhr.status == 200) {
multipleFileUploadError.style.display = "none";
var content = "<p>All Files Uploaded Successfully</p>";
// for(var i = 0; i < response.length; i++) {
// content += "<p>DownloadUrl : <a href='" + response[i].fileDownloadUri + "' target='_blank'>" + response[i].fileDownloadUri + "</a></p>";
// }
var endDate = new Date();
var diff = endDate - startDate;
multipleFileUploadSuccess.innerHTML = content + "time taken :::: " + diff;
multipleFileUploadSuccess.style.display = "block";
} else {
multipleFileUploadSuccess.style.display = "none";
multipleFileUploadError.innerHTML = (response && response.message) || "Some Error Occurred";
}
}
// console.log(xhr.responseText);
xhr.send(formData);
}
singleUploadForm.addEventListener('submit', function(event){
var files = singleFileUploadInput.files;
if(files.length === 0) {
singleFileUploadError.innerHTML = "Please select a file";
singleFileUploadError.style.display = "block";
}
uploadSingleFile(files[0]);
event.preventDefault();
}, true);
multipleUploadForm.addEventListener('submit', function(event){
var files = multipleFileUploadInput.files;
if(files.length === 0) {
multipleFileUploadError.innerHTML = "Please select at least one file";
multipleFileUploadError.style.display = "block";
}
uploadMultipleFiles(files);
event.preventDefault();
}, true);
asyncMltipleUploadForm.addEventListener('submit', function(event){
var files = asyncMultipleFileUploadInput.files;
if(files.length === 0) {
asyncMultipleFileUploadError.innerHTML = "Please select at least one file";
asyncMultipleFileUploadError.style.display = "block";
}
asynchUploadMultipleFiles(files);
event.preventDefault();
}, true);
Can you please help
I have the following Microsoft Dynamics related XMLHttpRequest javascript function, and is encountering issue when attemtping to retrieve the entity attributes of the returned records.
The record managed to be created even though the conditions should have blocked it. It is likely that my following statement caused the issue:
var result1 = results.results[0];
alert("result1: " + result1.id); //Not displayed
function DisableInvalidRecordCreation(context) {
var saveEvent = context.getEventArgs();
var idNumber= Xrm.Page.getAttribute("IDNumber").getValue();
var category= Xrm.Page.getAttribute("Category").getValue();
var id = Xrm.Page.data.entity.getId();
var req = new XMLHttpRequest();
req.open("GET", Xrm.Page.context.getClientUrl() + "/api/data/v9.0/ccc_cases?$select=IDNumber&$filter=IDNumber eq '" + idNumber+ "' and statecode eq 0", false);
req.setRequestHeader("OData-MaxVersion", "4.0");
req.setRequestHeader("OData-Version", "4.0");
req.setRequestHeader("Accept", "application/json");
req.setRequestHeader("Content-Type", "application/json; charset=utf-8");
req.setRequestHeader("Prefer", "odata.include-annotations=\"*\",odata.maxpagesize=1");
req.onreadystatechange = function () {
if (this.readyState === 4) {
req.onreadystatechange = null;
if (this.status === 200) {
var results = JSON.parse(this.response);
if (results.value.length > 0 && id == "") {
alert(results.value.length); //Displayed as 1
var result1 = results.results[0];
alert("result1: " + result1.id); //Not displayed
for (var i = 0; i < results.entities.length; i++) {
var returned_category= results.entities[i]["Category"];
alert(returned_category); //Not displayed
if (category == 100000003 && returned_category!= 100000003)
{
alert("Invalid record");
saveEvent.preventDefault();
}
}
}
} else {
Xrm.Utility.alertDialog(this.statusText);
}
}
};
req.send();
}
This is happening because in your get request you are selecting only IDNumber field and not the one you desire like Category
req.open("GET", Xrm.Page.context.getClientUrl() + "/api/data/v9.0/ccc_cases?$select=IDNumber&$filter=IDNumber eq '" + idNumber+ "' and statecode eq 0", false);
Also it should not be var result1 = results.results[0];
rather it should be var result1 =results.value[0]
sample code snippet for reference
if (this.readyState === 4) {
req.onreadystatechange = null;
if (this.status === 200) {
var results = JSON.parse(this.response);
for (var i = 0; i < results.value.length; i++) {
var abc = results.value[i]["abc"];
var xyz = results.value[i]["xyz"];
var pqr = results.value[i]["pqr"];
var pqr_formatted = results.value[i]["pqr#OData.Community.Display.V1.FormattedValue"];
}
} else {
Xrm.Utility.alertDialog(this.statusText);
}
}
I'm trying to run this code here, but i keep getting this error
ReferenceError: xmlHttp is not defined
at XMLHttpRequest.ChamadaJSON.xmlhttp.onreadystatechange
I've tried mostly everything but it just continues... Here's the code:
function ChamadaJSON(data) {
var xmlhttp = new XMLHttpRequest();
var url = "http://menuetec.esy.es/test3.php?data="+data;
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var responseText = xmlHttp.responseText;
ConectaServidor(responseText);
}
}
xmlhttp.open("GET", url, true);
xmlhttp.send();
function ConectaServidor(response) {
var dados = JSON.parse(response);
var i;
var conteudo = "";
var conteudo2 = "";
var conteudo3 = "";
var conteudo4 = "";
for (i = 0; i < dados.length; i++)
{
conteudo += dados[i].tb02_cafe;
conteudo2 += dados[i].tb02_lanchedia;
conteudo3 += dados[i].tb02_almoco;
conteudo4 += dados[i].tb02_lanchenoite;
}
document.getElementById("cafe1").innerHTML = conteudo;
document.getElementById("lanche1").innerHTML = conteudo2;
document.getElementById("almoco1").innerHTML = conteudo3;
document.getElementById("lanchen1").innerHTML = conteudo4;
}}
What's wrong?
Note that if i directly put my dates into the array enabledDates, it will work.
var enabledDays = [];
var answ = '';
function choosedoc(){
var xmlhttp = getXMLHttpRequest();
var actionmode = 1;
var doctorid = document.getElementById('doctorid').value;
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
var data = $.parseJSON(xmlhttp.responseText);
var msg = data[0].message;
if (msg != "") {
alert(decodeURIComponent(msg));
} else {
answ = data[0].some;
// this will get an array of dates: 11-11-2014,11-13-2014,11-14-2014
alert(enabledDays);
if(answ!=''){
alert(answ);
var result = answ.split(",");
//that would split the answer with the , seperator
for(i = 0; i < result.length; i++){
enabledDays.push("'"+result[i]+"'");
}
}else{
enabledDays ='';
}
}
}
}
xmlhttp.open("GET","appointments_ajax.php?actionmode="+actionmode+"&doctorid="+doctorid);
xmlhttp.send();
}
function enableAll(date) {
var m = date.getMonth() + 1, d = date.getDate(), y = date.getFullYear();
for (i = 0; i < enabledDays.length; i++) {
if($.inArray(m + '-' + d + '-' + y,enabledDays) != -1) {
return [true];
}
}
return [false];
}
$(function(){
$('#appointmentdate').datepicker({
dateFormat:'yy-mm-dd',
beforeShowDay: enableAll,
});
});
When I press the input toolbar, it will display a calendar which will be all disabled except the dates that are in the array
Just got some codes from worldofwebcraft.com for my project examination system.I only know PHP,and I actually have no idea on javascripts because our teacher hasnt taught us yet. Please help me on how do I submit the form automatically when the user reloads the page or when he/she opens a new tab.
heres the codes:
<?php if(isset($_GET['question'])){
$question = preg_replace('/[^0-9]/', "", $_GET['question']);
$next = $question + 1;
$prev = $question - 1; ?>
<script type="text/javascript">
function countDown(secs,elem) {
var element = document.getElementById(elem);
element.innerHTML = "You have "+secs+" seconds remaining.";
if(secs < 1) {
var xhr = new XMLHttpRequest();
var url = "userAnswers.php";
var vars = "radio=0"+"&qid="+<?php echo $question; ?>;
xhr.open("POST", url, true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.onreadystatechange = function() {
if(xhr.readyState == 4 && xhr.status == 200) {
alert("You did not answer the question in the allotted time. It will be marked as incorrect.");
clearTimeout(timer);
}
}
xhr.send(vars);
document.getElementById('counter_status').innerHTML = "";
document.getElementById('btnSpan').innerHTML = '<h2>Times Up!</h2>';
document.getElementById('btnSpan').innerHTML += 'Click here now';
}
secs--;
var timer = setTimeout('countDown('+secs+',"'+elem+'")',1000);
}
</script>
<script>
function getQuestion(){
var hr = new XMLHttpRequest();
hr.onreadystatechange = function(){
if (hr.readyState==4 && hr.status==200){
var response = hr.responseText.split("|");
if(response[0] == "finished"){
document.getElementById('status').innerHTML = response[1];
}
var nums = hr.responseText.split(",");
document.getElementById('question').innerHTML = nums[0];
document.getElementById('answers').innerHTML = nums[1];
document.getElementById('answers').innerHTML += nums[2];
}
}
hr.open("GET", "questions.php?question=" + <?php echo $question; ?>, true);
hr.send();
}
function x() {
var rads = document.getElementsByName("rads");
for ( var i = 0; i < rads.length; i++ ) {
if ( rads[i].checked ){
var val = rads[i].value;
return val;
}
}
}
function post_answer(){
var p = new XMLHttpRequest();
var id = document.getElementById('qid').value;
var url = "userAnswers.php";
var vars = "qid="+id+"&radio="+x();
p.open("POST", url, true);
p.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
p.onreadystatechange = function() {
if(p.readyState == 4 && p.status == 200) {
document.getElementById("status").innerHTML = '';
alert("Your answer was submitted.");
var url = 'exam.php?question=<?php echo $next; ?>';
window.location = url;
}
}
p.send(vars);
document.getElementById("status").innerHTML = "processing...";
}
</script>
<script>
window.oncontextmenu = function(){
return false;
}
document.onkeydown = function() {
if(event.keyCode == 116) {
event.returnValue = false;
event.keyCode = 0;
return false;
}
}
</script>
I would do something like :
window.onbeforeunload = function() {
post_answer();
}
If post_answer() is your "submit the form"-handler. Cannot tell exactly from the code.