Previous data is lost because of new data - javascript

I am creating some html tag and assigning data as below.
MyCombo = function(args) {
var dataUrl = args.url;
var divID = args.divID;
var div = document.getElementById(divID);
var myTable = '<input type="text" id="myInput" list="myUL" onclick = "MyList()" onkeyup="MyList()" style="width:100% " >' +
'<ul id="myUL" hidden=false>' + '<li>' + '<a href="#" ></a>' + '</li>' + '</ul>';
div.innerHTML = myTable;
function getData(callback) {
var httpRequest = new XMLHttpRequest();
httpRequest.open('GET', dataUrl, true);
httpRequest.onreadystatechange = function() {
if (httpRequest.readyState === XMLHttpRequest.DONE && httpRequest.status === 200) {
callback(httpRequest.responseText);
}
};
httpRequest.send();
}
getData(function(data) {
var jsonc = JSON.parse(data);
var new_opt = "";
for (i = 0; i < jsonc.length; i++) {
new_opt += '<li>' + jsonc[i]['VALUE'] + '</li>';
}
document.getElementById('myUL').innerHTML = new_opt;
});
}
Now when I pass my second div, previous data is getting lost. And for first div I am getting second data.
This how I am calling the class :
For the first instance
var myCombo = new liveSearch({
"url": "data1.json",
"divID": "ID1",
});
For the second instance
var myCombo2 = new liveSearch({
"url": "data2.json",
"divID": "ID2",
});
Any idea how to overcome this?

In getData you call
document.getElementById('myUL').innerHTML = new_opt;
which writes to the element called myUL everytime it is called.

Append instead of replacing
document.getElementById('myUL').appendChild(new_opt);
or you can append to the old
old_html = document.getElementById('myUL').innerHTML;
document.getElementById('myUL').innerHTML = old_html+new_opt;

Related

'object HTMLCollection' instead of Image URL from RSS

I'm trying to pull thumbnail URLs from a wordpress feed and keep getting [object HTMLCollection] instead of an image URL string for the thumbnail. The feed i'm pulling from is: https://harpercollegece.com/feed/. I know that the tag is named media:thumbnail and the value is stored in 'URL'. I can't find the correct way to reference this image inside of the forEach loop when running through each post. I've tried searching other posts as well as on google for several hours.
var proxy = 'https://api.allorigins.win/raw?url=';
var feeds = [
'https://harpercollegece.com/feed/',
];
var limit = 10;
var forEach = function (array, callback, scope) {
for (var i = 0; i < array.length; i++) {
callback.call(scope, i, array[i]);
}
};
function strip_tags(string) {
if ((string === null) || (string === '')) {
return '';
} else {
string = string.toString();
}
string = string.replace('<![CDATA[', '');
string = string.replace(' […]]]>', '');
string = string.replace(/<[^>]*>/g, '');
string = string.replace(/<[^>]*>/g, '');
string = string.replace(']]>', '');
return string;
}
function get_rss(url) {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if (xhr.readyState !== 4) {
return;
}
if (xhr.status >= 200 && xhr.status < 300) {
var response = xhr.responseText;
var parser = new window.DOMParser();
var data = parser.parseFromString(response, "text/xml");
var items = Array.from(data.querySelectorAll("item"));
var output = '';
forEach(items, function(index, item) {
if (index <= limit) {
var ilink = item.querySelector("link").innerHTML;
var title = item.querySelector("title").innerHTML;
var descr = item.querySelector("description").innerHTML;
var thumb = item.getElementsByTagName("media:thumbnail");
//console.log(item);
output +=
'<div class="ce-blog-slider-well">' +
'<div class = "ce-blog-thumb">' +
'<img class="blog-post-img" src="' + thumb + '" alt="Veterans Center Sign">' +
'</div>' +
'<div class = "ce-blog-header">' +
'' + strip_tags(title) + '' +
'</div>' +
'<div class ="ce-blog-descr">' + strip_tags(descr) + '</div>' +
'</div>';
}
});
var d1 = document.getElementById('wp-blog-posts');
d1.insertAdjacentHTML("beforeend", output);
}
};
xhr.open('GET', url);
xhr.send();
}
forEach(feeds, function(index, feed) {
get_rss(proxy + encodeURIComponent(feed));
});
<div class="ce-blog-slider" id="wp-blog-posts"></div>
getElementsByTagName returns an HTMLCollection. To get the URL, you'll have to grab the first element in that collection with [0]. The URL is stored in an attribute called url, a la
<media:thumbnail url="https://harpercollegece.files.wordpress.com/2021/01/writing-red-typewriter-typing.jpg" />
From your HTMLElement, get the url attribute like so:
var thumb = item.getElementsByTagName("media:thumbnail")[0].getAttribute("url");
var proxy = 'https://api.allorigins.win/raw?url=';
var feeds = [
'https://harpercollegece.com/feed/',
];
var limit = 10;
var forEach = function (array, callback, scope) {
for (var i = 0; i < array.length; i++) {
callback.call(scope, i, array[i]);
}
};
function strip_tags(string) {
if ((string === null) || (string === '')) {
return '';
} else {
string = string.toString();
}
string = string.replace('<![CDATA[', '');
string = string.replace(' […]]]>', '');
string = string.replace(/<[^>]*>/g, '');
string = string.replace(/<[^>]*>/g, '');
string = string.replace(']]>', '');
return string;
}
function get_rss(url) {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if (xhr.readyState !== 4) {
return;
}
if (xhr.status >= 200 && xhr.status < 300) {
var response = xhr.responseText;
var parser = new window.DOMParser();
var data = parser.parseFromString(response, "text/xml");
var items = Array.from(data.querySelectorAll("item"));
var output = '';
forEach(items, function(index, item) {
if (index <= limit) {
var ilink = item.querySelector("link").innerHTML;
var title = item.querySelector("title").innerHTML;
var descr = item.querySelector("description").innerHTML;
var thumb = item.getElementsByTagName("media:thumbnail")[0].getAttribute("url");
//console.log(item);
output +=
'<div class="ce-blog-slider-well">' +
'<div class = "ce-blog-thumb">' +
'<img class="blog-post-img" src="' + thumb + '" alt="Veterans Center Sign">' +
'</div>' +
'<div class = "ce-blog-header">' +
'' + strip_tags(title) + '' +
'</div>' +
'<div class ="ce-blog-descr">' + strip_tags(descr) + '</div>' +
'</div>';
}
});
var d1 = document.getElementById('wp-blog-posts');
d1.insertAdjacentHTML("beforeend", output);
}
};
xhr.open('GET', url);
xhr.send();
}
forEach(feeds, function(index, feed) {
get_rss(proxy + encodeURIComponent(feed));
});
<div class="ce-blog-slider" id="wp-blog-posts"></div>

