How to compare JSON data from the same API request? - javascript

I'm still learning a lot about web development and javascript, so forgive me if my explanations are not clear.
I have a function to request from an API informations about cryptocurrency (Price, volume etc.) in a JSON file and then i display the price on the web page every 15 seconds.
I want to change the background color of the card where the price is displayed by comparing the actual price and the new one coming from the next request.
here's my javascript :
function requestPrice(url, domLocation){
var req = new XMLHttpRequest();
req.open("GET", url);
req.addEventListener("load", function() {
if (req.status >= 200 && req.status < 400) {
var data = JSON.parse(req.responseText)
domLocation.innerHTML = data.ticker.price + "$";
erreur.innerHTML = "";
} else {
erreur.innerHTML = "Erreur: " + req.status + " " + req.statusText;
}
});
req.addEventListener("error", function () {
erreur.innerHTML = "Erreur";
});
req.send(null);
}
var btcPrice = document.getElementById('boxBTC'), erreur =
document.getElementById('erreur');
setInterval(requestPrice("https://api.cryptonator.com/api/ticker/btc-eur",
btcPrice), 15000);
I was thinking of a simple comparaison between the values and put this code in my loop but i need to stock the actual price somewhere to do the comparison with the new one coming and i'm stuck with that.
if (valueOf(data.ticker.price) <= valueOf(data.ticker.price)){
document.getElementById('overviewcard').style.backgroundColor = red;
} else {
document.getElementById('overviewcard').style.backgroundColor = blue;
}
Or
var overviewcard = getElementById('overviewcard');
if (data.ticker.price <= data.ticker.price){
overviewcard.style.backgroundColor = red;
} else {
overviewcard.style.backgroundColor = blue;
}
here's the html :
<div class="overviewcard">
<span id="boxBTC">...</span>
<span id="erreur"></span>
</div>
Thanks a lot for your help

You can do this in a myriad of ways, but the simplest is to grab the data from the actual HTML DOM element.
var currValue = document.getElementById('boxBTC').innerHTML;
if(valueOf(data.ticker.price) == currValue) {
// do something
}
If you're boxBTC string is formatted too much (eg. if you make "1000" -> "1,000"), then you can always also store a data attribute of the raw value inside the DOM as a data attr.
// assigning the data
document.getElementById('boxBTC').setAttribute('data-val', price);
...
// accessing the data
document.getElementById('boxBTC').getAttribute('data-val');

Related

Changing variable on button-click using JQuery / JavaScript

