AJAX repeatitive values php for a simple to-do app - javascript

I have the following issue when adding new items. When I add a new item, multiple values are spit. I entered the first 2 in db (phpmyAdmin). The click button displays the new data without the refreshing the page. Different number of copies are returned on each click. sometimes 7 as below, sometimes 13, 30 even up to 100+ copies if the execution hangs for long. Could the onload=process() on <body> be affecting the call?
When I enter a new value, It displays multiple values. (Edit: Apologies. In the snapshot below, ["rd] is meant to spell [new])
Where could the bug be?
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>To Do List</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="http://fonts.googleapis.com/css?family=Open+Sans" rel="stylesheet">
<link href="css/main.css" rel="stylesheet">
<script
src="https://code.jquery.com/jquery-3.2.1.min.js"
integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
crossorigin="anonymous">
</script>
<script src="js/item.js" type="text/javascript"></script>
</head>
<body onload="process()">
<div class="list">
<h1 class="header">My To Do</h1>
<div id="todo-items"></div>
</div>
<div class="list">
<div id="item-add" >
<input type="text" id="name" name="name" placeholder="Enter new item" class="input" autocomplete="off">
<button id="add">Add Item</button><br /><br />
<div id="status"></div>
</div>
</div>
</body>
item.js
var xmlHttp = createXmlHttpRequestObject();
function createXmlHttpRequestObject() {
var xmlHttp;
if(window.ActiveXObject) {
try {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch(e) {
xmlHttp = false;
}
} else {
try {
xmlHttp = new XMLHttpRequest();
} catch(e) {
xmlHttp = false;
}
}
if(!xmlHttp) {
alert("cant create that object hoss");
} else {
return xmlHttp;
}
}
function fetch_data(){
$.ajax({
url:"/to-do-list/display.php",
method:"POST",
success:function(data){
$('#todo-items').html(data);
}
});
}
fetch_data();
function process() {
$(document).ready(function(){
$(document).on('click', '#add', function(){
$.ajax({
url:"/to-do-list/add.php",
method:"POST",
data:{name:name},
success:function(data){
//console.log(data + 'hi');
//$('#item-add').submit( function() {
// console.log("are you returning false?");
// return false;
//});
function clearinput (){
$('#item-add :input').each( function(){
$(this).val('');
});
}
clearinput();
fetch_data();
}
});
});
});
if (xmlHttp.readyState==0 || xmlHttp.readyState==4) {
name = encodeURIComponent(document.getElementById('name').value);
xmlHttp.open("GET", "item.php?name="+name, true);
xmlHttp.onreadystatechange = handleServerResponse;
xmlHttp.send(null);
} else {
setTimeout('process()', 1000);
}
}
function handleServerResponse(){
if(xmlHttp.readyState==4) {
if(xmlHttp.status==200){
xmlResponse = xmlHttp.responseXML;
xmlDocumentElement = xmlResponse.documentElement;
console.log(xmlResponse.documentElement);
message = xmlDocumentElement.firstChild.data;
// message = "colin";
document.getElementById('status').innerHTML =
'<span style="color:blue">' + message + '</span>';
setTimeout('process()', 1000);
} else {
alert('Something went wrong!');
}
}
}

Found the bug. Took the ajax call out of the onload function in item.js

Related

Desperately trying to figure out how to display API info on HTML website [duplicate]

This question already has answers here:
How can I use setInterval and clearInterval?
(5 answers)
Closed 2 years ago.
Im trying to figure out a way to display crypto currency prices in real time on my website. So far Ive got a script that works at posting the current price but im having trouble using the setinterval to autorefresh the data. This is the code im using, and I think ive lost it at the setinterval part, please help!!!
<html>
<head>
<title>Test Site</title>
<style type="text/css">
#data {
text-align: center;
}
</style>
</head>
<body>
<div id="data" />
<script type="text/javascript">
var xmlhttp = new XMLHttpRequest();
var url = "https://api.coindesk.com/v1/bpi/currentprice.json";
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var json = JSON.parse(this.responseText);
parseJson(json);
}
};
xmlhttp.open("GET", url, true);
xmlhttp.send();
function parseJson(json) {
var usdValue = "Bitcoin Price: $" + json["bpi"]["USD"]["rate"];
document.getElementById("data").innerHTML =
usdValue;
}
setInterval(data, 3000);
</script>
</body>
</html>
I have updated your a bit please have a look it will work for you.
<html>
<head>
<title>Test Site</title>
<style type="text/css">
#data {
text-align: center;
}
</style>
</head>
<body>
<div id="data" />
<script type="text/javascript">
function loadBitCointPrice(){
var xmlhttp = new XMLHttpRequest();
var url = "https://api.coindesk.com/v1/bpi/currentprice.json";
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var json = JSON.parse(this.responseText);
parseJson(json);
}
};
xmlhttp.open("GET", url, true);
xmlhttp.send();
}
function parseJson(json) {
var usdValue = "Bitcoin Price: $" + json["bpi"]["USD"]["rate"];
document.getElementById("data").innerHTML = usdValue;
}
setInterval(function(){
loadBitCointPrice();
}, 3000);
</script>
</body>
</html>
You need to wrap the code that pulls the data in a function, and then use setInterval to call that function:
function pullData() {
var xmlhttp = new XMLHttpRequest();
var url = "https://api.coindesk.com/v1/bpi/currentprice.json";
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var json = JSON.parse(this.responseText);
parseJson(json);
}
};
xmlhttp.open("GET", url, true);
xmlhttp.send();
function parseJson(json) {
var usdValue = "Bitcoin Price: $" + json["bpi"]["USD"]["rate"];
document.getElementById("data").innerHTML =
usdValue;
console.log('Data updated at', new Date())
}
}
pullData() // Call it immediately the first time.
setInterval(pullData, 3000);
<html>
<head>
<title>Test Site</title>
<style type="text/css">
#data {
text-align: center;
}
</style>
</head>
<body>
<div id="data" />
</body>
</html>

