Random quote on click (API + JavaScript) - javascript

I want to show a random quote when a button is clicked. The project is here https://skidle.github.io/projects/random-quote. If you open a console, you can see that this onclick=newQuote() function is working because it generates an JSON object into a console. But the quote stays the same, so should I change the URL somehow?
JS:
var xhr = new XMLHttpRequest();
xhr.open("GET", "https://quotesondesign.com/wp-json/posts?filter[orderby]=rand&filter[posts_per_page]=1");
xhr.send();
xhr.onreadystatechange = function () {
var DONE = 4; // readyState 4 means the request is done.
var OK = 200; // status 200 is a successful return.
if (xhr.readyState === DONE) {
if (xhr.status === OK) {
var json = JSON.parse(xhr.responseText);
var elQuote = document.getElementById("quote");
elQuote.innerHTML = json[0]["content"];
var elAuthor = document.getElementById("author");
elAuthor.innerHTML = json[0]["title"];
console.log(json[0]);
} else {
console.log("Error: " + xhr.status); // An error occurred during the request.
}
};
}
var newQuote = function() {
//the script below is the same as above just inserted inside newQuote()
var xhr = new XMLHttpRequest();
xhr.open("GET", "https://quotesondesign.com/wp-json/posts?filter[orderby]=rand&filter[posts_per_page]=1");
xhr.send();
xhr.onreadystatechange = function () {
var DONE = 4; // readyState 4 means the request is done.
var OK = 200; // status 200 is a successful return.
if (xhr.readyState === DONE) {
if (xhr.status === OK) {
var json = JSON.parse(xhr.responseText);
var elQuote = document.getElementById("quote");
elQuote.innerHTML = json[0]["content"];
var elAuthor = document.getElementById("author");
elAuthor.innerHTML = json[0]["title"];
console.log(json[0]);
} else {
console.log("Error: " + xhr.status); // An error occurred during the request.
}
};
}
}
HTML:
<main>
<div class="container">
<div class="wrapper">
<section id="quote">
</section>
<div class="button-wrapper">
<button>Tweet this</button>
<div id="author"></div>
<button onclick="newQuote()">New quote</button>
</div>
</div>
</div>
</main>
Thank you in advance!

I think that the ajax request is beeing cached. Try adding a timestamp to the url, like this:
xhr.open("GET", "https://quotesondesign.com/wp-json/posts?filter[orderby]=rand&filter[posts_per_page]=1&timestamp="+new Date());

Related

How to add Node.js result in my HTML project?

this is my project: http://cryptotipsitalia.sytes.net/.
I want add Ethereum value down to "Valore BTC" with Node.js: https://www.npmjs.com/package/crypto-price.
How can I add it?
That's my code:
function getValueBTC() { <!-- chiamata API --> /
var xmlhttp = new XMLHttpRequest();
var url = "https://api.coindesk.com/v1/bpi/currentprice.json";
var output;
console.log(url);
xmlhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
output = this.responseText;
var obj = JSON.parse(output);
var rightValue = (obj.bpi.EUR.rate).substring(0,obj.bpi.EUR.rate.length-2); /* eliminazione ultime due cifre */
document.getElementById("cellaValoreBTC").innerHTML= obj.bpi.EUR.symbol + " " + rightValue;
}
};
xmlhttp.open("GET", url, true);
xmlhttp.setRequestHeader("Content-type", "text/plain");
xmlhttp.send();
}
let price = require('crypto-price');
price.getCryptoPrice('EUR', 'ETH').then(obj => {
console.log(obj.price); // It will print ETH rate per BTC
document.getElementById("cellaValoreETH").innerHTML = obj.price;
}).catch(err => {
console.log(err);
});
table><tr><td width="75%">VALORE BTC:</td></tr><tr id="cellaValoreBTC" width="75%"></tr><tr><td width="75%">VALORE ETH:</td></tr><tr id="cellaValoreETH" width="75%"></table>
Why "document.getElementById("cellaValoreBTC").innerHTML = obj.price;" doesnt' work?
How can I add obj.price in my HTML code?
Thanks

Repeat XMLHttpRequest request

