How to add auto-refresh to this code? - javascript

My name is John. (Yes I know very useful information :)) I'm create a new statistics in php and my Javascript code look like
var req;
function hide() {
for(var i=0; i<arguments.length; i++) {
element = document.getElementById(arguments[i]);
if (element) {
element.style.visibility = 'hidden';
}
}
}
function show() {
for(var i=0; i<arguments.length; i++) {
element = document.getElementById(arguments[i]);
if (element) {
element.style.visibility = 'visible';
}
}
}
function loadXMLDoc(url) {
if (window.XMLHttpRequest) {
req = new XMLHttpRequest();
req.onreadystatechange = processReqChange;
req.open("GET", url, true);
req.send(null);
hide('lastposts');
show('lastposts_update');
} else if (window.ActiveXObject) {
req = new ActiveXObject("Microsoft.XMLHTTP");
if (req) {
req.onreadystatechange = processReqChange;
req.open("GET", url, true);
req.send();
hide('lastposts');
show('lastposts_update');
}
}
}
function processReqChange() {
if (req.readyState == 4) {
element = document.getElementById('lastposts_text');
if (element) {
if (req.status == 200) {
element.innerHTML = req.responseText;
} else {
element.innerHTML = "Error " + req.status + "<br />" + req.statusText;
}
}
hide('lastposts_update');
show('lastposts');
} else {
var status_message = new Array(
"The query is not initialized",
"The query is created",
"The query is sent",
"The query is processed"
);
element_status = document.getElementById('status');
if (element_status) {
element_status.innerHTML = status_message[req.readyState];
}
}
}
and HTML output
<div id="lastposts_update" style="visibility: hidden;">
<img src="images/refresh.gif" alt="wait">
<span id="status"></span>
</div>
<div id="lastposts" style="z-index: 2;">
<a href="" onclick="loadXMLDoc('{URL}'); return false;">
<img src="images/refresh.gif" alt="refresh" border="0"></a>
<span id="lastposts_text">
{IMPORT_NEW_STATISTICS}
</span>
</div>
How modified this code and add auto-refreshing and remove manual refresh?
Can you help me? I'll be very grateful

Here is the similar QA Auto refresh code in HTML using meta tags
try to put the following code
<meta http-equiv="refresh" content="5">
into HTML header tag.

Related

Parse big JSON Data info HTML Table

I want to implement the JSON File into an HTML Table. In my case it doesnt work however. The table should show all data at once (if possible)
<!DOCTYPE html>
<html>
<body>
<h2>Make a table based on JSON data.</h2>
<p id="demo"></p>
<script>
var obj, dbParam, xmlhttp, myObj, x, txt = "";
obj = { table: "name", limit: 50 };
dbParam = JSON.stringify(obj);
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
myObj = JSON.parse(this.responseText);
txt += "<table border='1'>"
for (x in myObj) {
txt += "<tr><td>" + myObj[x].name + "</td></tr>";
}
txt += "</table>"
document.getElementById("demo").innerHTML = txt;
}
};
xmlhttp.open("GET", "http://infoportal.vag.de/InfoPortal/busstations.xhr", true);
xmlhttp.setRequestHeader("Content-type", "application/json");
xmlhttp.send("x=" + dbParam);
</script>
</body>
</html>
this code should work (but not within this snippet)
const
Limit = 20,
LoadingTable = document.getElementById('Loading-Table')
;
let xdr = getXDomainRequest("get", "http://infoportal.vag.de/InfoPortal/busstations.xhr");
if (!xdr) {
throw new Error("no cross-domain allowed by your browser :/");
};
xdr.onload = function() {
jsonData = JSON.parse(xdr.responseText);
let line = 0;
for (elm in jsonData) {
let
row = LoadingTable.insertRow(line),
c_0 = row.insertCell(0),
c_1 = row.insertCell(1),
c_2 = row.insertCell(2),
c_3 = row.insertCell(3)
;
c_0.textContent = elm;
c_1.textContent = jsonData[elm].name;
c_2.textContent = jsonData[elm].x;
c_3.textContent = jsonData[elm].y;
if (++line >= Limit) break;
}
}
xdr.send();
function getXDomainRequest( method, url ) {
var xdr = null;
if (window.XDomainRequest) { // MS ie
xdr = new XDomainRequest();
xhr.open(method, url);
}
else if (window.XMLHttpRequest) {
xdr = new XMLHttpRequest();
if ('withCredentials' in xdr) {
xdr.open(method, url, true);
}
else {
xdr = null;
}
}
return xdr;
}
body {
font-size: 14px;
font-family: Arial, Helvetica, sans-serif;
}
#Loading-Table {
border-collapse: collapse;
}
#Loading-Table,
#Loading-Table td {
border: 1px solid grey;
}
#Loading-Table td {
padding: 2px 10px;
}
<h2>Make a table based on JSON data.</h2>
<p id="demo"></p>
<table id="Loading-Table" ></table>

