JSON print to HTML - javascript

Any idea what's the best way to get json from webhook to HTML?
I already got to the step where I can print the json from the webhook and a json in script and It looks THE SAME but the one from webhook gives "undefined".
<body>
<h2>Print from Integromat</h2>
<p id="demo"></p>
<script>
let xhr = new XMLHttpRequest();
xhr.open("POST", "https://hook.integromat.com/xyxyxyxyxyxyxyxyxyx", true);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.onload = function(e) {
// Error...
if (this.status != 200) return alert("Error")
// Success..
let json = JSON.stringify(this.response);
let text = "";
for(let i = 0; i < json.length; i++) {
let obj = json[i];
text += obj.firstname + "<br>";
text += obj.email + "<br><hr>"
}
document.getElementById("demo").innerHTML = text;
}
xhr.send(JSON.stringify({
//JSON to send
date: new Date(),
}));
</script>
</body>
Thanks a lot!

Related

XML response text is undefined

I am making a call to an external server and am getting a valid response back with data. If I dump that data into console.log() I can see the data that I'm looking for. However the returned data is XML and if I try and use the getElementsByTagName method on the response text I get the error Uncaught TypeError: searchResults.getElementsByTagName is not a function. I checked and searchResults is undefined, which I'm assuming is my problem, I'm just not sure how to fix it.
function getBggData() {
var searchTerm = document.getElementById("searchTerm").value;
// console.log("Search Term = " + searchTerm);
var httpURL = "https://www.boardgamegeek.com/xmlapi2/search?type=boardgame,boardgameexpansion&query=" + searchTerm
// console.log("URL used is = " + httpURL);
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
displayData(this);
}
};
xhttp.open("GET", httpURL, true);
xhttp.send();
};
function displayData(xml) {
var i;
var searchResults = xml.responseText;
console.log(searchResults.type);
console.log(searchResults);
var table = "<tr><th>Game</th><th>Year Released</th></tr>";
var x = searchResults.getElementsByTagName("item");
document.getElementById("resultsHeader").innerHTML = "Search Results = " + x + " items.";
document.getElementById("searchResults").innerHTML = table;
};
you can do like this,
var parser = new DOMParser();
var xmlDoc = parser.parseFromString(xml,"text/xml");
console.log(xmlDoc.getElementsByTagName("title")[0]);
here we are parsing the xml and getting it to the variable xmlDoc
var searchResults = xml.responseXML;

Value of list populated with javascript

How to populate the select list with the values that I got with javascript?
I am sending a GET request to a .php site which gives me the respond in JSON format. Now I want to put those lines I got into the select list.
<select id = "list" name=log size=50 style=width:1028px>
<script type="text/javascript">
window.onload = function () {
var bytes=0;
var url = "/test/log.php?q='0'";
function httpGet(url)
{
var xhttp = new XMLHttpRequest();
var realurl = url + bytes;
xhttp.open("GET", url, true);
xhttp.onload = function (e) {
if (xhttp.readyState === 4) {
if (xhttp.status === 200) {
console.log(xhttp.responseText);
var response=JSON.parse(xhttp.responseText);
var log = response.key;
bytes = log.length;
}
};
xhttp.onerror = function (e) {
console.error(xhttp.statusText);
}
};
xhttp.send();
}
var updateInterval = 2000;
function update() {
httpGet(url);
setTimeout(update, updateInterval);
}
update();
}
</script>
</select>
The response I get from log.php is "{"key":"whole log file"}". Now I want to store that reponse into a list and populate it every 2 seconds.
Loop over the contents of the returned string after JSON.parse-ing it. Create option elements from it, and insert those into the select.
var html = "";
var obj = JSON.parse(xhttp.responseText);
for(var key in obj) {
html += "<option value=" + key + ">" +obj[key] + "</option>";
}
document.getElementById("list").innerHTML = html;
See JSBin

Can't get weather asynchronously using openweathermap API

