Open method in ajax call not responding - javascript

I am new to JSON and AJAX,
SO i tried this piece of code to get JSON data from the url mentioned and then using a AJAX call i tried to print it on console, however nothing gets printed on the console.
Please someone correct what is it that i am doing wrong here, below is the code snippet.
var req = new XMLHttpRequest();
var btn = document.getElementById("btn");
var display = document.getElementById("display");
req.open("GET", "http://www.filltext.com/?rows=10&id={index}&email={email}&username={username}&password={randomString|5}&pretty=true", true);
btn.addEventListener("click",function(){
req.onreadystatechange = function() {
var res = req.responseText;
Console.log(res);
};
});
req.send();
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<h1>Hello</h1>
<Button id= 'btn'>click me</Button>
<div id = 'display'></div>
<script>"Test.js"</script>
</body>
</html>

When you set req.onreadystatechange inside btn event you only add the callback to request. The problem is the request has already been made. You need to make request on btn click, then you call send() inside the btn action.
console instead of Console
var req = new XMLHttpRequest();
var btn = document.getElementById("btn");
var display = document.getElementById("display");
req.open("GET", "http://www.filltext.com/?rows=10&id={index}&email={email}&username={username}&password={randomString|5}&pretty=true", true);
req.onreadystatechange = function() {
var res = req.responseText;
console.log(res);
};
btn.addEventListener("click",function(){
req.send();
});
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<h1>Hello</h1>
<Button id= 'btn'>click me</Button>
<div id = 'display'></div>
<script>"Test.js"</script>
</body>
</html>

You need to change your JS code and put everything inside the block, so it looks nice :)
var btn = document.getElementById("btn");
var display = document.getElementById("display");
btn.addEventListener("click", function() {
req = new XMLHttpRequest();
req.open("GET", "http://www.filltext.com/?rows=10&id={index}&email={email}&username={username}&password={randomString|5}&pretty=true", true);
req.send();
req.onreadystatechange = function() {
var res = req.responseText;
console.log(res);
};
});

Related

Image link from JSON and apply it to HTML

I have created a weather app where I collect the data from an API and receive it as JSON file and it is working well, I just have one issue where I want to get the icon from the link in JSON and apply it to my HTML so I can see it myself.
Very basic HTML
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>weather api</title>
</head>
<body>
<div id="data-result"></div>
<div id="data-result-temp"></div>
<img id="data-result-icon" src="" alt=""> // I changed this a lot but did not really work.
</body>
<script src="app.js"></script>
</html>
and my JS code here
var url = "https://api.weatherapi.com/v1/current.json?key=1a4795e3c8a64d0ba4b92322202711&q=Istanbul";
const city = document.querySelector("#data-result");
const temp = document.querySelector("#data-result-temp");
const icon = document.querySelector("#data-result-icon");
const xhr = new XMLHttpRequest();
xhr.open("GET", url);
xhr.onload = function(data, status) {
const response = JSON.parse(xhr.response);
console.log(response);
if (xhr.status === 200) {
city.innerHTML = response.location.name;
temp.innerHTML = response.current.temp_c;
icon.innerHTML = response.current.condition.icon; // dont really know how to update
} else {
/** .. **/
}
}
xhr.onerror = function(err) {
console.log(`Network Error`, err);
};
xhr.send();
thanks!
Change the innerHTML attribute in the icon element into src attribute. Then you can display the icon. Check the below example
var url = "https://api.weatherapi.com/v1/current.json?key=1a4795e3c8a64d0ba4b92322202711&q=Istanbul";
const city = document.querySelector("#data-result");
const temp = document.querySelector("#data-result-temp");
const icon = document.querySelector("#data-result-icon");
const xhr = new XMLHttpRequest();
xhr.open("GET", url);
xhr.onload = function(data, status) {
const response = JSON.parse(xhr.response);
console.log(response);
if (xhr.status === 200) {
city.innerHTML = response.location.name;
temp.innerHTML = response.current.temp_c;
icon.src = "https:"+response.current.condition.icon;
} else {
/** .. **/
}
}
xhr.onerror = function(err) {
console.log(`Network Error`, err);
};
xhr.send();
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>weather api</title>
</head>
<body>
<div id="data-result"></div>
<div id="data-result-temp"></div>
<img id="data-result-icon" src="" alt="">
</body>
</html>
I think what you're looking for is:
icon.src = response.current.condition.icon;
So you're updating the src of the img rather than innerHTML.
Your current code will just return this:
<img id="data-result-icon" src="" alt="">//cdn.weatherapi.com/weather/64x64/day/113.png</img>

How do I create an express route that handles an HTTP GET request which sends an a href tag

How do I create an express route that handles an HTTP GET request which sends an a href tag containing a link to an email address? Given No DOCTYPE declaration, html, head, body, or other tags should be present.
Here's what I've tried and it doesn't work:
router.get('/contact.ajax', function(req, res, next) {
res.send(aaa#gmail.com);
});
in HTML:
<!DOCTYPE HTML>
<html>
<head>
<title></title>
</head>
<body>
<h1>My AJAX Site</h1>
<p><button id = "contactButton" onclick = "buttonClicked()">Contact</button></p>
<div id = "mainDiv"></div>
<script>
function buttonClicked(){
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function(){
if(this.readyState ==4 && this.status == 200){
var mainDiv = document.getElementById("mainDiv");
mainDiv.appendChild(xhttp.responseText);
}
};
xhttp.open("GET","/contact.ajax",true);
xhttp.send();
}
</script>
</body>
</html>
Thank you in advance!
The only thing you need to send from express (or your serverside code) is the email in a string.
res.send('aaa#gmail.com')
Then when you get the string on the client side you can inject it into a tag.
let mainDiv = document.getElementById('mainDiv')
mainDiv.innerHTML = `${responseText}`
Note this is a simplified version.

HTTP request Readystate=4 and Status=400

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>

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.

Categories