Combining html5 progress bar with javascript and CGI script and C backend - javascript

I'm pretty new to everything concerning webbased programming. I have the following progress bar.
<!doctype html>
<html>
<head>
<title>HTML5 Progress Bar</title>
<link rel="stylesheet" href="css/normalize.css">
<link rel="stylesheet" href="css/style.css">
<script src="js/jquery.js" type="text/javascript"></script>
<script src="js/modernizr.js" type="text/javascript"></script>
<script>
$(document).ready(function() {
if(!Modernizr.meter){
alert('Sorry your brower does not support HTML5 progress bar');
} else {
var progressbar = $('#progressbar'),
max = progressbar.attr('max'),
time = (1000/max)*5,
value = progressbar.val();
var loading = function() {
value += 1;
addValue = progressbar.val(value);
$('.progress-value').html(value + '%');
if (value == max) {
clearInterval(animate);
}
};
var animate = setInterval(function() {
loading();
}, time);
};
});
</script>
</head>
<body>
<div class="demo-wrapper html5-progress-bar">
<div class="progress-bar-wrapper">
<progress id="progressbar" value="0" max="100"></progress>
<span class="progress-value">0%</span>
</div>
</div>
</body>
</html>
This works pretty well based on a timer. I now want to fill that progress bar with the help of data from a c program. The Scenario is
the "value" must be updated with progress data from the c program i need to call.
if i understand right i need to call a CGI script which then opens up a pipe to my c program to catch the stdout of that c program.
that stdout data from my c program will then be redirected through the cgi back to the html5 document and update the progress bar.
Problem with that: Is that the right way to do it? Or am i understanding that wrong?
An alternative would be to open a websocket in html5 and adding a socket communcation thread to my c program and then they could both communicate. Is that possible with updating the progress bar in realtime in mind?

Related

Javascript not working on page after that page is called by ajax