My app have some jquery http calls and some angular http calls....
So.. to add a param to every request, I add this code at the beginning of my code.
var op = XMLHttpRequest.prototype.open;
XMLHttpRequest.prototype.open = function() {
this.addEventListener("readystatechange", function() {
if(this.readyState === 4 && this.status === 200 ){
// http call is done
}
}, false);
arguments[1] = arguments[1]+'?test=testParam';
var resp = op.apply(this, arguments);
return resp;
};
Now I want 2 things
1) I want to change the response before apply it
2) If the response is 404.... I want to make another call.... take the response... and then repeat the call with some new params
The short answer is that we can't extend XMLHttpRequest to retry the connection because we can't fire .open if we have the .onload event fired. Writing several .open of the same XMLHttpRequest instance causes that each .open rewrites the previously .open, but once .onload event is fired, we can't reuse that instance (the request doesn't send), so we have to create another instance of XMLHttpRequest. So the closest approach in my opinion is reusing the code, like this:
var param = 106;
var div = document.getElementById("retry");
var div2 = document.getElementById("success");
var div3 = document.getElementById("response");
div.innerHTML = "Trying: " + param;
var xhr = new XMLHttpRequest();
xhr.open('GET', 'https://jsonplaceholder.typicode.com/posts/' + param);
xhr.onload = function() {
if (this.status === 200) { //<-- we use this instead of xhr
div2.innerHTML = "Success: " + param;
div3.innerHTML = this.responseText;
} else {
var newXhr = xhr; //<-- we have to create another instance
newXhr.open('GET', 'https://jsonplaceholder.typicode.com/posts/' + param);
newXhr.onload = xhr.onload; //<--we reuse the function
newXhr.send();
div.innerHTML = "Trying: " + param;
param--;
}
};
xhr.send();
<div id="retry">
</div>
<div id="success">
</div>
<div id="response">
</div>
This is another approach (my previous answer), that I think is better:
function myAjax(param) {
var div = document.getElementById("retry");
var div2 = document.getElementById("success");
var div3 = document.getElementById("response");
div.innerHTML = "Trying: " + param;
console.log(param);
var xhr = new XMLHttpRequest();
xhr.open('GET', 'https://jsonplaceholder.typicode.com/posts/' + param);
xhr.onload = function() {
if (xhr.status === 200) {
div2.innerHTML = "Success: " + param;
div3.innerHTML = xhr.responseText;
} else {
param--;
myAjax(param); //I'm calling again the function
}
};
xhr.send();
}
myAjax(105);
<div id="retry">
</div>
<div id="success">
</div>
<div id="response">
</div>

XMLHttpRequest looping

I know this question has been asked before, but I tried to apply the answers with no results.
I'm trying to do multiple requests on the same domain with a for loop but it's working for the entire record of my array.
Here is the code I use:
function showDesc(str) {
var prod = document.getElementsByName("prod_item[]");
var xhr = [], i;
for (i = 0; i < prod.length; i++) {
var txtHint = 'txtHint10' + i;
(function(i) {
var xhr = new XMLHttpRequest();
var url = "getDesc.php?q=" + str;
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
document.getElementById(txtHint).innerHTML = xhr.responseText;
}
};
xhr.open("GET", url, false);
xhr.send();
})(i);
}
}
PHP
<select name="prod_item[]" id="prod_item.1" onchange="showDesc(this.options[this.selectedIndex].value)"></select>
<div id="txtHint100"></div>
and then I will use dynamic table for the prod_item field and div_id.
Is there any mistake in my code?

Having trouble making a XMLHttpRequest()