How to parse XML using AJAX in html?

I'm trying to parse XML by using AJAX. However there were a few errors which i got saying my "html is not defined"
Basically what I want to do is to parse a specific amount of data from my XML codes and display it using HTML webpage .
The below is the list of bugs in console when I tried to run the script
at displayCountrylist (test2.html:136)
at handleStatusSuccess (test2.html:61)
at readyStateChangeHandler (test2.html:32)
at XMLHttpRequest.xhttp.onreadystatechange (test2.html:16)
I tried to do everything to debug but still failed. Any one help please?
<html>
<script>
function makeAjaxQueryCountrylist()
{
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function()
{
readyStateChangeHandler(xhttp);
};
xhttp.open("GET", "A3_CtryData_dtd_Sample.xml", true);
xhttp.send();
}
function readyStateChangeHandler(xhttp)
{
if (xhttp.readyState == 4)
{
if(xhttp.status == 200)
{
handleStatusSuccess(xhttp);
}else
{
handleStatusFailure(xhttp);
}
}
}
function handleStatusFailure(xhttp){
var displayDiv = document.getElementById("display");
displayDiv.innerHTML = "XMLHttpRequest failed: status " + xhttp.status;
}
function handleStatusSuccess(xhttp)
{
var xml = xhttp.responseXML;
var countrylistObj = parseXMLCountrylist(xml);
displayCountrylist(countrylistObj);
}
function parseXMLCountrylist(xml)
{
var countrylistObj = {};
var countrylistElement = xml.getElementsByTagName("CountryList")[0];
var recordElementList = countrylistElement.getElementsByTagName("CountryRecord");
countrylistObj.recordList = parseRecordElementList(recordElementList);
return countrylistObj;
}
function parseRecordElementList(recordElementList)
{
var recordList = [];
for(var i=0; i < recordElementList.length; i++)
{
var recordElement = recordElementList[i];
var recordObj = parseRecordElement(recordElement);
recordList.push(recordObj);
}
return recordList;
}
function parseRecordElement(recordElement)
{
var recordObj = {};
var countrycodeElement = recordElement.getElementsByTagName("country-code")[0];
recordObj.countrycode = Number(countrycodeElement.textContent);
var nameElement = recordElement.getElementsByTagName("name")[0];
recordObj.name = nameElement.textContent;
var alpha2Element = recordElement.getElementsByTagName("alpha-2")[0];
recordObj.alpha2 = alpha2Element.textContent;
var alpha3Element = recordElement.getElementsByTagName("alpha-3")[0];
recordObj.alpha3 = alpha3Element.textContent;
var capitalcityElement = recordElement.getElementsByTagName("capital-city")[0];
recordObj.capitalcity = capitalcityElement.textContent;
return recordObj;
}
function displayCountrylist(countrylistObj)
{
for(var i=0; i < countrylistObj.recordList.length; i++)
{
var recordObj = countrylistObj.recordList[i];
html += "country-code: " + recordObj.countrycode;
html += "<br />";
html += "name: " + recordObj.name;
html += "<br />";
html += "alpha-2: " + recordObj.alpha2;
html += "<br />";
html += "alpha-3: " + recordObj.alpha3;
html += "<br />";
html += "capital-city: " + recordObj.capitalcity;
html += "<br />";
}
var displayDiv = document.getElementById("display1");
displayDiv.innerHTML = html;
}
</script>
<body>
<button onClick="makeAjaxQueryCountrylist()"> Region Info I (Format: region-fmt-1.xsl)</button>
<br /><br />
<div id="display1">
</div>
</body>
</html>
There isn't any problem with my XML codes so it has to be some error from here.
You got that error html is not defined because you are using html variable without declaring it. So, before the line
html += "country-code: " + recordObj.countrycode;
you have to write
let html = '';