Im still new to javascript and ajax and all that. Im working on a project for my web dev course and have been stuck on this for a while now. The professor hasnt been of any help.
I am making a data page. On the index there are 4 radio buttons, each on loading another html page into the div. Each of these other pages have data sets and allow for searches on a few of the fields. The issue is that when these pages are called by the index page, none of the functions work on them anymore. The functions work on them when I open the page alone and not through the index.
This is the Index Page html and javascript
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Index</title>
<link href="index.css" rel="stylesheet">
<script src="index.js"></script>
</head>
<body>
<h1> Welcome to Data Sets - Calgary</h1>
<table id="buttons">
<tr><td>Find Calgary Libraries</td><td>Find Traffic Incidents In Calgary</td><td>Search Calgary Building Permits</td><td>Search Calgary Crimes</td></tr>
<tr><td><p>Clicking on this loads a search for Calgary Libraries</p></td><td><p>Clicking on this loads a search for Calgary traffic incidents</p></td><td><p>Clicking on this loads a search for Calgary Building permits</p></td><td><p>Clicking on this loads a search for Calgary Crimes</p></td></tr>
<tr><td><input type="radio" id="calgLib" name="butt"></td><td><input type="radio" id="calgTraff" name="butt"></td><td><input type="radio" id="calgBuild" name="butt"></td><td><input type="radio" id="calgCrime" name="butt"></td></tr>
</table>
<div class="buttonresults" id="buttonresults">
</div>
</body>
</html>
window.onload=registerListeners;
function registerListeners() { var asd; asd=document.getElementById("calgLib"); asd.addEventListener("change", function () { getContent("liblocations.html");}, false); asd=document.getElementById("calgTraff"); asd.addEventListener("change", function () { getContent("trafficincident.html");}, false); asd=document.getElementById("calgBuild"); asd.addEventListener("change", function () { getContent("buildpermit.html");}, false); asd=document.getElementById("calgCrime"); asd.addEventListener("change", function () { getContent("commcrime.html");}, false); }
function getContent(infopage) {
asynchrequest= new XMLHttpRequest();
asynchrequest.onreadystatechange = function() {
if (asynchrequest.readyState == 4 && asynchrequest.status == 200) { document.getElementById("buttonresults").innerHTML = asynchrequest.responseText; } }; asynchrequest.open("GET", infopage, true); asynchrequest.send(); }
This is one of the pages being called from the index
<script src="liblocations.js"></script>
<h1>Find Calgary Libraries</h1>
<div class="textfields">
<table id="fields">
<tr><td><label>Find Libraries by Name </label></td><td><input type="text" id="libname"></td></tr>
<tr><td><label>Find Libraries by Postal Code </label></td><td><input type="text" id="libPostal"></td></tr>
<tr><td><label>Find Libraries by Square Feet </label></td><td><input type="text" id="libSquareFeet"></td></tr>
</table>
</div>
<br>
<br>
<h3 id="searchvalue"> Enter a search</h3>
<table id="searchresults">
</table>
This is the unfinished Java script for the liblocations page
var xhr = new XMLHttpRequest; var parsedrecord; window.onload=pageSetup;
function pageSetup() {
document.getElementById("libname").addEventListener("keyup", function (){ searchByLibraryName();},false);
document.getElementById("libPostal").addEventListener("keyup", function (){ searchByLibraryPostal();},false);
document.getElementById("libSquareFeet").addEventListener("keyup", function (){ searchByLibrarySqrFeet();},false);
xhr.onreadystatechange = function() { if (xhr.readyState == 4 && xhr.status == 200) { parsedrecord = JSON.parse(xhr.responseText); } }; xhr.open("GET", "https://data.calgary.ca/resource/m9y7-ui7j.json", true); xhr.send();
}
function searchByLibraryName() { document.getElementById("searchvalue").innerHTML="Searching by Library Name"; var librarytoUse=libname.value.toUpperCase(); libPostal.value=""; libSquareFeet.value=""; var gmap=""; var position=""; var output="<tr><th>Library</th><th>Postal Code</th><th>Square Feet</th><th>Phone Number</th><th>Location</th></tr>";
for(var i=0;i<parsedrecord.length;i++)
{
var record=parsedrecord[i];
var searchLib=record.library.toUpperCase();//assign
if(searchLib.startsWith(librarytoUse))//partial match on string
{
output+="<tr><td>";
output+=record.library;
output+="</td><td>"
output+=record.postal_code;
output+="</td><td>";
output+=record.square_feet;
output+="</td><td>";
output+=record.phone_number;
output+="</td><td>";
position=record.location.latitude+","+record.location.longitude;
gmap ="<a href=https://www.google.com/maps/search/?api=1&query="+position+" target=_blank>Click here to see map</a> ";
output+=gmap;
output+="</td></tr>";
}
}
document.getElementById("searchresults").innerHTML=output;
}
When opening liblocations.html, the functions work but when I use the radio button and the index.html
loads the page, the functions stop working. I'm not sure what is going on, or how to fix it. Any help is appreciated!
This is the index page calling the liblocations
enter image description here
This is what the liblocations page looks like when I open it alone
enter image description here
In the index.html page put this line <script src="index.js"></script> end of the body tag . I mean here:
<script src="index.js"></script>
</body>
From personal experience, things can quickly get messy when using XMLHttpRequest for fetching data in JavaScript. A much better option would be to use the Fetch API, which you can read more about on the MDN Web Docs. I'm not sure if this is the exact problem you're facing, but I do know that trying to run asynchronous code with XMLHttpRequest (rather than async/await and the Fetch API) can cause many unintended consequences that can be confusing unless you really know what you're doing. That is unless you have a valid reason for using XMLHttpRequest, such as having to target IE.

JavaScript setInterval animation creates gibberish without error in the console

I'm trying to create a simple animation with setInterval, and I'm testing it on a Python SimpleHTTPServer because I had some cross-origin issues earlier. There is no error in the console when I load the page, and I can see the loading overlay properly, and then the page just becomes gibberish (see images below) although the console shows it is loading image properly. I'm wondering what is wrong. Thanks!
(The gibberish is really long, so this screenshot is just part of it.)
<!DOCTYPE html>
<html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>fish</title>
<link rel="stylesheet" type="text/css" href="./assets/style.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
</head>
<body>
<div id="overlay">
<img src="http://i.imgur.com/KUJoe.gif">
</div>
<div id="fish" style="width:100px; height:100px;"></div>
<script type="text/javascript">
$(window).on("load", function(){
$("#overlay").fadeOut();
var r = 1;
setInterval(function(){
if (r < 5) {
$("#fish").load("./assets/images/fish" + r + ".jpeg");
r++;
} else {
r = 1;
}
console.log(r);
console.log("./assets/images/fish" + r + ".jpeg");
}, 100);
});
</script>
</body>
</html>
When you say this:
$("#fish").load("./assets/images/fish" + r + ".jpeg");
...you are loading the data in the jpeg file as text within the #fish element - that is, you are doing the equivalent of trying to open a jpeg file in Notepad.
What you probably want to do is have an <img> element and set its src to that jpeg file - either change the <div> to be an <img> or add an <img> within the <div>:
<div style="width:100px; height:100px;"><img id="fish"></div>
// and then
$("#fish").prop("src", "./assets/images/fish" + r + ".jpeg");
Note that for smooth animation you probably want to "preload" all of the images, then use setInterval() after that to switch between them.