I am attempting to build a web feature that allows the user to select a window of time to see local Earthquake information, using information found here.
https://earthquake.usgs.gov/earthquakes/feed/v1.0/geojson.php
As you can see here, (https://codepen.io/JoshTheGray/pen/yPmJeR) I am having success parsing the information when I statically assign the url variable for whatever timeframe I want, however I am running into trouble trying to make that url variable change, based on a user button click.
My HTML
<div>Please select a window of time to see Earthquake information.</div>
<br>
<button id="1HourButton">Past Hour</button>
<button id="1DayButton">Past 24 Hours</button>
<br>
<br>
<div id="output1">Earthquakes Around the State<br><br></div>
<br>
My JavaScript / JQuery
;(function($){
$( document ).ready(function() {
// testing document load state
console.log( "document loaded" );
var output1 =document.getElementById('output1');
var hr = new XMLHttpRequest();
// Asigns url based on button choice from user.
var url = '';
$('#1HourButton').click(function () {
url = 'https://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/all_hour.geojson';
console.log(url);
});
$('#1DayButton').click(function () {
url = 'https://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/all_day.geojson';
console.log(url);
});
hr.onreadystatechange = function() {
if(this.readyState === 4 && this.status === 200){
var myObj = JSON.parse(hr.response);
for(i=0; i < myObj.features.length; i++) {
if (myObj.features[i].properties.title.includes("Alaska")) {
output1.innerHTML += myObj.features[i].properties.title + '<br>';
}
}
}
}
hr.open("GET", url, true);
hr.send();
});
})(jQuery);
=========================
Currently I am seeing the correct URL information passed to the console upon button click, but the json information is no longer coming through.
What am I missing?

Error on AJAX call PHP function with JSON return

I want to develop a News Ticker using three technologies: PHP, Javascript and AJAX.
First, I made a PHP function getFeed() to fetch data from News websites on an Array, then I made a JSON return using this code: echo json_encode($articles, true);
Secondly, I aim to use AJAX and Javascript to make repeated calls to getFeed() function, here is my javascript code:
<script type="text/javasript">
var xmlhttp=false;
function begin() {
if(window.XMLHttpRequest){
xmlhttp = new XMLHttpRequest();
}else{
xmlhttp = new ActiveXObject('Microsoft.XMLHTTP');
}
xmlhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200){
var jsonContent=JSON.parse(this.responseText);
displayT(jsonContent);
}
};
// rssnews.inc.php contain the getFeed() function
xmlhttp.open('GET','rssnews.inc.php', true);
xmlhttp.send();
}
// displayT(content) function display the JSON element
function displayT(content){
var out = "";
var i;
for(i = 0; i < arr.length; i++) {
out += '<h4><a href="' + arr[i].link+ '">' +
arr[i].title + '</a></h4><br>';
}
document.getElementById('item').innerHTML = out;
}
</script>
On the HTML page, I have the following components a button (id="start") - on click execute begin() function, a div container (id="Ticker") and a div (id="item") for display data with AJAX
<form>
<button type="submit" class="btn btn-default" id="start" onclick="begin();"> START </button>
</form>
<div id= "ticker" style="border: 1px solid #ccc; height: 500px; weight:600px;">
<div id="item">
<!-- I want to display the fetched data by 4 items at a specific time Interval-->
</div>
</div>
When I click on the start button, I don't get the json data.
How can I solve this problem and how can I ensure that this AJAX calls is the most appropriate way to my Ticker.
Thank you!
The error is essentially saying that the file you are trying to GET with you AJAX call, does not exist at the specified location (which is http://localhost/rss/rssnews.inc.php).
You are using a Relative path, which searches for 'rssnews.inc.php' in the same folder. To go up to the parent directory, use ../.
Or use an Absolute path, as in http://localhost/rss/rssnews.inc.php. (Replace with absolute path to your PHP script)
Update
(after HTTP 401 solved)
displayT function is taking content as input, and is then reffering to arr, which is not defined.
Assuming content is actually an array containing your data in the desired format, replace arr with content:
function displayT(content){
var out = "";
var i;
for(i = 0; i < content.length; i++) {
out += '<h4><a href="' + content[i].link+ '">' +
content[i].title + '</a></h4><br>';
}
document.getElementById('item').innerHTML = out;
}

Kendo Grid - Window template button with update functionality

Right now I am using a window to view details that are not shown in the grid. I have made my own custom editor in the window as well which hides the details and replaces them with inputs.
Unfortunately I cannot get the Update button to have the same functionality as an update button in the kendo toolbar.
I am using transport and parameter map for my create which works perfectly. I just need to be able to hit the update, which I haven't been able to.
Here is a snippet of code for the template:
<li><b>Change Control Objective</b></li>
<li><textarea type="text" class="k-textbox k-input" data-bind="value:ChangeControlObjective">#= ChangeControlObjective #</textarea></li>
<li><b>Change Control Specifics</b></li>
<li><textarea type="text" class="k-textbox k-input" data-bind="value:ChangeControlSpecifics">#= ChangeControlSpecifics #</textarea></li>
<span class="k-update k-icon k-i-tick"></span>Save
I can't show my JS code but it is based off this dojo: http://dojo.telerik.com/abUHI
UPDATE:
I am able to hit the update in the parametermap off of my save button click but it's sending the old data to the update instead of the new. Here is the button click code:
$("#saveChanges").click(function () {
dataItem.dirty = true;
$("#ccrGrid").data('kendoGrid').saveChanges();
});
Each input has a data-bind attribute and the parametermap looks like this:
case "update":
var changeControlRequestId = options.ChangeControlRequestID;
var changeControlObjective = options.ChangeControlObjective;
var changeControlSpecifics = options.ChangeControlSpecifics;
var productAssociation;
if (options.AccountChangeInfo.ProductAssocation == undefined) {
productAssociation = "";
} else { productAssociation = options.ProductAssocation; }
var amortization;
if (options.AccountChangeInfo.Amortization == undefined) {
amortization = "";
} else { amortization = options.Amortization; }
var productType;
if (options.ProductChangeInfo.ProductType == undefined) {
productType = "";
} else { productType = options.ProductType; }
var productName;
if (options.ProductChangeInfo.ProductName == undefined) {
productName = "";
} else { productName = options.ProductName; }
var productDescription;
if (options.ProductChangeInfo.ProductDescription == undefined) {
productDescription = "";
} else { productDescription = options.ProductDescription; }
var productContract;
if (options.ProductChangeInfo.ProductContractualFeatures == undefined) {
productContract = "";
} else { productContract = options.ProductContractualFeatures; }
var productBehavior;
if (options.ProductChangeInfo.ProductBehavioralAssumptions == undefined) {
productBehavior = "";
} else { productBehavior = options.ProductBehavioralAssumptions; }
var evaluationBehavior;
if (options.ProductChangeInfo.ProductEvaluationBehavior == undefined) {
evaluationBehavior = "";
} else { evaluationBehavior = options.ProductEvaluationBehavior; }
var productStratification;
if (options.ProductChangeInfo.ProductStratificationRoutines == undefined) {
productStratification = "";
} else { productStratification = options.ProductStratificationRoutines; }
if (content.isreadonly == "True") {
alert("you have readonly access");
}
else {
var urlString = "env=" + content.env + "&allyid=" + content.userId + "&changeRequestID" + changeRequestID + "&changeControlObjective=" + changeControlObjective + "&changeControlSpecifics=" + changeControlSpecifics +
"&productAssociation" + productAssociation + "&amortization" + amortization +
"&productType" + productType + "&productName" + productName + "&productDescription" + productDescription +
"&productContract" + productContract + "&productBehavior" + productBehavior + "&evaluationBehavior" + evaluationBehavior +
"&productStratification" + productStratification;
return urlString;
I've been going through this a couple months ago. Per my extensive research there are 2 key sources for doing custom popup editing in Kendo in entire Internet ;) :
Custom editor template
I aslo created a simplified version of this for you here: http://jsbin.com/qudotag/
to cut the elements which can be expanded once you grap the key concepts. Note that this does not work fully as changes are not persisted. It is expected behaviour, as you would need to define the CRUD operations for the grid (what happens when save, cancel etc. is done).
How to deal with CRUD is available in the second source:
Crud with external form
Some heavy studying of these 2 along with going into some more depths of MVVM (which might be intimidating at first, but then really useful for much smoother work with Kendo) will get you going.
Edit: actually you could do with just first approach, which is easier and retain the state by refreshing the grid after cancel.

Javascript: Simple currency converter with previous conversions

what i aim to do is a very simple currency converter. Basically, you type in a number, and press a button, a text is displayed that says "x dollars is y euros". Press the button again, a new text is displayed where the old one was, and the old one is displayed under the new one.
I've come so far that when something is entered in the field, it pops up below, and if you press the button again (with the same or a different value) it becomes a list of text.
To clarify what it is i'm saying here, take a look at this jsfiddle: http://jsfiddle.net/w8KAS/5/
Now i want to make it so that only numbers work, and so that number(x) is converted when the button is pressed and displayed below next to some fitting text (like "x dollars is y euros")
This is my js code, check the jsfiddle full code (html, js, css)
Any suggestions?
var count = 0;
function validate() {
var amount = document.querySelector("#amount");
if(amount.value.length > 0) {
amount.className = 'correct';
}
else {
amount.className = 'empty';
}
if (document.querySelector('.empty')) {
alert('Något är fel');
}
else {
addconvert(amount.value);
}
}
function addconvert(amount) {
var table = document.querySelector('#tbody');
var tr = document.createElement('tr');
var amountTd = document.createElement('td');
var amountTextNode = document.createTextNode(amount);
amountTd.appendChild(amountTextNode)
tr.appendChild(amountTd);
table.insertBefore(tr, table.firstChild);
count++;
}
var button = document.querySelector(".button");
button.onclick = validate;
Your number validation is failing. Change the first part of your validation to this:
function validate() {
var amount = document.querySelector("#amount");
var amountNum = parseFloat(amount.value); //This is the numeric value, use it for calculations
if(amount.value.length > 0 && !isNaN(amountNum) ) {
amount.className = 'correct';
amount.value = amountNum;
}
...
Working here: http://jsfiddle.net/edgarinvillegas/w8KAS/6/
Cheers
You need a conversion rate (there are APIs for that), and then you can just add them together in a string
var convRate = 1.3;
var amountTextNode = document.createTextNode(amount + " dollars is " + amount*convRate + " euros");
Regarding the API, Yahoo will tell you what you need without even the need to sign-in
$.ajax({
url: "http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.xchange%20where%20pair%20in%20(%22USDEUR%22)&format=json&diagnostics=true&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys&callback="
}).done(function(data) {
convRate = data.query.results.rate.Rate
});
To make sure that only numbers work, you can test the variable amount.value using the isNaN function. This will return true if the user's input is Not-a-Number, so if it returns false, you can proceed with your conversion.
if (!isNaN(amount.value)){
addconvert(+amount.value) // the plus symbol converts to a number
} else {
// display error here
}
Inside your addconvert function, you can add code to will multiply your input amount by an exchange rate to get a rough conversion.
function addconvert(){
// ...
var euros = 0.74 * amount
var text = amount + ' dollars is ' + euros + ' euros'
var amountTextNode = document.createTextNode(text);

How do i solve these issues?

I wrote simplest extension as an exercise in JS coding. This extension checks if some user (of certain social network) is online, and then outputs his/her small image, name and online status in notification alert. It checks profile page every 2 minutes via (setTimeout), but when user becomes "online", i set setTimeout to 45 minutes.(to avoid online alerts every 2 minutes).
It works, but not exactly as i expected. I have 2 issues:
1)When certain user is online and i change user id (via options page) to check another one, it doesnt happen because it waits 45 or less minutes. i tried the following code (in options.html), but it doesnt help.
2)When i change users, image output doesnt work correctly!! It outputs image of previous user!!
How do i fix these problems??
Thanks!
options.html
<script>
onload = function() {
if (localStorage.id){
document.getElementById("identifier").value = localStorage.id;
}
else {
var el = document.createElement("div");
el.innerHTML = "Enter ID!!";
document.getElementsByTagName("body")[0].appendChild(el);
}
};
function onch(){
localStorage.id = document.getElementById("identifier").value;
var bg = chrome.extension.getBackgroundPage();
if(bg.id1){
clearTimeout(bg.id1);
bg.getdata();
}
}
</script>
<body>
<h1>
</h1>
<form id="options">
<h2>Settings</h2>
<label><input type='text' id ='identifier' value='' onchange="onch()"> Enter ID </label>
</form>
</body>
</html>
backg.html
<script type="text/javascript">
var domurl = "http://www.xxxxxxxxxxxxxx.xxx/id";
var txt;
var id1;
var id2;
var imgarres = [];
var imgarr = [];
var imgels = [];
function getdata() {
if (id1){clearTimeout(id1);}
if (id2){clearTimeout(id2);}
var url = getUrl();
var xhr = new XMLHttpRequest();
xhr.open('GET',url, true);
xhr.setRequestHeader('Cache-Control', 'no-cache');
xhr.setRequestHeader('Pragma', 'no-cache');
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
txt = xhr.responseText;
var r = txt.indexOf('<b class="fl_r">Online</b>');
var el = document.createElement("div");
el.innerHTML = txt;
var n = imgprocess(el,url);
var nam = el.getElementsByTagName("title")[0].innerHTML;
if (r != -1) {
var notification = webkitNotifications.createNotification(n, nam, 'online!!' );
notification.show();
var id1 = setTimeout(getdata, 60000*45);
}
else {
var id2 = setTimeout(getdata, 60000*2);
}
}}
xhr.send();
}
function imgprocess(text,url){
imgels = text.getElementsByTagName("IMG");
for (var i=0;i< imgels.length;i++){
if (imgels[i].src.indexOf(parse(url)) != -1){
imgarr.push(imgels[i]);
}
}
for (var p=0; p< imgarr.length; p++){
if (imgarr[p].parentNode.nodeName=="A"){
imgarres.push(imgarr[p]);
}
}
var z = imgarres[0].src;
return z;
}
function getUrl(){
if (localStorage.id){
var ur = domurl + localStorage.id;
return ur;
}
else {
var notif = webkitNotifications.createNotification(null, 'blah,blah,blah', 'Enter ID in options!!' );
notif.show();
getdata();
}
}
function init() {
getdata();
}
</script>
</head>
<body onload="init();">
</body>
</html>
In options instead of clearTimeout(bg.id1); try bg.clearTimeout(bg.id1);
For image problem looks like you never clean imgarres array, only adding elements to it and then taking the first one.
PS. You code is very hard to read, maybe if you made it well formatted and didn't use cryptic variable names you would be able to find bugs easier.
UPDATE
I think I know what the problem is. When you are setting the timeout you are using local scope variable because of var keyword, so your id1 is visible only inside this function and global id1 is still undefined. So instead of:
var id1 = setTimeout(getdata, 60000*45);
try:
id1 = setTimeout(getdata, 60000*45);
Because of this if(bg.id1){} inside options is never executed.
(bg.clearTimeout(bg.id1); should work after that, but it is not needed as you are clearing the timeout inside getdata() anyway)

Categories