I am trying to make an XMLHttpRequest, however, I am having issues. The page keeps refreshing automatically even when returning false or using e.preventDefault(). I'm trying to get cities to eventually pass through an options block. (I've started the option section and will complete it after I figure out the get request issue.) I'm trying to do this using pure Javascript because I've already done it using Angular and Node. Any help would be appreciated.
HTML:
<form id="citySearchForm" method="get" onSubmit="return searchFormFunc();">
<div>
<p>Choose a city:</p>
<input type="text" placeholder="Enter a city" id="getCitiesInput" name="city">
<input type="submit" value="submit">
</div>
<div id="weather"></div
<p><span id="temp"></span></p
<p><span id="wind"></span></p>
</form>
Javascript:
var citySearch = document.getElementById("citySearchForm");
// citySearch.addEventListener("submit", searchFormFunc);
function searchFormFunc(e){
cityName = document.getElementById('getCitiesInput').value;
var searchCityLink = "http://autocomplete.wunderground.com/aq?query=";
var search = searchCityLink.concat(cityName);
console.log("link : " + search);
var xhr = XMLHttpRequest();
xhr.onreadystatechange = function() {
if(xhr.readyState == 4) {
var r = JSON.parse(xhr.response || xhr.responseText); // IE9 has no property response, so you have to use responseText
console.log(r);
} else {
console.log('error');
}
};
xhr.open("GET", link, true);
xhr.send(null);
var r = JSON.parse(xhr.response);
return false;
// e.preventDefault();
}
You are specifying that you want this to be an async request. So you need to parse your response inside of the onreadystatechange or onload.
function ajax(url, callback) {
var xhr;
if(typeof XMLHttpRequest !== 'undefined') xhr = new XMLHttpRequest();
else {
var versions = ["MSXML2.XmlHttp.5.0",
"MSXML2.XmlHttp.4.0",
"MSXML2.XmlHttp.3.0",
"MSXML2.XmlHttp.2.0",
"Microsoft.XmlHttp"]
for(var i = 0, len = versions.length; i < len; i++) {
try {
xhr = new ActiveXObject(versions[i]);
break;
}
catch(e){}
} // end for
}
/** Here you can specify what should be done **/
xhr.onreadystatechange = function() {
if(xhr.readyState < 4) {
return;
}
if(xhr.status !== 200) {
return;
}
// all is well
if(xhr.readyState === 4) {
callback(xhr);
}
}
xhr.open('GET', url, true);
xhr.send('');
}
Answer from documentation by user6123921
You have to use var xhr = new XMLHttpRequest();
you have to define an onreadystatechange event listener
xhr.onreadystatechange = function() {
if(xhr.readyState == 4) {
var r = JSON.parse(xhr.response || xhr.responseText); // IE9 has no property response, so you have to use responseText
console.log(r);
/* do stuff with response */
}
};

AJAX not refreshing chat message section

I recently got a website aired and am having trouble getting the chat to work without having to have the user refresh the page (hence, the ajax). But the person on the other end still has to refresh in order to see the latest message. We're in the same room, so I can see if the chat refreshes or not; it doesn't, and here's the code
<script type="text/javascript">
var scroller = function(){
posts = document.getElementById("posts");
posts.scrollTop = posts.scrollHeight;
}
var menu = 3;
var checksum = function(){
if (menu == 3){
document.getElementById('smileys').style.display="block";
document.bob.smileyhider.innerHTML="−";
menu=1;
}
else {
document.getElementById('smileys').style.display="none";
document.bob.smileyhider.innerHTML="+";
menu=3;
}
}
//Chat ajax loader
var updater = 10;
function update(){
var xhr;
if(updater < 200){ updater = 200 }
if (window.XMLHttpRequest){ xhr = new XMLHttpRequest(); }
else { xhr = new ActiveXObject('Microsoft.XMLHTTP'); }
xhr.onreadystatechange = function(){
if (xhr.readyState==4 && xhr.status == 200){
document.getElementById('posts').innerHTML = xhr.responseText;
}
}
setTimeout(update, (++updater)*10);
xhr.open("GET","chatlog<?php echo date("d");?>.log",true);
xhr.send(null);
}
</script>
You are never actually calling update to kick off the ajax requests. I wouldn't nest it either
You want to use setInterval instead. setTimeout will only run once.
I would just use a static value for updater, like 3 seconds
/
var updater = 3000;
function update(){
var xhr;
if(updater < 200){ updater = 200 }
if (window.XMLHttpRequest){ xhr = new XMLHttpRequest(); }
else { xhr = new ActiveXObject('Microsoft.XMLHTTP'); }
xhr.onreadystatechange = function(){
if (xhr.readyState==4 && xhr.status == 200){
document.getElementById('posts').innerHTML = xhr.responseText;
}
}
xhr.open("GET","chatlog<?php echo date("d");?>.log",true);
xhr.send(null);
}
setInterval(update, updater);

Categories