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.
Related
I had similar code run before but now i've lost it. No matter what I do, it will never run the php code.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script>
function kosarica() {
var vrednost = "Itworks!";
var httpr=new XMLHttpRequest();
httpr.open("POST","izpis3.php",true);
httpr.setRequestHeader("Content-type","aplication/x-www-form-urlencode");
httpr.onreadystatechange=function(){
if(httpr.readyState==4 && httpr.status ==200){
document.getElementById("responce").innerHTML=httpr.responseText;
}
httpr.send("vrednost"+vrednost);
}
}
</script>
</head>
<body>
<p id="responce">a</p>
<button onclick="kosarica()">Click me</button>
</body>
</html>
PHP Code:
<?php
echo $_POST['vrednost'];
?>
I know that I can make code for this example all in javascript but I want to run more php code where it access my database.
It does not fail, but it does never happen. You need to move the send() outside the handler.
The content type is wrong.
You need to use an equal sign to make it a variable for PHP.
Please do not use var keyword. Use const for a constant or let for a variable.
function kosarica() {
const vrednost = "Itworks!";
const httpr = new XMLHttpRequest();
httpr.open("POST", "izpis3.php", true);
httpr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
httpr.onreadystatechange = function () {
if (httpr.readyState === 4 && httpr.status === 200) {
document.getElementById("responce").innerHTML = httpr.responseText;
}
}
httpr.send("vrednost=" + vrednost);
}
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>
Im trying to make a POST call on a JSON based API, but im keep getting Status:400, bad request.
Here is my current code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>API TEST</title>
</head>
<body>
<button onclick="myFunction()">Test</button>
<div id="result"></div>
<script>
function myFunction() {
const xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
//alert(this.status);
alert(this.readyState);
if (this.readyState == 4 && this.status == 200) {
document.getElementById("result").innerHTML = this.responseText;
}
};
xhr.open("POST", URL);
xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
xhr.send(JSON.stringify({username: "test", password: "test"}))
}
</script>
</body>
</html>
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.
I want to make a JS Ajax request but it doesn't work.
I wrote this code:
var i=0;
function send()
{
var request = new XMLHttpRequest();
request.open("GET", 'support.html', true);
request.send(null);
request.onreadystatechange = interpretRequest;
i++;
document.getElementById("debug").innerHTML=document.getElementById("debug").innerHTML+i;
}
function interpretRequest() {
document.getElementById("answer").innerHTML=document.getElementById("answer").innerHTML+"answer received";
document.getElementById("answer").innerHTML=document.getElementById("answer").innerHTML+request.status;
document.getElementById("answer").innerHTML=document.getElementById("answer").innerHTML+request.readyState;
switch (request.readyState) {
// if readyState == 4 and status == 200
case 4:
document.getElementById("Antwort").innerHTML=document.getElementById("Antwort").innerHTML+" answer received and state 4";
if (request.status != 200) {
alert("Error"+request.status);
} else {
var content = request.responseText;
// write content
document.getElementById("content").innerHTML = content;
}
break;
default:
break;
}
}
The function send is called by an intervall every s.I see that this works because
the nummers appears in the debug div. The function interpretRequest is called too. The string "answer received" appears but there is no print out which contains the request.status. In addition case 4 is never entered and the content div stays empty.
The HTML File is:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Test</title>
<script type="text/javascript" src="code.js"></script>
</head>
<body>
<div id="debug">Debug:</div>
<br /><hr />
<div id="content">HTML:</div>
<br /><hr />
<div id="answer">answer:</div>
</body>
</html>
The support.html is in the same folder and it contains:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<h3>It works It works It works It works It workIt works</h3>
</body>
</html>
request isn't a global, so you can't access it from the interpretRequest function.
Use this instead.