XHR Response with For-Loop not working

I have this issue with my XMLHttpRequest that I'm making. The idea is that the loop is mean to loop through a JSON array of users and also load their profile image. Loading the users works absolutely fine but when I loop to get the profile image, it shows it with the last user.
I can see where the issue lies but I don't know how to solve it. When I debug this, it does not run the xhr[i].onload part, which is important because I'm trying to append the image found to the id of the user as the loop runs. The first part of the loop will create the 'img id ="username"' for the username and then i want the XHR request to run and get the image and then append it to the 'img id' tag.
function parseJSON() {
console.log(jsonArrayOfUsers);
var htmlStart = '<ul class ="softwares">';
var htmlEnd = '</ul>'
var html = ''
var len = jsonArrayOfUsers.length;
for (var i = 0; i < len; i++) {
var xhr = [];
currentuser = jsonArrayOfUsers[i].username;
currentavatar = jsonArrayOfUsers[i].avatar
console.log(currentuser);
html += '<li class ="softwares">'
+ '<p><img id ="' + jsonArrayOfUsers[i].username + '" width="auto" height="100px"/></p>'
+ '<p>' + jsonArrayOfUsers[i].fullName + '</p>'
+ '<p>' + jsonArrayOfUsers[i].username + '</p>'
+ '<p>' + jsonArrayOfUsers[i].university + '</p>'
+ '<p>' + jsonArrayOfUsers[i].userType + '</p></li>';
(function (i){
if (jsonArrayOfUsers[i].avatar == null){}
else{
xhr[i] = new XMLHttpRequest();
xhr[i].open("GET", "URL TO API" + jsonArrayOfUsers[i].avatar, true);
xhr[i].setRequestHeader("Authorization", localStorage.token);
xhr[i].responseType = 'blob';
xhr[i].onload = function response(e) {
var urlCreator = window.URL || window.webkitURL;
imageUrl = urlCreator.createObjectURL(this.response);
document.querySelector("#" + currentuser).src = imageUrl;
};
xhr[i].send();
}})(i);
}
var htmlFull = htmlStart + html + htmlEnd
$('.people').append(htmlFull);
The way you are appending insecure text into html is bad...
I would have solved it this way using a simple forEach loop instead of a for loop
function parseJSON() {
var list = $('<ul class="softwares">');
var url = window.URL || window.webkitURL;
jsonArrayOfUsers.forEach(function(user) {
var currentuser = user.username;
var currentavatar = user.avatar;
console.log(currentuser);
var img = $('<img>', {
id: user.username,
width: 'auto',
height: '100px'
})[0];
$('<li class ="softwares">').append(
$('<p>').append(img),
$('<p>', {text: user.fullName}),
$('<p>', {text: user.username}),
$('<p>', {text: user.university}),
$('<p>', {text: user.userType})
).appendTo(list)
if (jsonArrayOfUsers[i].avatar == null) {
} else {
var xhr = new XMLHttpRequest();
xhr.open("GET", "URL TO API" + user.avatar);
xhr.setRequestHeader("Authorization", localStorage.token);
xhr.responseType = 'blob';
xhr.onload = function response(e) {
img.onload = function() {
url.revokeObjectURL(this.src);
}
img.src = url.createObjectURL(xhr.response);
};
xhr.send();
}
})
$('.people').append(list);
}

How to dynamically add checkboxes using Javascript for parsed data

I have this HTML file where if the user clicks on "View questions", it should display the parsed data that I receive. Right now I am working with a JSON test file. It displays the data fine, but I need to dynamically add checkboxes using Javascript for when the data is displayed. And when the user clicks on a checkbox, that data can be sent through Ajax to the backend. How can I achieve this? Any help would be appreciated. Thanks.
<button type=button class="lg=button" id="btn">View questions</button>
<p id="response"></p>
<script>
var resp = document.getElementById("response");
var btn = document.getElementById("btn");
btn.addEventListener("click", function() {
var xhr = new XMLHttpRequest();
xhr.open("GET", "https://learnwebcode.github.io/json-example/animals-1.json", true);
xhr.onload = function() {
if (xhr.status >= 200 && xhr.status < 400) {
console.log(xhr.responseText);
var ourData = JSON.parse(xhr.responseText);
//console.log(ourData);
renderHTML(ourData);
}
}
xhr.send();
});
function renderHTML(data) {
var htmlString = "";
for (i = 0; i < data.length; i++) {
htmlString += "<p>" + data[i].name + " is a " + data[i].species + " that likes to eat ";
}
htmlString += '.</p>';
resp.insertAdjacentHTML('beforeend', htmlString);
}
</script>
It displays the data fine, but I need to dynamically add checkboxes using Javascript for when the data is displayed you need to put input type checkbox while rendering it
<input id="checkBox" type="checkbox">
You can add event listener to do any logic based on click event on those checkbox.
var resp = document.getElementById("response");
var btn = document.getElementById("btn");
btn.addEventListener("click", function() {
var xhr = new XMLHttpRequest();
xhr.open("GET", "https://learnwebcode.github.io/json-example/animals-1.json", true);
xhr.onload = function() {
if (xhr.status >= 200 && xhr.status < 400) {
console.log(xhr.responseText);
var ourData = JSON.parse(xhr.responseText);
//console.log(ourData);
renderHTML(ourData);
}
}
xhr.send();
});
function renderHTML(data) {
var htmlString = "";
for (i = 0; i < data.length; i++) {
htmlString += "<p><input type='checkbox'>" + data[i].name + " is a " + data[i].species + " that likes to eat ";
}
htmlString += '.</p>';
resp.insertAdjacentHTML('beforeend', htmlString);
}
<button type=button class="lg=button" id="btn">View questions</button>
<p id="response"></p>

How to get this data using the loop?

How do i show all the data by using the loop to display all the data from json to html ?
ATM , I am able to print one of the data. but if i am using data[i] the code will not display any data.
I think I mess up the the concept of object and array.
please advice me , how to loop thru object , like array?
thanks
var getWeather = document.getElementById('weather');
var requestWeather = new XMLHttpRequest();
//+'-31' +'&lon='+'150'
requestWeather.open('GET','https://fcc-weather-api.glitch.me/api/current?lat=-31&lon=150');
requestWeather.onload = function () {
var weatherData = JSON.parse(requestWeather.responseText);
console.log(weatherData);
getHTML(weatherData);
};
requestWeather.send();
function getHTML(data) {
var weatherString = "";
for(var i in data.weather ){
var x= data.weather[i].main;
weatherString+= "<p class='weather'>" + x + "</p>";
// weatherString+= "<p>" + data.currently.summary + "</p>";
// console.log(data[i].city);
}
getWeather.insertAdjacentHTML("beforeend", weatherString);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="weather"></div>
to get all data check for object and do recursive loop
var getWeather = document.getElementById('weather');
var requestWeather = new XMLHttpRequest();
//+'-31' +'&lon='+'150'
requestWeather.open('GET', 'https://fcc-weather-api.glitch.me/api/current?lat=-31&lon=150');
requestWeather.onload = function() {
var weatherData = JSON.parse(requestWeather.responseText);
//console.log(weatherData);
getHTML(weatherData);
};
requestWeather.send();
function getHTML(data) {
var weatherString = "";
for(var i in data) {
var x = data[i];
if(typeof(x) == "object") {
getHTML(x);
}
else {
weatherString += "<p class='weather'><b>" + i + "</b>: " + x + "</p>";
// weatherString+= "<p>" + data.currently.summary + "</p>";
// console.log(data[i].city);
}
}
getWeather.insertAdjacentHTML("beforeend", weatherString);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="weather"></div>
var getWeather = document.getElementById('weather');
var requestWeather = new XMLHttpRequest();
//+'-31' +'&lon='+'150'
requestWeather.open('GET', 'https://fcc-weather-api.glitch.me/api/current?lat=-31&lon=150');
requestWeather.onload = function() {
var weatherData = JSON.parse(requestWeather.responseText);
getHTML(weatherData);
};
requestWeather.send();
function getHTML(data) {
var weatherString = "";
for (var i in data.weather) {
var x = data.weather[i].main;
weatherString += "<p class='weather'>" + x + "</p>";
$.each(data.main, function(i, f) {
var main = "<div>" + i + ": " + f + "</div>";
$(main).appendTo("#main");
});
}
getWeather.insertAdjacentHTML("beforeend", weatherString);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="weather"></div>
<div id="main"></div>
use foreach loop to iterate over all object
read more from here

Categories