In a Firefox add-on, how to implement injecting a script into an HTML page and sending a message back to the main script?

My add-on specifically works on a single site.
It injects a contentscript and sends a message to popup(panel in firefox terminology) to display.
Here is my contentscript:
//this code is same for firefox as well as chrome since it is that which manipulates the page in which it is injected, so I think this is indepent of browser
var table = document.getElementsByClassName("collapse")[0];
var marks = new Array();
for(var i=0;i<8;i++)
marks[i] = table.children[0].children[i+1].children[5].innerHTML;
var total=0;
for(var i=0;i<8;i++)
total += Number(marks[i]);
------------------------------------------------
//this code is different for firefox
//code to send the data to popup
var fromDOM = total;
chrome.runtime.sendMessage(fromDOM);//what is the equivalent method for sending a message to popup(panel)?
popup.html
//no change , I think would be same with firefox
<!DOCTYPE HTML>
<html>
<head>
<title>Popup page</title>
<link rel="stylesheet" type="text/css" href="popup.css">
</head>
<body>
<div id="output">
<h1><form name="F1" method="POST">
TOTAL: <p id="total"></p>
PERCENTAGE: <p id="percentage"></p>
</form></h1>
</div>
<script src="popup.js">
</script>
</body>
</html>
popup.js:
//code to load the contentscript into the page
chrome.tabs.executeScript({"file": "contentscript.js"});
//equivalent firefox code??***
-----------------------------------------------------------------
var total= 0,percentage = 0;
chrome.runtime.onMessage.addListener(function(response){
total = response;***
//Getting response sent from contentscript, how can I do the same in firefox?
percentage = total/7.25;
document.getElementById("total").innerHTML = total;
document.getElementById("percentage").innerHTML = percentage.toFixed(2)+" %";
});
What are the specific firefox methods for some chrome API's methods mentioned?
I'd be glad if any one could help me out.
Thanks

Simple youtube javascript api 3 request not works