Trying to run a console log on php file storing json but callback error and 404 (not found)

Working with trying to learn json and ajax and how they interoperate with html and javascript
I have a php with json data inside
I am trying to get the json data formatted into the html page but I keep getting error that "callback is not a function"
I am running the php and html files on my MAMP server to simulate a api feed
I will share my html and js files
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="style.css" rel="stylesheet" type="text/css">
<script src="run2.js"></script>
<title>Ajax Demo</title>
</head>
<body>
<h1 class="title">Todays Weather Forecast</h1>
<p class="sub">Click the button the check the local weather.</p>
<button class="demo-centered" type="button" onclick="loadPhp()">Check Weather</button><br><br>
<p id="demo"></p>
</body>
</html>
var loadPhp = function(url, callback) {
var xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.responseType = 'json';
xhr.onload = function () {
var status = xhr.status;
if (status == 200) {
callback(null, xhr.response);
} else {
callback(status);
}
};
xhr.send();
};
loadPhp('demo.php', function (err, data) {
if (err != null) {
alert('Something went wrong: ' + err);
} else {
for (var i = 0; i < data.length; i++) {
for (x in data[i]) {
console.log(data[i][x]);
}
}
}
});
PHP just in case
{"coord":{"lon":-116.8,"lat":33.03},"weather":[{"id":802,"main":"Clouds","description":"scattered clouds","icon":"03d"}],"base":"stations","main":{"temp":293.73,"feels_like":289.89,"temp_min":289.26,"temp_max":295.93,"pressure":1016,"humidity":52},"visibility":16093,"wind":{"speed":5.7,"deg":260},"clouds":{"all":40},"dt":1589408840,"sys":{"type":1,"id":5686,"country":"US","sunrise":1589374130,"sunset":1589423903},"timezone":-25200,"id":5391832,"name":"San Diego County","cod":200}
You have to create a javascript function called callback to do what the you want the callback to do.

window.onload function is not getting called on the page