onload variable initialization

I have a button which increments a variable value, and I use this variable to load specific content. My problem is that after the page has loaded, I have to click 3 times for the first content load:
1st time I click: I get an undefined result because no ID is loaded
2nd time: the input field value from before I reload the page disappears
3rd time: the first content finally loads
Once the first content has loaded everything works fine. From what I understood it is because the variable isn't initalized at page loading. So I added an onload event but it doesn't work at all.
the script :
var Pokemon_ID = 1
function changePokemon(Pokemon_ID) {
function resetID() {
document.getElementById("id-input").innerHTML = Pokemon_ID;
}
document.getElementById("right-btn").onclick = function() {
Pokemon_ID++;
document.getElementById("id-input").value = Pokemon_ID;
document.getElementById("id-input").click();
}
document.getElementById("left-btn").onclick = function() {
if (Pokemon_ID > 1) {
Pokemon_ID--;
}
document.getElementById("id-input").value = Pokemon_ID;
document.getElementById("id-input").click();
}
if (window.XMLHttpRequest) {
// IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else { //IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var parts = xmlhttp.responseText.split('|')
document.getElementById("img").innerHTML = parts[0];
document.getElementById("name").innerHTML = parts[1];
document.getElementById("type-display1").innerHTML = parts[2];
document.getElementById("categorie").innerHTML = "Categorie: " + parts[3];
document.getElementById("talent").innerHTML = "Talent: " + parts[4];
document.getElementById("taille").innerHTML = "Taille: " + parts[5];
document.getElementById("poids").innerHTML = "Poids: " + parts[6];
}
}
xmlhttp.open("GET", "get_id.php?q=" + Pokemon_ID, true);
xmlhttp.send();
}
<div id="pokedex" onload="resetID()">
<a id="right-btn" onclick="changePokemon(this.value)"></a>
<a id="left-btn" onclick="changePokemon(this.value)"></a>
<form>
<input type="number" id="id-input" onclick="changePokemon(this.value)">
</form>
</div>
I also tried to declare my variable inside the changePokemon() function, but only the first id was loading I couldn't change the value of Pokemon_ID.
I tried to use const and let but both of them also didn't work
You use the same name Pokemon_ID for the global variable and the parameter to the changePokemon() function. The parameter is a local variable, so assignments to it don't affect the global variable. Give it a different name.
You need to take resetID() out of the changePokemon() function. It needs tobe in the global scope so it can be accessed from onclick.
To change an input, you need to assign to .value, not .innerHTML.
DIVs don't have a load event. You need to put onload="resetID()" in the <body> tag, or write:
window.onload = resetID;
in the Javascript.
var Pokemon_ID = 1
function resetID() {
document.getElementById("id-input").value = Pokemon_ID;
}
function changePokemon(Pokemon_val) {
document.getElementById("right-btn").onclick = function() {
Pokemon_ID++;
document.getElementById("id-input").value = Pokemon_ID;
document.getElementById("id-input").click();
}
document.getElementById("left-btn").onclick = function() {
if (Pokemon_ID > 1) {
Pokemon_ID--;
}
document.getElementById("id-input").value = Pokemon_ID;
document.getElementById("id-input").click();
}
if (window.XMLHttpRequest) {
// IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else { //IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var parts = xmlhttp.responseText.split('|')
document.getElementById("img").innerHTML = parts[0];
document.getElementById("name").innerHTML = parts[1];
document.getElementById("type-display1").innerHTML = parts[2];
document.getElementById("categorie").innerHTML = "Categorie: " + parts[3];
document.getElementById("talent").innerHTML = "Talent: " + parts[4];
document.getElementById("taille").innerHTML = "Taille: " + parts[5];
document.getElementById("poids").innerHTML = "Poids: " + parts[6];
}
}
xmlhttp.open("GET", "get_id.php?q=" + Pokemon_val, true);
xmlhttp.send();
}
<div id="pokedex" onload="resetID()">
<a id="right-btn" onclick="changePokemon(this.value)"></a>
<a id="left-btn" onclick="changePokemon(this.value)"></a>
<form>
<input type="number" id="id-input" onclick="changePokemon(this.value)">
</form>
</div>