i've tried to write a simple youtube request to search video with youtube javascript api v3.
This is the source code:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function showResponse(response) {
var responseString = JSON.stringify(response, '', 2);
document.getElementById('response').innerHTML += responseString;
}
// Called automatically when JavaScript client library is loaded.
function onClientLoad() {
gapi.client.load('youtube', 'v3', onYouTubeApiLoad);
}
// Called automatically when YouTube API interface is loaded
function onYouTubeApiLoad() {
// This API key is intended for use only in this lesson.
gapi.client.setApiKey('API_KEY');
search();
}
function search() {
var request = gapi.client.youtube.search.list({
part: 'snippet',
q:'U2'
});
// Send the request to the API server,
// and invoke onSearchRepsonse() with the response.
request.execute(onSearchResponse);
}
// Called automatically with the response of the YouTube API request.
function onSearchResponse(response) {
showResponse(response);
}
</script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script src="https://apis.google.com/js/client.js?onload=onClientLoad" type="text/javascript"></script>
</head>
<body>
<pre id="response"></pre>
</body>
</html>
When i load this page on google chrome (updated), nothing happens, the page remains blank.
I have request the API Key for browser apps (with referers) and copied in the method gapi.client.setApiKey.
Anyone can help me?
Thanks
Try this example here
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<title>Google AJAX Search API Sample</title>
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script type="text/javascript">
// How to search through a YouTube channel aka http://www.youtube.com/members
google.load('search', '1');
function OnLoad() {
// create a search control
var searchControl = new google.search.SearchControl();
// So the results are expanded by default
options = new google.search.SearcherOptions();
options.setExpandMode(google.search.SearchControl.EXPAND_MODE_OPEN);
// Create a video searcher and add it to the control
searchControl.addSearcher(new google.search.VideoSearch(), options);
// Draw the control onto the page
searchControl.draw(document.getElementById("content"));
// Search
searchControl.execute("U2");
}
google.setOnLoadCallback(OnLoad);
</script>
</head>
<body style="font-family: Arial;border: 0 none;">
<div id="content">Loading...</div>
</body>
</html>
When you use <script src="https://apis.google.com/js/client.js?onload=onClientLoad" ..></script>
you have to upload the html file somewhere online or use XAMPP on your PC
To use html for searching YT videos, using Javascript on PC, as I know, we need to use other codings:
1- Use javascript code similar to this for API version 2.0. Except only the existence of API KEY v3.
2- Use the jQuery method "$.get(..)" for the purpose.
See:
http://play-videos.url.ph/v3/search-50-videos.html
For more details see (my post "JAVASCRIPT FOR SEARCHING VIDEOS"):
http://phanhung20.blogspot.com/2015_09_01_archive.html
var maxRes = 50;
function searchQ(){
query = document.getElementById('queryText').value;
email = 'https://www.googleapis.com/youtube/v3/search?part=snippet&maxResults=50'+
'&order=viewCount&q='+ query + '&key=****YOUR API3 KEY*****'+
'&callback=myPlan';
var oldsearchS = document.getElementById('searchS');
if(oldsearchS){
oldsearchS.parentNode.removeChild(oldsearchS);
}
var s = document.createElement('script');
s.setAttribute('src', email);
s.setAttribute('id','searchS');
s.setAttribute('type','text/javascript');
document.getElementsByTagName('head')[0].appendChild(s);
}
function myPlan(response){
for (var i=0; i<maxRes;i++){
var videoID=response.items[i].id.videoId;
if(typeof videoID != 'undefined'){
var title=response.items[i].snippet.title;
var links = '<br><img src="http://img.youtube.com/vi/'+ videoID +
'/default.jpg" width="80" height="60">'+
'<br>'+(i+1)+ '. <a href="#" onclick="playVid(\''+ videoID +
'\');return false;">'+ title + '</a><br>';
document.getElementById('list1a').innerHTML += links ;
}
}
}
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
</head>
<body>
<input type="text" value="abba" id="queryText" size="80">
<button type="button" onclick="searchQ()">Search 50 videos</button>
<br><br>
<div id='list1a' style="width:750px;height:300px;overflow:auto;
text-align:left;background-color:#eee;line-height:150%;padding:10px">
</div>
I used the original code that Tom posted, It gave me 403 access permission error. When I went back to my api console & checked my api access time, it was expired. So I recreated the access time for the api. It regenerated new time. And the code worked fine with results.
Simply i must make request from a web server.
Thanks all for your reply

Javascript : External Functions won't work

I have been using javascript for the last couple of days and have decided to use it for my website. I also decided to use external functions in a single .js file
function imageLoad() {
var path,domain,cut;
path = window.location.pathname;
domain = "WEBSITE DOMAIN ADDRESS";
cut = path.substring(domain.length,path.length);
/* Still in progress */
}
function pageStart() {
var image-on = 0;
var imgArray = new Array();
alert("boo"); /* Used to check the script will run */
}
Now that's a simple process. Nothing too complex. And I have done the following (it is a code extract of my template)
<script type="text/javascript" src="main_script.js"></script>
<head>
<link rel="stylesheet" href="main.css" type="text/css" />
<title>Grandpa Pixel</title>
</head>
<body onload="pageStart();">
Now that should do the trick. On body loading, it should cause an alert "boo". But it doesn't. It just loads the page normally. However If I make the external script ONLY contain the line alert("boo"), it works perfectly. Can I ask why this is the case? Does this mean you can only have one function per external file?
check this:
function pageStart() {
var image_on = 0;
var imgArray = new Array();
alert("boo"); /* Used to check the script will run */
}
HTML
<head>
<link rel="stylesheet" href="main.css" type="text/css" />
<title>Grandpa Pixel</title>
<script type="text/javascript" src="main_script.js"></script>
</head>
<body onload="pageStart();">
recommended using Firebug or other debuggers.
ERRORS
SyntaxError: missing ; before statement
var image-on = 0;
main_script.js (line 12, col 13)
ReferenceError: pageStart is not defined
pageStart();
SOLUTION
change
var image-on = 0;
with
var imageOn = 0;
it would be cleaner to put the <script> tag into the <header> tag.

Categories

Resources