My code is as shown below:
xyz.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Status</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<div style="width: 300px;padding: 10px;margin: 0 auto;background: #f2f2f2;">
<form name="Form">
<input type="hidden" name="Status" value="<?php echo $_POST['Status'] ?>" />
</form>
<script type="text/javascript">
alert(window.onload);
window.onload = function() {
var xhr = new XMLHttpRequest();
xhr.open('POST', 'http://api.com');
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.onload = function() {
if (xhr.status === 200) {
var apiresponse = JSON.parse(xhr.response);
console.log(apiresponse);
if (apiresponse.status == "200") {
document.getElementById('response').innerHTML = apiresponse.message + '<br/> Press back button to continue in App.';
} else {
document.getElementById('response').innerHTML = JSON.stringify(apiresponse);
}
} else {
document.getElementById('response').innerHTML = JSON.stringify(xhr);
}
};
var elements = document.forms['Form'].elements;
let formBody = [];
for (var i = 0, element; element = elements[i++];) {
let encodedKey = encodeURIComponent(element.name);
let encodedValue = encodeURIComponent(element.value);
formBody.push(encodedKey + "=" + encodedValue);
}
formBody = formBody.join("&");
document.getElementById('request').innerHTML = formBody;
xhr.send(formBody);
}
</script>
</body>
</html>
when I run the above code, in alert method I get null value and the function below it given with window.onload = function() is not getting called at all. So is there anything which needs to be included to get it done.
When you call alert(window.onload) it is null because you have not assigned a function to window.onload. Your alert proves nothing.
For a sanity check, add the code alert('hello world'); above the line var xhr = new XMLHttpRequest(); in the function you bind to window.onload. You will probably find that your function is being called but its behavior is not acting as you expect, so you think your function is NOT being called on window.onload but it actually is.

Why The News Is Not Being Pulled [XML JS Query]

Here's my code.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>News Site</title>
<script>
window.document.onload = function () {
var xhttp = new XMLHttpRequest();
xhttp.open("GET", "cdcatalog.xml", true);
xhttp.send();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var xmlDoc = this.responseXML;
console.log(xmlDoc);
document.getElementById("demo").innerHTML = xmlDoc.getElementsByTagName("TITLE")[0].childNodes[0].nodeValue + "<br/>" + xmlDoc.getElementsByTagName("PRICE")[0].childNodes[0].nodeValue;
} else {
document.getElementById("demo").innerHTML = "Can't show it.";
}
}
}
</script>
</head>
<body>
<div id="demo"></div>
</body>
</html>
I am a beginner in using Ajax and this is my first project. I checked with the format, even validated it with W3 Validator, and it doesn't seem to work.
Nothing is showing on the page. It's completely blank.
Can anyone point out my mistake please?
The document object does not have an onload property. Using that style of event handler assignment, you are looking for window.onload.

simple ajax nothing happens

I trying to create a small ajax script that add some text into div.
nothing happen, it's killing me.
please help.
HTML:
<!DOCTYPE>
<html>
<head>
<script type="text/javascript" src="ajax.js"></script>
<script type="text/javascript" src="jquery.js"></script>
</head>
<body onload="process()">
OK, you made it this far
<br/>
<div id="theD">
</div>
</body>
</html>
ajax.js:
var xmlHttp= createXmlHttpRequestObject();
function createXmlHttpRequestObject(){
var xmlHttp;
if (window.XMLHttpRequest)(
xmlHttp = new XMLHttpRequest();
)else{
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP")
}
return xmlHttp;
}
function process(){
alert('hi');
if (xmlHttp){
try{
xmlHttp.open("GET", "ajax.txt", true);
xmlHttp.onreadystatechange = handleServerResponse;
xmlHttp.send(null);
}catch(e){
alert(e.toString());
}
}
}
function handleServerResponse(){
theD = documet.getElementById('theD');
if (xmlHttp.readyState==1){
theD.innerHTML += "Status1:server connection established <br/>";
}else if (xmlHttp.readyState==4){
if (xmlHttp.status=200){
try{
text=xmlHttp.responseText
theD.innerHTML += "Status4:request finish<br/>";
theD.innerHTML += text;
}catch(e){
alert(e.toString);
}
}else{
alert((xmlHttp.statusText);
}
}
}
the ajax.txt contain a simple string.
this is xhr2 if you want more browser support you can extend it.
http://caniuse.com/xhr2
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>ajax</title>
<script>
function ajax(a,b,c){ // Url, Callback, just a placeholder
c=new XMLHttpRequest;
c.open('GET',a);
c.onload=b;
c.send()
}
function h(){
document.getElementById('theD').innerText=this.response
}
window.onload=function(){
ajax('ajax.txt',h);
}
</script>
</head>
<body>
<div id="theD"></div>
</body>
</html>
if you have any questions about how this works or how you can extend it just ask
here you have some more info about this
https://stackoverflow.com/a/18309057/2450730
you can add ie support
by replacing
c=new XMLHttpRequest;
with
c=new XMLHttpRequest||new ActiveXObject("MSXML2.XMLHTTP.3.0");
and using onreadystatechange

Categories