span tag not working in online name checking using ajax

Here is my code in JavaScript that is calling check.php file for checking online existence of user in the database
<html>
<input type = "text" name="txt1" id="user" onKeyUp="check_username(this.value)"> <br>
<script>
var xmlhttp = false;
if (window.ActiveXObject) {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
} else {
xmlhttp = new XMLHttpRequest();
}
function check_username(str) {
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var arr = xmlhttp.responseText.split("^");
document.getElementById("user").value = arr[1];
if (arr[0] == 1) {
</script>
<span style="color:blue">Username exists</span>
<script>
} else {
</script>
<span style="color:green">user available</span>
<script>
}
}
}
xmlhttp.open("GET", "check.php?txt1="+str, true);
xmlhttp.send();
}
</script>
</html>
And below is check.php file
<?php
mysql_connect("localhost", "root", "");
mysql_select_db("check");
$username = ($_REQUEST['txt1']);
$a = 0;
if (checkexistence($username)) {
$a = 1;
echo $a."^".$username;
} else {
$a = 0;
echo $a."^".$username;
}
function checkexistence($username) {
$check = mysql_query("select uname from t1");
while ($row = mysql_fetch_array($check)) {
if (strcmp($username, $row['uname']) == 0) {
return true;
}
}
return false;
}
?>
It works correctly when I use alert (of course, we cannot use alert as it will become too irritating) but when I am using span tag it do not works correctly giving only
Username exists user available
as output instead of checking after each character we enter in the textfield..
How can I correct it??
Don't close and open the scripts in between of if else statements.
You can achieve this using jQuery library in easily. Download the jQuery library from here. You can include this jQuery files in bottom of the page, like this
<script src="js/jquery.1.11.0.js" type="text/javascript"></script>
Let's do that in different way of manner. Use jQuery method of after() to insert a content in between any where.
And try this code,
<input type = "text" name="txt1" id="user" onKeyUp="check_username(this.value)"> <br>
<span id="exist" style='color:blue'></span>
<span id="avail" style='color:green'></span>
<script>
var xmlhttp = false;
if (window.ActiveXObject) {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
} else {
xmlhttp = new XMLHttpRequest();
}
function check_username(str) {
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var arr = xmlhttp.responseText.split("^");
document.getElementById("user").value = arr[1];
if (arr[0] == 1) {
$("#avail").html();
$("#exist").html('Username exists');
} else {
$("#exist").html();
$("#avail").html('User available');
}
}
}
xmlhttp.open("GET", "check.php?txt1="+str, true);
xmlhttp.send();
}
</script>

how to separate the response div ids in ajax call

