How can I load a spinning icon when using xmlhttprequest object - javascript

How can I load a spinning icon when using xmlhttprequest in JavaScript while Ajax is processing and I want to direct it to an innerHTML of a tag

Instead of 'Loading...' just use your spinner image and correct the path to your_file.txt to get a response from server:
function loadXMLDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var res = this.responseText;
setTimeout(function(){
document.getElementById("demo").innerHTML = res;
}, 2000);
} else {
document.getElementById("demo").innerHTML = 'Loading...';
}
};
xhttp.open("GET", "your_file.txt", true);
xhttp.send();
}
<div id="demo">
<button type="button" onclick="loadXMLDoc()">Change Content</button>
</div>
You don't need the setTimeout either - it's just for demo purposes, so you can actually see and verify the spinner when the response comes back way to fast, i.e. on localhost.

Related

Parsing JSON Array to print specific elements

Im currently trying to parse JSON data from this api in JS but im not sure how to. As of right now when I press any buttons to give me the data, it prints the arrays out rather than the specific data I want. Ive tried to use the JSON Parse function to retrieve the specific data but it seems its not working. Any help would be greatly appreciated! URL to the API docs: https://www.balldontlie.io/#get-all-players
//Loads Player Data
function loadPlayers() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("players").innerHTML =
this.responseText;
}
};
xhttp.open("GET", "https://www.balldontlie.io/api/v1/players", true);
var data = JSON.parse(xhttp.responseText);
console.log(data["last_name"])
xhttp.send();
}
//Loads Game Data
function loadGames() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("games").innerHTML =
this.responseText;
}
};
xhttp.open("GET", "https://www.balldontlie.io/api/v1/games", true);
xhttp.send();
}
//Loads Team Data
function loadTeams() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("teams").innerHTML =
this.responseText;
}
};
xhttp.open("GET", "https://www.balldontlie.io/api/v1/teams", true);
xhttp.send();
}
<!DOCTYPE html>
<html>
<body style="background-color:peachpuff;" >
<center>NBA STATS</center>
<center><marquee behavior="scroll" direction="right" scrollamount="12.5">Data Extracted From BDL API</marquee></center>
<center> View API Docs </center>
<script src="main.js"></script>
<div id="players">
<button type="button" onclick="loadPlayers()">View Players</button>
</div>
<div id = "teams" >
<button type="button2" onclick="loadTeams()">View Teams</button>
</div>
<div id ="games">
<button type="button3" onclick="loadGames()">View Games</button>
<div>
</body>
</html>
You should parse JSON in xhttp.onreadystatechange, that's a callback when request data success.
For the players data as example, it is an object with data and meta, and the players is in data key which is an Array, so you need to loop inside the array to print the values that you needed.
Here's the example for loadPlayers(). You can apply the same concept to loadGames and loadTeams, please let me know if you still having questions.
function loadPlayers() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
// parse JSON after response
var players = JSON.parse(this.responseText);
// get 'data' key inside response
var playersData = players.data;
// loop all the players
for (var player of playersData) {
// print last_name to the #players element
document.getElementById("players").innerHTML += "<br />" + player['last_name'];
}
}
};
xhttp.open("GET", "https://www.balldontlie.io/api/v1/players", true);
xhttp.send();
}
In function loadPlayers()
data is an array not object

how to parse data in javascript

Use the free REST API: https://jsonplaceholder.typicode.com/ to get
100 albums. And display all the albums on the html page as:
UserId: value of userId from the object that came to you,
Id: Id value from the object that came to you,
Title: title value from the object that came to you
As a result, 100 different albums should be parsed on your page.
I tried to parse data and the data becomes a JavaScript object using JSON.parse() but data is showed in json format
<h2>The XMLHttpRequest Object</h2>
<button type="button" onclick="loadDoc()">Change Content</button>
</div>
<script>
function loadDoc() {
const xhttp = new XMLHttpRequest();
const url = "https://jsonplaceholder.typicode.com/albums";
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML =
this.responseText;
}
};
xhttp.open("GET", url, true);
xhttp.send();
}
</script>
It works fine if you add a <div id="demo"></div>:
function loadDoc() {
const xhttp = new XMLHttpRequest();
const url = "https://jsonplaceholder.typicode.com/albums";
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML =
this.responseText;
}
};
xhttp.open("GET", url, true);
xhttp.send();
}
<h2>The XMLHttpRequest Object</h2>
<button type="button" onclick="loadDoc()">Change Content</button>
<div id="demo"></div>

jQuery inside dynamically generated element doesn't run