I'm trying to retrieve data using the openweathermap API. I can get it to work, but I can't seem to do it asynchronously. This causes the following error:
Content-Type is not allowed by Access-Control-Allow-Headers in preflight response.
Form:
<label>Zipcode: </label>
<form>
<input type="text" id="locationField" name="locationField">
<input type="submit" id="weatherSubmit" value="Get Weather">
</form>
<div>
<br>
<label>Location:</label>
<div id="location"></div>
<br>
<label>Temperature:</label>
<div id="temperature"></div>
<br>
<label>Humidity</label>
<div id="humidity"></div>
</div>
Script:
document.getElementById('weatherSubmit').addEventListener('click', function(event) {
var zipcode = document.getElementById('locationField').value;
var req = new XMLHttpRequest();
var payload = {location: null, temperature:null, humidity:null};
req.open("GET", "http://api.openweathermap.org/data/2.5/weather?q=" + zipcode + ",us&appid=fa7d80c48643dfadde2cced1b1be6ca1", true);
req.setRequestHeader('Content-Type', 'application/json');
req.addEventListener('load',function(){
if(req.status >= 200 && req.status < 400){
var response = JSON.parse(req.responseText);
document.getElementById('location').textContent = response.name;
document.getElementById('temperature').textContent = response.main.temp;
document.getElementById('humidity').textContent = response.main.humidity;
} else {
console.log("Error in network request: " + request.statusText);
}});
req.send(JSON.stringify(payload));
event.preventDefault();
});
I can get this to work if I don't use AJAX, but that's not the way I want to do it. The following code works if foo() is called onclick from the submit button and passes in the zip code value.
function foo(value) {
var req = new XMLHttpRequest();
req.open("GET", "http://api.openweathermap.org/data/2.5/weather?q=" + value + ",us&appid=fa7d80c48643dfadde2cced1b1be6ca1", false);
req.send(null);
var response = JSON.parse(req.responseText);
document.getElementById('location').textContent = response.name;
var f = ((response.main.temp - 273.15) * 9 / 5) + 32;
document.getElementById('temperature').textContent = f + "f";
document.getElementById('humidity').textContent = response.main.humidity + "%";
}
Get rid of the setRequestHeader
var req = new XMLHttpRequest();
var payload = {location: null, temperature:null, humidity:null};
req.open("GET", "http://api.openweathermap.org/data/2.5/weather?q=02143,us&appid=fa7d80c48643dfadde2cced1b1be6ca1", true);
//req.setRequestHeader('Content-Type', 'application/json');
req.addEventListener('load',function(){
if(req.status >= 200 && req.status < 400){
var response = JSON.parse(req.responseText);
console.log(response);
//document.getElementById('location').textContent = response.name;
//document.getElementById('temperature').textContent = response.main.temp;
//document.getElementById('humidity').textContent = response.main.humidity;
} else {
console.log("Error in network request: " + request.statusText);
}});
req.send(null);
Works great!
BTW. Change your API key :(
It's a problem with CORS. The workaround is to use JSONP. It seems to be supported by OpenWeatherMap's API.
function foo(value) {
window.weatherCallback = function(response) {
document.getElementById('location').textContent = response.name;
var f = ((response.main.temp - 273.15) * 9 / 5) + 32;
document.getElementById('temperature').textContent = f + "f";
document.getElementById('humidity').textContent = response.main.humidity
delete window.weatherCallback; // delete the property
};
var script = document.createElement('script');
script.src = '//api.openweathermap.org/data/2.5/weather?q=" + value + ",us&appid=fa7d80c48643dfadde2cced1b1be6ca1&callback=weatherCallback';
document.head.appendChild(script);
}
Can't test it though, as I don't have the key for API.

data is not showing in dropdown

I am very new in javascipt infact this is my first program.
i have written html javascrpit code to shoow data in dropdown from python django databse but when i run it, it is not showing data my code is
<!DOCTYPE html>
<html>
<title>CP Project</title>
<head>
</head>
<body>
Country : <select class="country" onchange="changeCountry(this)">
</select><br/>
State :
<select class="state" onchange="changeState(this)">
</select><br/>
City :
<select class="city" onchange="changeCity(this)">
</select>
<script>
var country = document.querySelector(".country");
var state = document.querySelector(".state");
var city = document.querySelector(".city");
var countryList = {};
var stateList = {};
var cityList = {};
// Access-Control-Allow-Origin: http://127.0.0.1:8002/data/ ;
Access-Control-Allow-Methods: POST, GET, OPTIONS;
getCountryList(function(response){
countryList = response;
var tempStr = "";
/*for(var i in response.result){
tempStr+="<option value="+i+">"+response.result[i]+"</option>";
}*/
for(var i=0;i<response.length; i++){
tempStr+="<option value="+response[i].countryId+">"+response[i].country+"</option>";
}
country.innerHTML = tempStr;
});
function changeCountry(this_){
getStateList(this_.value, function(response){
stateList = response;
var tempStr = "";
/*for(var i in response.result){
tempStr+="<option value="+i+">"+response.result[i]+"</option>";
}*/
for(var i=0;i<response.length; i++){
tempStr+="<option value="+response[i].state_id+">"+response[i].state+"</option>";
}
http.open("GET", "http://127.0.0.1:8002/data/country/", true);
http.send();
state.innerHTML = tempStr;
});
}
function changeState(this_){
getCityList(this_.value, function(response){
cityList = response;
var tempStr = "";
/*for(var i in response.result){
tempStr+="<option value="+i+">"+response.result[i]+"</option>";
}*/
for(var i=0;i<response.length; i++){
tempStr+="<option value="+response[i].cityid+">"+response[i].city+"</option>";
}
city.innerHTML = tempStr;
});
}
function getCountryList(callBackFun){
var http = new XMLHttpRequest();
http.onreadystatechange = function(){
if (this.readyState === 4){
callBackFun(JSON.parse(this.responseText));
}
};
http.open("GET", "http://127.0.0.1:8002/data/country/", true);
http.send();
}
function getStateList(countryCode, callBackFun){
var http = new XMLHttpRequest();
http.onreadystatechange = function(){
if (this.readyState === 4){
callBackFun(JSON.parse(this.responseText));
}
};
http.open("GET", "http://127.0.0.1:8002/data/state?count_id="+countryCode, true);
http.send();
}
function getCityList(stateCode, callBackFun){
var http = new XMLHttpRequest();
http.onreadystatechange = function(){
if (this.readyState === 4){
callBackFun(JSON.parse(this.responseText));
}
};
http.open("GET", "http://127.0.0.1:8002/data/cities/?sta_id="+stateCode, true);
http.send();
}
</script>
</body>
</html>
it is showing two warning
1.SyntaxError: missing ; before statement
2.The character encoding of the HTML document was not declared. The document will render with garbled text in some browser configurations if the document contains characters from outside the US-ASCII range. The character encoding of the page must be declared in the document or in the transfer protocol.
Well, you're probably missing a semicolon.
And adding
<meta charset="UTF-8">
should solve the bottom error.

JSON response returning null array

Please help i have been trying from 1 hours and not able to get whats wrong
<!DOCTYPE html>
<html>
<body>
<div id="id01">Result<br/></div>
<script>
var xmlhttp = new XMLHttpRequest();
var url = "http://it-ebooks-api.info/v1/book/2279690981";
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var myArr = JSON.parse(xmlhttp.responseText);
myFunction(myArr);
}
}
xmlhttp.open("GET", url, true);
xmlhttp.send();
function myFunction(arr) {
var out = "";
var i;
for(i = 0; i < arr.length; i++) {
out = arr[i].ID + arr[i].Title + arr[i].Description;
}
document.getElementById("id01").innerHTML = out;
}
</script>
</body>
</html>
I am trying to fetch details from http://it-ebooks-api.info/v1/book/2279690981 but it show only empty array being returned. What changes are required ?
Modification
I added [ ] on JSON object and it worked .. Please can someone explain me.
Thank in advance :)
The response does not contain an array, so the for loop is not needed and this should get you the result you are looking for:
<!DOCTYPE html>
<html>
<body>
<div id="id01">Result<br/></div>
<script>
var xmlhttp = new XMLHttpRequest();
var url = "http://it-ebooks-api.info/v1/book/2279690981";
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var myresponse = JSON.parse(xmlhttp.responseText);
myFunction(myresponse);
}
}
xmlhttp.open("GET", url, true);
xmlhttp.send();
function myFunction(response) {
var out = "";
var i;
out = "<p>" + response.ID + response.Title + response.Description + "<p>";
document.getElementById("id01").innerHTML = out;
}
</script>
</body>
If you use the full listing available from http://it-ebooks-api.info/v1/search/php, then you need the for loop to go through the array like this:
<!DOCTYPE html>
<html>
<body>
<div id="id01">Result<br/></div>
<script>
var xmlhttp = new XMLHttpRequest();
var url = "http://it-ebooks-api.info/v1/search/php";
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var myresponse = JSON.parse(xmlhttp.responseText);
myFunction(myresponse.Books);
}
}
function myFunction(Books) {
var out = "";
for (var i = 0; i < Books.length; i++) {
out += "<p>ID: " + Books[i].ID + "</p>" + "<p>Title: " + Books[i].Title + "</p>" + "<p>Description: " + Books[i].Description + "</p>"
}
document.getElementById("id01").innerHTML = out;
}
xmlhttp.open("GET", url, true);
xmlhttp.send();
</script>
</body>
</html>
And to make it slightly more elegant, you could have a function that adds the book and if you get only one book you can call it directly from the onreadystatechange, and if you have the full listing, then you can loop it through, but still use the same function. So something like this:
<!DOCTYPE html>
<html>
<body>
<div id="id01">Result<br/></div>
<script>
var xmlhttp = new XMLHttpRequest();
var url = "http://it-ebooks-api.info/v1/search/php";
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var response = JSON.parse(xmlhttpo.responseText);
if (response.Books) { // If the response object has Books array, we pass it to the parseBooks functoin to add them all one by one.
parseBooks(response.Books)
} else {
addBook(response); // If there is no Books array, we assume that there is only one book and add it to the list with addBook function.
}
}
}
function addBook (Book) {
var text = document.getElementById("id01").innerHTML;
var body = "<p>ID: " + Book.ID + "</p><p>Title: " + Book.Title + "</p><p>Description: " + Book.Description + "</p>";
document.getElementById("id01").innerHTML = text + body; // Append the innerHTML with the new Book.
}
function parseBooks(Books) {
for (var i = 0; i < Books.length; i++) {
addBook(Books[i]) // Add all books in the array one by one
}
}
xmlhttp.open("GET", url, true);
xmlhttp.send();
</script>
</body>
</html>
You JSON feed is just a simple object and not an Array of objects. Note the opening curly braces in the returned feed: {}
You should then change your myFunction function so it goes through an object and not an array just by removing the for loop:
function myFunction(obj) {
var out = "",
id01 = document.getElementById("id01");
out = obj.ID + obj.Title + obj.Description;
id01.innerHTML = id01.innerHTML + out;
}
Edit:
You can use the same function then inside a for loop when you have to parse an Array of Objects.
Taking as a feed the JSON returned from http://it-ebooks-api.info/v1/search/php, you can retrieve the Books value and then loop through it:
var xmlhttp = new XMLHttpRequest();
var url = "http://it-ebooks-api.info/v1/book/2279690981";
var url2 = "http://it-ebooks-api.info/v1/search/php";
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var rslt = JSON.parse(xmlhttp.responseText);
console.log(rslt);
var books = rslt.Books;
for (var i = 0; i < books.length; i++)
{
myFunction(books[i]);
}
}
}
xmlhttp.open("GET", url2, true);
xmlhttp.send();

Categories

Resources