I have a code that is making ajax calls to the server and does some drawing on screen. Everything works, but the execution seems unstable, sometimes I have to
reload page several time before I will see the results of the drawing function. The drawing is done through Processing.js Here is the code with some comments, that I added
that show what I intend the code to do.
The view structure (it is Rails 3.2 ) is as follows:
app/sentence/show.html.erb
<script>
$(document).ready(function () {
//This calls the action in controller that queries database for new results:
setInterval(function(){
var idx = "<%= #sentence.id %>";
$.post("getstatus/", {id:idx});
console.log("reload");
},6000);
});
</script>
<%= javascript_include_tag "pjs" %>
<div class="container-fluid plots-field" >
<div id="grid-system">
<canvas id="graphsketch" data-processing-sources="/assets/pjs/graphBuilder2_2.pde"></canvas>
<div id='node_div'></div>
<div id='iframe_div'></div>
<div id='comments_div'></div>
<div id='link_to_plot'><%= link_to "Original plot", #sentence.plot %></div>
</div>
</div>
<div id="data_div"></div>
app/controllers/sentences_controller.rb <- Here I have a getstatus function:
def getstatus
#sentence = Sentence.find(params[:id])
#sentence_so_far = #sentence.get_graph.to_json.html_safe
#sentence_test = "BBB"
respond_to do |format|
format.js
end
end
app/controllers/sentences/gestatus.js.erb <- Here is where the drawing is happening. I have a "cache" variable, that is saved to corresponding div through jquery.data and gets compared with latest return from the controller.
var bound = false;
var pjs = Processing.getInstanceById("graphsketch");
var text = <%= #sentence_so_far %>;
var test = <%= array_or_string_for_javascript(#sentence_test)%>;
//Added this to be able to check difference between cache and current data
Array.prototype.diff = function(a) {
return this.filter(function(i) {
return !(a.indexOf(i) > -1);
});
};
//Saving current state to data with 'orig' ket
$("#data_div").data("orig", text);
var orig = $("#data_div").data("orig");
//Getting cache from data_div
var cache = $("#data_div").data("cache");
//If I have the cache, get the difference and get assign it to text variable, if there is no difference, means I already have what I need on screen
if (cache) {
var dif = cache.diff(orig);
text = dif;
}
//If cache is different from what I had before, draw stuff with text.
if (cache != orig) {
pjs.update(text);
}
//Save current text to cache.
$("#data_div").data("cache", text);
//This allows Processing.js to interact with Javascript
function bindJavascript() {
var pjs = Processing.getInstanceById("graphsketch");
if (pjs != null) {
pjs.bindJavascript(this);
bound = true;
}
if (!bound) setTimeout(bindJavascript, 250);
}
bindJavascript();
//This function is getting called form within Processing.js and works fine..
function nodeName(name) {
$.post("/nodes/this_node/", {id: name});
// console.log(name);
}
So the result is that sometimes I actually get to see the results of pjs.update(text) but sometimes nothing is drawn. From server console I can see that controller action works fine and always returns what I need from the model.
EDIT:
Here is the "show source" of the HTML page, if that is helpful..
<!DOCTYPE html>
<html lang="en">
<head>
<link href="/assets/bootstrap.css?body=1" media="screen" rel="stylesheet" type="text/css" />
<link href="/assets/docs.css?body=1" media="screen" rel="stylesheet" type="text/css" />
<link href="/assets/bootstrap-responsive.css?body=1" media="screen" rel="stylesheet" type="text/css" />
<link href="/assets/style.css?body=1" media="screen" rel="stylesheet" type="text/css" />
<link href='http://fonts.googleapis.com/css?family=Didact+Gothic' rel='stylesheet' type='text/css'>
<script src="/assets/jquery.js?body=1" type="text/javascript"></script>
<script src="/assets/jquery_ujs.js?body=1" type="text/javascript"></script>
<script src="/assets/pjs.js?body=1" type="text/javascript"></script>
<script src="/assets/pjs/lib/toxiclibs.js?body=1" type="text/javascript"></script>
<script src="/assets/pjs/lib/toxiclibs.min.js?body=1" type="text/javascript"></script>
<script src="/assets/pjs/processing.js?body=1" type="text/javascript"></script>
<script src="/assets/application.js?body=1" type="text/javascript"></script>
</head>
<body>
<script>
$(document).ready(function () {
setInterval(function(){
var idx = "5";
$.post("getstatus/", {id:idx});
console.log("reload");
},6000);
});
</script>
<script src="/assets/pjs.js?body=1" type="text/javascript"></script>
<script src="/assets/pjs/lib/toxiclibs.js?body=1" type="text/javascript"></script>
<script src="/assets/pjs/processing.js?body=1" type="text/javascript"></script>
<div class="container-fluid plots-field" >
<div id="grid-system">
<canvas id="graphsketch" data-processing-sources="/assets/pjs/graphBuilder2_2.pde"></canvas>
<div id='node_div'></div>
<div id='iframe_div'></div>
<div id='comments_div'></div>
<div id='link_to_plot'>Original plot</div>
</div>
</div>
<div id="data_div"></div>
<div id="video_grid" class="row"></div>
</body>
</html>
Any input greatly appreciated. If there is more info I can provide, please let me know.
Thanks!
Related
I am writing a webpage using HTML and javascript. I have written a script (as seen below) that loads records from a json file. My script is meant to load data from the json file and display like a bootstrap alert. When I first ran it, the script worked, but strangely subsequent tests did not work. Does anyone have any ideas to fix this?
index.html:
<!DOCTYPE html>
<html>
<head>
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
<link type="text/css" href="css/style.css" rel="stylesheet">
<!-- Script in Question -->
<script type="text/javascript">
// This is a way to load data from a JSON file and load it into places in the html document. Based on: https://howtocreateapps.com/fetch-and-display-json-html-javascript/
fetch('alerts.json')
.then(function(response){
return response.json();
})
.then(function (data){
appendData(data);
})
.catch(function (err) {
console.log(err);
});
function appendData(data) {
var container = document.getElementById("alerts");
for (let i = 0; i < data.length; i++) {
var div = document.createElement("div");
div.className = "alert alert-primary";
div.setAttribute("role", "alert")
div.innerHTML = data[i].content;
container.appendChild(div)
}
}
</script>
<title>Guitars</title>
</head>
<body>
<div id="alerts" style="text-align: center;">
<!-- JSON data appears here -->
</div>
<div style="text-align: center;" id="main">
<!-- Other stuff here -->
</div>
<div style="text-align: center;">
<!-- Other stuff here -->
</div>
</body>
</html>
alerts.json:
[
{"content":"Welcome back, test1!"},
{"content":"Welcome back, test2!"},
{"content":"Welcome back, test3!"}
]
The code reads the records from alerts.json and inserts them into a div with an id "alerts" - as seen in the <script> tag. Any help would be greatly appreciated!
OP here. Thanks to user #David, it was suggested to clear out all errors found in the webpage debugging console. Upon clearing these up, the function then worked as intended!
im trying to fetch data from a json file but i doesnt work, i already check every options here but no one works for me, none of the code its working, i dont know if i have to import something else, and the json file its in the same level of the index file, hope you can help me
appClients.js
(function(){
var app = angular.module('customer',[]);
alert('Success');
app.controller("CustomerController",function($scope,$http){
$http.get('../customer.json')
.success(function(data) {
// $scope.phones = data;
alert('Success');
})
.error(function(data){
alert('Error');
});
});
});
index.html
<!DOCTYPE HTML>
<html ng-app="customer">
<head>
<link rel="stylesheet" type="text/css" href="css/bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="css/style.css">
</head>
<body class="Master" ng-controller="CustomerController as customer">
<script type="text/javascript" src="js/angularjs.min.js"></script>
<script type="text/javascript" src="js/appClients.js"></script>
<header id="MasterHeader">
</header>
<div class="container">
<div class="row">
<div class="col-lg-12">
<div class="col-lg-6" id="CustomerList" ng-repeat="product in customer.clients">
<h3>{{product.id}}</h3>
</div>
<div class="col-lg-6" id="CustomerDetails">Details</div>
</div>
</div>
</div>
<footer id="MasterFooter">
</footer>
</body>
</html>
It looks like your IIFE (Immediately-invoked function expression) is not being executed. Update your appClient.js file to
(function(){
var app = angular.module('customer',[]);
alert('Success');
app.controller("CustomerController",function($scope,$http){
$http.get('../customer.json')
.success(function(data) {
// $scope.phones = data;
alert('Success');
})
.error(function(data){
alert('Error');
});
});
})();
Note the additional () on the final line. This should allow you to see the initial "Success" alert.
If your ajax call then succeeds you would need to make the $scope property that the result is set to consistent with the $scope property referenced in the HTML. Based on the current snippet you seem to be setting the result to $scope.phone in the controller, but reference $scope.customer in your HTML.
I am practicing Windows Phone development using WinJS and I have the following code which parses JSON received from a particular URL. And using the images to be bound to a list view in an HTML page,
JavaScript code:
WinJS.xhr({ url: urlToBeUsed }).then(
function (sportsResponse) {
var sportsJSON = JSON.parse(sportsResponse.responseText);
var listItems = sportsJSON.Videos.Data;
for (var i = 0; i < listItems.length; i++) {
var imageList = listItems[i].Items;
var count = imageList.length;
if (count > 0) {
listItems[i].Items[0].Images.forEach(imageIteration);
function imageIteration(value, index, array) {
var picture = value.Url;
var name = value.title;
sportsImageList.push({
title: name,
picture: picture
});
}
}
}
imageList.itemDataSource = sportsImageList.dataSource;
})
}
HTML Code:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
<!-- WinJS references -->
<script src="//Microsoft.Phone.WinJS.2.1/js/base.js"></script>
<script src="//Microsoft.Phone.WinJS.2.1/js/ui.js"></script>
<script src="/js/navigator.js"></script>
<link href="/css/default.css" rel="stylesheet" />
<link href="/pages/home/home.css" rel="stylesheet" />
<script src="/pages/sports/sports.js"></script>
</head>
<body>
<!-- The content that will be loaded and displayed. -->
<div class="fragment homepage" style="width:100%;height:100%;padding:10px">
<div class="myTemplate" data-win-control="WinJS.Binding.Template">
<div class="myItem">
<img data-win-bind="src:picture" style="width:100px;height:100px" />
</div>
</div>
<div id="imageList" data-win-control="WinJS.UI.ListView" data-win-bind="winControl.itemDataSource:sportsImageList.dataSource" data-win-options="{itemTemplate:select('.myTemplate')}"></div>
</div>
</body>
</html>
I have tried many ways to bind the URL to the Image, but on the screen I can only see the links but not the actual images.
Where am I wrong?
All help and suggestions appreciated.
Thank you!
I believe your error is in your assignment line, remember that itemDataSource is a property of the ListView control. As it is in your code you're assigning that property to the imageList element.
Change it to this:
imageList.winControl.itemDataSource = sportsImageList.dataSource;
I am trying to implement CSS binding in knockoutJS.
I want to print all the names in the names array, One after another.
The catch is that there is another array which has some special names.
All the special names should get "good" CSS class. And the rest, "bad" css class.
Here is something that i have tried:
HTML
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery.min.js"></script>
<link href="http://getbootstrap.com/dist/css/bootstrap.css" rel="stylesheet" type="text/css" />
<script src="http://getbootstrap.com/dist/js/bootstrap.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/knockout/3.0.0/knockout-min.js"></script>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<meta charset="utf-8">
<title>JS Bin</title>
</head>
<body>
<div data-bind="foreach : items">
<div data-bind="text: $data, css: checkName($data)" ></div>
</div>
</body>
</html>
JAVASCRIPT
var dataModel = function(){
self.items = ko.observableArray(["don","bom","harry","sharry","ron"]);
self.names = ["ron","harry"];
self.checkName = ko.observable(function(name){
if( $.inArray(name,self.names) ){
return "good";
}
else{
return "bad";
}
});
};
ko.applyBindings(new dataModel());
FIDDLE - http://jsbin.com/difaluwo/2/edit
Now its not woking. In console its giving me "Script error. (line 0)"
Thanks !
The out of the box CSS binding is a little tricky. You specify class name and then the condition when it will be applied.
JSBIN
<div data-bind="foreach : items">
<div data-bind="text: $data, css: { good: isGoodName($data), bad: !isGoodName($data) }" ></div>
</div>
And your view model:
var dataModel = function(){
self.items = ko.observableArray(["don","bom","harry","sharry","ron"]);
self.names = ["ron","harry"];
self.isGoodName = function (name) {
return $.inArray(name, self.names) !== -1;
};
};
ko.applyBindings(new dataModel());
I use a Javascript widget on a blogspot. It include a div with some javascripts that get some "non-statical" strings from a server and print them on the page. Until here everything works fine, the problem is that I would like to update the execution of this div every few seconds in order to have updated strings, without refreshing the whole page, but just the specific widget (div). I have added another script that tries to refresh the specific div, but I had no luck. Please see the code below
<div id="info">
<b>Song:</b>
<script type="text/javascript" src="xxxx">
You appear to have javascript turned off.
</script>
<br />
<b>Listeners:</b>
<script type="text/javascript" src="xxxx">
You appear to have javascript turned off.
</script>
<br />
<b>Server Status:</b>
<img src="xxxxx.gif" alt="Stream status" width="17" height="17" align="absmiddle" />
</div>
Script for refreshing:
<script type="text/javascript">
window.onload = startInterval;
function startInterval()
{
setInterval("startTime();",5000);
}
function startTime()
{
document.getElementById('info').innerHTML = ??? // reload div
}
</script>
Additionally something like this could be used, but this method reload the whole page and not the specific div.
<script>
setInterval(function() {
parent.location.reload(true);
}, 5000);
</script>
Last Update
I try with Ajax and with created element.
With this technique, load the contains of the scripts but the document.write() not function.
Because this write() need the refresh page()!!
Just returning a value from a function does not place that value into an HTML element in any way. One could either use document.write (not recommended), or access the element via its id and write the desired element content via .innerHTML=…
Explain.
If you will be displaying it on page, first create an element with an id "message" (you can write anything you want, but remember, id's have to be unique on the page) like
<div id="message"></div>
and then use
document.getElementById("message").innerHTML = "New title";
or if you are using jQuery:
$("#message").html("New title");
or if you are using a console enabled browser (Firefox, Chrome etc.)
console.log("New title");
instead of
document.write("New title");
THEN document.write only for page loading time.
You have to change the scripts and replace document.write()
I put the my code with createElement and on the comment you look the my work.
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-2.0.0.js"></script>
<script type="text/javascript" src="http://code.jquery.com/ui/1.10.2/jquery-ui.js"></script>
<link href="http://code.jquery.com/ui/1.10.2/themes/smoothness/jquery-ui.css" rel="stylesheet" type="text/css"/>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body onload="JavaScript:timedRefresh(5000);">
<div id="info">
<b>Song:</b>
<script type="text/javascript" src="http://shoutcast.mixstream.net/js/song/uk23-free:5106">You appear to have javascript turned off.</script>
<br />
<b>Listeners:</b>
<script type="text/javascript" src="http://shoutcast.mixstream.net/js/listeners/uk23-free:5106">
You appear to have javascript turned off.
</script>
<br />
<b>Server Status:</b>
<img src="http://shoutcast.mixstream.net/status/uk23-free:5106.gif" alt="Stream status" width="17" height="17" align="absmiddle" />
</div>
<script type="text/javascript">
function timedRefresh(timeoutPeriod) {
var myVar=setInterval(function(){myTimer()},timeoutPeriod);
function myTimer()
{
document.getElementById("info").innerHTML="";
var b=document.createElement('B');
b.appendChild( document.createTextNode("Song") );
document.getElementById("info").appendChild(b);
// span.innerHTML="";
// span.appendChild( document.createTextNode("hello") );
// document.getElementById('myspan').innerHTML = 'newtext';
var src1 = 'http://shoutcast.mixstream.net/js/song/uk23-free:5106',
script1 = document.createElement('SCRIPT');
script1.type="text/javascript";
script1.src = src1;
document.getElementById("info").appendChild(script1);
var br= document.createElement('BR');
document.getElementById("info").appendChild(br);
document.getElementById("info").appendChild(br);
var b=document.createElement('B');
b.appendChild( document.createTextNode("Listeners") );
document.getElementById("info").appendChild(b);
var src2 = 'http://shoutcast.mixstream.net/js/listeners/uk23-free:5106',
script2 = document.createElement('SCRIPT');
script2.type="text/javascript";
script2.src = src2;
document.getElementById("info").appendChild(script2);
document.getElementById("info").appendChild(br);
var b=document.createElement('B');
b.appendChild( document.createTextNode("Server Status") );
document.getElementById("info").appendChild(b);
var src3 = 'http://shoutcast.mixstream.net/js/song/uk23-free:5106',
script3 = document.createElement('IMG');
script3.src = src3;
script3.alt="Stream status";
script3.width="17";
script3.height="17";
script3.align="absmiddle";
document.getElementById("info").appendChild(script3);
//
// document.body.appendChild(script);
//
// document.body.info.appendChild(b);
// document.getElementsByTagName('b')[1].appendChild( document.createTextNode("Listeners") );
// document.body.info.appendChild(script2);
// var br= document.createElement('BR');
//
// document.body.info.appendChild(br);
}
// // create an object of the head element of current page
// var hdEl = document.getElementsByTagName("song");
//
// //check for previously appended child
// //(it ensures that each time the button is pressed it
// // removes the previously loaded script element)
// if (hdEl.childNodes.length > 1) {
// hdEl.removeChild(hdEl.lastChild);
// }
//
// // Now add this new element to the head tag
//
//
// //Create a 'script' element
// var scrptE = document.createElement("script");
//
// // Set it's 'type' attribute
// scrptE.setAttribute("type", "text/javascript");
//
// // Set it's 'language' attribute
// scrptE.setAttribute("language", "JavaScript");
//
// // Set it's 'src' attribute
// scrptE.setAttribute("src", "http://shoutcast.mixstream.net/js/song/uk23-free:5106");
//
// // Now add this new element to the head tag
// hdEl.appendChild(scrptE);
// // document.getElementsByTagName("song").appendChild(scrptE);
// //This is a old:
// setTimeout("alert("ojk");",timeoutPeriod);
// // This function!!!
// setTimeout("document.getElementById('info').innerHTML = document.getElementById('info').innerHTML;",timeoutPeriod);
// var oHead = document.getElementsByTagName('HEAD').item(0);
// var oScript= document.createElement("script");
// oScript.type = "text/javascript";
// oScript.src="other.js";
// oHead.appendChild( oScript);
}
</script>
</body>
</html>
UPDATE:
THEN....
I change your site and now function!!!
And on the my pc this site is refresh every 5 second!!!
You have always the two particular errors.
This work for you but you have the particular error.
Resource interpreted as Script but transferred with MIME type text/html: "http://xxxx". on the sentence n° 13 and also for sentence n°18.
http://xxxx
This error I find with the tool's chrome (Inspect element).
The solution is on Stackoverflow or prefier the blog.
I have the software is Kubuntu (KDE + Ubuntu) and I don't know for change the value 's registry.
Solution:
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-2.0.0.js"></script>
<script type="text/javascript" src="http://code.jquery.com/ui/1.10.2/jquery-ui.js"></script>
<link href="http://code.jquery.com/ui/1.10.2/themes/smoothness/jquery-ui.css" rel="stylesheet" type="text/css"/>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body onload="JavaScript:timedRefresh(5000);">
<div id="info">
<b>Song:</b>
<script type="text/javascript" src="xxxx">You appear to have javascript turned off.</script>
<br />
<b>Listeners:</b>
<script type="text/javascript" src="xxxx">
You appear to have javascript turned off.
</script>
<br />
<b>Server Status:</b>
<img src="xxxx.gif" alt="Stream status" width="17" height="17" align="absmiddle" />
</div>
<script type="text/javascript">
function timedRefresh(timeoutPeriod) {
//This is a old:
//setTimeout("location.reload(true);",timeoutPeriod);
// This function!!!
setTimeout("document.getElementById('info').innerHTML = document.getElementById('info').innerHTML;",timeoutPeriod);
}
</script>
</body>
</html>
Or other solution:
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-2.0.0.js"></script>
<script type="text/javascript" src="http://code.jquery.com/ui/1.10.2/jquery-ui.js"></script>
<link href="http://code.jquery.com/ui/1.10.2/themes/smoothness/jquery-ui.css" rel="stylesheet" type="text/css"/>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body >
<div id="info">
<b>Song:</b>
<script type="text/javascript" src="xxxx">You appear to have javascript turned off.</script>
<br />
<b>Listeners:</b>
<script type="text/javascript" src="xxxxx">
You appear to have javascript turned off.
</script>
<br />
<b>Server Status:</b>
<img src="xxxxx.gif" alt="Stream status" width="17" height="17" align="absmiddle" />
</div>
<script type="text/javascript">
// function timedRefresh(timeoutPeriod) {
// setTimeout("document.getElementById('info').innerHTML = document.getElementById('info').innerHTML;",timeoutPeriod);
// document.getElementById("info").innerHTML=document.getElementById("info").innerHTML
// }
window.setInterval("refreshDiv()", 5000);
function refreshDiv(){
document.getElementById("info").innerHTML = document.getElementById("info").innerHTML;
}
</script>
</body>
</html>
This is a old site but not refresh the site.
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-2.0.0.js"></script>
<script type="text/javascript" src="http://code.jquery.com/ui/1.10.2/jquery-ui.js"></script>
<link href="http://code.jquery.com/ui/1.10.2/themes/smoothness/jquery-ui.css" rel="stylesheet" type="text/css"/>
</head>
<body>
<div id="info">
<b>Song:</b>
<script type="text/javascript" src="xxxx">You appear to have javascript turned off.</script>
<br />
<b>Listeners:</b>
<script type="text/javascript" src="xxxx">
You appear to have javascript turned off.
</script>
<br />
<b>Server Status:</b>
<img src="xxxx.gif" alt="Stream status" width="17" height="17" align="absmiddle" />
</div>
<script type="text/javascript">
setInterval(function(){
document.getElementById('info').innerHTML = document.getElementById('info').innerHTML;
}, 5000);
</script>
</body>
</html>
here is a fiddle working example of how i typically declare my set interval functions...
this one is setting the inner html of my #info div to a timestamp just so u can see that it is functional.
fiddle here with set interval
but i think there is another flaw in this process...
it looks like here you are updating the contents of the div to exactly the same html as they were before:
document.getElementById('info').innerHTML = document.getElementById('info').innerHTML;
this is likely your issue, the external scripts you are using are likely writing html, and you are just copying it rather than running those scripts again. what you want to do is run some sort of AJAX call to rerun those scripts.
you can do this more easily with the jquery library if you are interested in going that route. or to maintain strict javascript i would reccomend starting here:
w3 ajax tutorial