I have an index which shows a list of orders, each of which calls a function (named dynamically with PHP when I brought the data from the db), to simplify I've reduced the function that each div contains to just an alert. But also every minute an ajax function executes that searches for new orders and appends them on top, with the exact same code as the ones initially loaded. The jQuery works perfectly in the elements that are loaded initially but doesn't work at all in the elements generated dynamically.
This is the index with one initial order inside, BEFORE newOrders runs for the first time. The alert on that order functions properly
<div id="content">
<div id="pedido_4126" class="pedido">
<h4>Pedido 4126</h4>
<button id="btn4126">Alert</button>
<script>
alert("Pedido 4126");
</script>
</div>
</div>
<script>
function newOrders() {
var xhttp = new XMLHttpRequest();
xhttp.open("POST", "simplereq.php", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var response = JSON.parse(this.responseText);
console.log(response);
var element = document.querySelector('#content');
var content = element.innerHTML;
ultimoid = response.ultimoid;
element.innerHTML = response.contenido + content;
}
};
xhttp.send("ultimoid="+encodeURIComponent(ultimoid));
}
setInterval(newOrders, 60000);
</script>
And this is the index when the function has executed once and appended a new order on top with it's corresponding script, dynamically generated and received from the AJAX call:
<div id="content">
<div id="pedido_4255" class="pedido">
<h4>Pedido 4255</h4>
<button id="btn4255">Alert</button>
<script>
alert("Pedido 4255");
</script>
</div>
<div id="pedido_4126" class="pedido">
<h4>Pedido 4126</h4>
<button id="btn4126">Alert</button>
<script>
alert("Pedido 4126");
</script>
</div>
</div>
<script>
function newOrders() {
var xhttp = new XMLHttpRequest();
xhttp.open("POST", "simplereq.php", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var response = JSON.parse(this.responseText);
console.log(response);
var element = document.querySelector('#content');
var content = element.innerHTML;
ultimoid = response.ultimoid;
element.innerHTML = response.contenido + content;
}
};
xhttp.send("ultimoid="+encodeURIComponent(ultimoid));
}
setInterval(newOrders, 60000);
</script>
As you can see, the html and script are exactly the same, but the one on the new order brought by the ajax call, doesn't work.
Ok, so doing more research I came upon the best answer for my case, I'll leave it here in case it helps someone:
In the content I generate in the AJAX call, I print the scripts like this, and obviously hide it with css:
<div class="javascript">
$("body").on("click","#btn4255",function(){
alert("Pedido 4255");
});
</div>
And then I execute this function every time the AJAX call is returned
$('.javascript').each(function() {
eval($(this).text());
});
I only evaluate strings I generate myself so in this case I think it's not unsafe to use eval().

jQuery not working with XMLHttpRequest object

I have an index.php page which loads info.php through AJAX. The info.php content is loaded like this:
<script>
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("data").innerHTML = this.responseText;
}
};
xhttp.open("GET", "info.php", true);
xhttp.send();
}
(function() {
loadDoc()
})();
setInterval ( "loadDoc()", 5000 );
</script>
The info.php file has the following code to do a count up/down from/to a specific number.
<div class="timer count-title count-number" data-from="2000" data-to="300" data-speed="1500"></div>
<script src='includes/jquery-3.2.1.min.js'></script>
<script src="includes/counter.js"></script>
When I visit info.php directly the counter works perfectly fine. However, if I visit index.php, the counter is not even showing. I had the same issue with other jQuery scripts. Even if index.php includes jQuery and the other scripts it still doesn't work. I do want the number to go through the AJAX call since it keeps updating.
Is there a simple solution?
you can do it by JQuery like as follow...
function loadDoc(){
console.log( "call done" );
$( "#data" ).load( "info.php", function() {
console.log( "Load done." );
});
};
$(function(){loadDoc();});
setInterval (loadDoc, 5000 );
I think their problem with your function statement checks this for the following script...
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("data").innerHTML = this.responseText;
}
};
xhttp.open("GET", "info.php", true);
xhttp.send();
}
$(function(){loadDoc();});
setInterval (loadDoc, 5000 );

Ajax -on page load with using a button

Im trying to get ajax to run in a paragraph when the webpage open. I can only get it working if i use a button. Is it possible to have the information from the ajax function to load once the webpage opens?
Here is my code.
<script>
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
document.getElementById('A1').innerHTML = xhttp.status;
document.getElementById('A1').innerHTML = xhttp.statusText;
document.getElementById('A1').innerHTML = xhttp.responseText;
}
};
xhttp.open("GET", "home.xml", true);
xhttp.send();
document.getElementById("demo").innerHTML = xhttp.responseText;
}
</script>
<p > <span id="A1"></span></p>
<button onclick="loadDoc('home.xml')">Get XML data</button>
Whatever function you are invoking, whether it handles ajax or any other calculation, to invoke a function on document load you have to call the function within window.onload
function a(){
...........
}
window.onload = function(){
a();
};
For jquery:
$(document).ready(functon(){
a();
});
or
$(function(){
a();
});
Try:
<body onload="loadDoc('home.xml')">

Categories