Please help me out to resolve the issue.
function createRequestObject(){
var req;
if(window.XMLHttpRequest){
//For Firefox, Safari, Opera
req = new XMLHttpRequest();
}
else if(window.ActiveXObject){
//For IE 5+
req = new ActiveXObject("Microsoft.XMLHTTP");
}
else{
//Error for an old browser
}
return req;
}
var http = createRequestObject();
function empajax(method,nameId)
{
url='college/cat/employee.jsp'+"?nameId="+nameId;
if(method == 'POST'){
http.open(method,url,true);
http.onreadystatechange = handleResponse;
http.send(null);
}
}
function handleResponse(){
if(http.readyState == 4 && http.status == 200){
var response = http.responseText;
if(response){
$("#empname").html(response);
$("#empnumber").html(response);
}
}
}
In the above ajax function, employee.jsp is returing below values in below divs. How to separate the div responses in the habdleResponse() function to set the values in corresponding divs like (empname,empnumber)
<div>
<b>ram</b>
</div>
<div>
<b>1234</b>
</div>
I just wan to set the employee name in the empname div and employee number in the empnumber div.
Thanks in advance!
You need to traverse your XML dom:
function handleResponse(){
if(http.readyState == 4 && http.status == 200){
var xmlResponse = xmlHttp.responseXML;
root = xmlResponse.documentElement;
names = root.getElementsByTagName("empname");
numbs = root.getElementsByTagName("empnum");
for (var i = 0 ; i < numbs.length; i++) {
throw(names[i].firstChild.data, numbs[i].firstChild.data);
}
Then just pass over the variables to a function that will throw them in the document:
function throw(name , number) {
var divider = document.createElement('div') ;
divider.innerHTML = "<div class='name'>" + name + " </div> <div class='numb'>" + number +"</div>"
document.appendChild(divider);
}
And then you'll have it. A separate div for each of your entry.

AJAX loader animation not showing

I have an AJAX script which should trigger a loading image once executed and then hide it once I get the result from the web-service, however the image is now showing.
My code is as below:
<script type="text/javascript">
function get_Code_Results() {
document.getElementById("loader").innerHTML = "<img src=\'loading.gif\' />";
var url = document.location;
if (window.XMLHttpRequest) req = new XMLHttpRequest();
else if (window.ActiveXObject) req = new ActiveXObject("Microsoft.XMLHTTP");
req.onreadystatechange = processRequest;
// req.open("GET", url, true);
// req.send(null);
req.open("POST",url,true);
req.setRequestHeader("Content-type","application/x-www-form-urlencoded");
req.send("isbns="+document.getElementById("Code").value);
function processRequest() {
if (req.readyState == 4 && document.getElementById("1").checked == true) {
document.getElementById("results").value = "myfirsturl.com" + req.responseText;
}
else if (req.readyState == 4 && document.getElementById("2").checked == true) {
document.getElementById("results").value = "myurl.com" + req.responseText;
}
}
}
</script>
and I have a position where I want the loader to be displayed:
<div id="loader"><img src="loading.gif" style="display:none;" /></div>
Where do I have the mistake in my code? Some advice would be greatly appreciated!
<div id="loader"><img src="loading.gif" style="display:none;" /></div>
You need to change the style="display:none;". I suggest you write the following code instead :
<div id="loader" style="display:none;"><img src="loading.gif" /></div>
Then when needed :
$('#loader').show(); // To show the laoding icon
$('#loader').hide(); // To hide it
Your functions are nested. I guess you pretend to write somethin like:
function get_ISBN_Results() {
document.getElementById("loader").innerHTML = "<img src=\'loading.gif\' />";
var url = document.location;
if (window.XMLHttpRequest) req = new XMLHttpRequest();
else if (window.ActiveXObject) req = new ActiveXObject("Microsoft.XMLHTTP");
req.onreadystatechange = processRequest;
// req.open("GET", url, true);
// req.send(null);
req.open("POST",url,true);
req.setRequestHeader("Content-type","application/x-www-form-urlencoded");
req.send("isbns="+document.getElementById("isbns").value);
}
function processRequest() {
if (req.readyState == 4 && document.getElementById("book").checked == true) {
document.getElementById("results").value = "myfirsturl.com" + req.responseText;
}
else if (req.readyState == 4 && document.getElementById("magazine").checked == true) {
document.getElementById("results").value = "myurl.com" + req.responseText;
}
}

Categories