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
Related
I have been trying to get a php code to work through an ajax call but it doesnt seem to work (even though its posting and etc) when im simply assigning a value. I know the php code works when I just put it directly on the page but I want this to load after a button is pressed. My question is what would be the javascript equalivant to doing:
$_['dog'] = 'red';
Update:
the value 'dog' is already a value , the php code is simply changing it to 'red' for clarification. And the ajax call since I just wanted the code to be run this was my call :
function ajaxPost() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
console.log("success");
}
};
xhttp.open("POST", "https://linkto.com/lan.php", false);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send();
}
ajaxPost();
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.
I have an AJAX call whose reponse will feed some HTML into a DIV's innerHTML.
The response can contain images, and I'd like to have all these images loaded before my custom loading-div will hide.
I want to do this in vanilla JS. Unfortunately every question I've found here so far does it via jQuery.
I've tried adding an onload Event Listener to both the DIV and the xhttp object, but neither works. The loader disappears as soon as the HTML code is received and inserted, and then the user can witness each image loading individually.
document.getElementById("pageloader").className = "fadein";
var poststring = "&page="+encodeURIComponent(page);
var xhttp = new XMLHttpRequest();
xhttp.addEventListener("load", function() {
document.getElementById("pageloader").className = "fadeout";
});
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("content").innerHTML = this.responseText;
}
};
xhttp.open("POST", "myajax.php", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send(poststring);
I'm reading a text file into with a temporary email address and let this snippet built a HTML link.
<script>
//<![CDATA[
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
document.getElementsByClassName('temporary_email')[0].innerHTML = "Email";
}
};
xhttp.open("GET", "/temporary_email.txt", true);
xhttp.send();
//]]>
</script>
The whole thing works as expected and I can just place <span class="temporary_email"></span> anywhere and get a link.
The problem: it seems I can only fetch this one time; if I have a mailto: link in the body and another one in my footer the script won't work. So, I figure this isn't actually a variable and me being a JS noob is the real problem.
PS: I'm trying to avoid jQuery. Tried a few dummy workarounds like duplicating the script and assigning another name for document.getElementsByClassName, but nothing. Basically I'm working for a quick and dirty fix until I know enough JavaScript to do this properly.
The reason you're only getting the JS appended to the first instance of the class name match, is because document.getElementsByClassName() returns an array of matched elements.
By using document.getElementsByClassName('temporary_email')[0], you're only ever going to select the first matched element.
You'd need to update to the following code:
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
var elements = document.getElementsByClassName('temporary_email');
for (var i = 0; i < elements.length; i++) {
elements[i].innerHTML = "Email";
}
}
};
xhttp.open("GET", "/temporary_email.txt", true);
xhttp.send();
Here's a basic fiddle.
This way, you're iterating trough the array, and each one you're changing the innerHTML to what you need. Plus, no jQuery!
you could iterate over your temporary_email links and update each of them:
Array.from(document.getElementsByClassName('temporary_email'))
.forEach(function(el){
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
el.innerHTML = "Emai l";
}
};
xhttp.open("GET", "/temporary_email.txt", true);
xhttp.send();
})
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.