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>
Related
So I have a search page that I'm working on that has a given JSON object as a return. When I click the search button, it's supposed to load up the results page (without a refresh), with the JSON parsed and placed neatly in div's using JS (I can't use jQuery) (this code is in ajax_info.html). Everything independently works. However, when I try to use AJAX with JavaScript, it doesn't load. Again, everything works when loaded independently. But right now, no scripts are working inside the script tag of ajax_info.html. Is there a better method that I could use to update the page with the results page without reloading? This is my code:
function loadDoc() {
var setInnerHTML = function(elm, html) {
elm.innerHTML = html;
Array.from(elm.querySelectorAll("script")).forEach( oldScript => {
const newScript = document.createElement("script");
Array.from(oldScript.attributes)
.forEach( attr => newScript.setAttributes(attr.name, attr.value) );
newScript.appendChild(document.createTextNode(oldScript.innerHTML));
oldScript.parentNode.replaceChild(newScript, oldScript);
});
}
console.log('hello');
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200 && xhttp.readyState == XMLHttpRequest.DONE) {
setInnerHTML(document.getElementById("demo"),this.responseText);
console.log(this.responseText);
}
};
xhttp.open("POST", "ajax_info.html", true);
xhttp.send();
}
and this is the relevant code for ajax_info.html:
<script>
alert("hello");
console.log('adfasdf');
const searchResults = {
//Json stuff
}
// console.log(searchResults);
//const obj = JSON.parse(searchResults);
//document.getElementById("demo2").innerHTML = searchResults.response.docs[0].es_description;
let text="";
for(let i=0; i<searchResults.response.docs.length; i++) {
text+="<div class='p-3 border rounded-3'>";
text+="<a href=''>"+ "<strong class='text-primary largeText'>" + searchResults.response.docs[i].es_title + "</strong></a>";
text+="<div class='largeText'>" + searchResults.response.docs[i].es_description + "</div>";
text+="<div>" + searchResults.response.docs[i].author + "</div>";
text+="<div>" + searchResults.response.docs[i].site + "</div>";
text+="<div>" + searchResults.response.docs[i].es_date + "<a class='text-success'> " + searchResults.response.docs[i].site + "</a></div>";
//text+="<a href='url'>"+ searchResults.response.docs[i].es_title + "</a>";
text+="</div>";
//text+=searchResults.response.docs[i].author + "<br>";
//text+=searchResults.response.docs[i].site + "<br>";
//text+=searchResults.response.docs[i].es_date + "<br>";
//text+="<p></p>";
document.getElementById("demo2").innerHTML = text;
console.log(i);
}
//alert(searchResults.response.docs.length);
</script>
demo2 is the id of the div inside of ajax_info and demo is the id of the body of index.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 = '';
I am trying to insert pictures to id "pokedex-view" by using Ajax GET. I think "spriteurl" is showing the correct path. But does not work correctly, and it cannot find the pciture for the local folder. Is there something wrong in this code. Thanks.
function populatePokedex() {
var xhr = new XMLHttpRequest();
xhr.open("GET", "https://webster.cs.washington.edu/pokedex/pokedex.php?pokedex=all");
xhr.onload = function(){
if (this.status == 200) {
var picArr = this.responseText.split("\n");
for(var i=0; i < picArr.length; i++){
var eachName = picArr[i].split(":")
var spriteurl = "/Pokedex/sprites/" + eachName[1];
document.getElementById("pokedex-view").innerHTML += spriteurl
document.getElementById("pokedex-view").innerHTML += "<img src = spriteurl>";
}
} else {
document.getElementById("pokedex-view").innerHTML = "ERROR: Status: " + this.status + ", " + this.statusText;
}
}
xhr.onerror = function(){
document.getElementById("pokedex-view").innerHTML = "ERROR";
}
xhr.send();
}
Try to concatenate or to interpolate the way you assign the spriteurl as the src attribute:
document.getElementById("pokedex-view").innerHTML += '<img src="' + spriteurl + '">'
Or:
document.getElementById("pokedex-view").innerHTML += `<img src="${spriteurl}">`
I have this code from w3school works like a charm:
<!DOCTYPE html>
<html>
<body>
<h1>Customers</h1>
<div id="id01"></div>
<script>
var xmlhttp = new XMLHttpRequest();
var url = "http://www.w3schools.com/website/customers_mysql.php";
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
myFunction(xmlhttp.responseText);
}
}
xmlhttp.open("GET", url, true);
xmlhttp.send();
function myFunction(response) {
var arr = JSON.parse(response);
var i;
var out = "<table>";
for(i = 0; i < arr.length; i++) {
out += "<tr><td>" +
arr[i].Name +
"</td><td>" +
arr[i].City +
"</td><td>" +
arr[i].Country +
"</td></tr>";
}
out += "</table>";
document.getElementById("id01").innerHTML = out;
}
</script>
</body>
</html>
but when I repeat the script like this it doesn't work:
<!DOCTYPE html>
<html>
<body>
<h1>Customers</h1>
<div id="id01"></div>
<script>
var xmlhttp = new XMLHttpRequest();
var url = "http://www.w3schools.com/website/customers_mysql.php";
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
myFunction(xmlhttp.responseText);
}
}
xmlhttp.open("GET", url, true);
xmlhttp.send();
function myFunction(response) {
var arr = JSON.parse(response);
var i;
var out = "<table>";
for(i = 0; i < arr.length; i++) {
out += "<tr><td>" +
arr[i].Name +
"</td><td>" +
arr[i].City +
"</td><td>" +
arr[i].Country +
"</td></tr>";
}
out += "</table>";
document.getElementById("id01").innerHTML = out;
}
</script>
<h1>Buyers</h1>
<div id="id02"></div>
<script>
var xmlhttp = new XMLHttpRequest();
var url = "http://www.w3schools.com/website/customers_mysql.php";
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
myFunction(xmlhttp.responseText);
}
}
xmlhttp.open("GET", url, true);
xmlhttp.send();
function myFunction(response) {
var arr = JSON.parse(response);
var i;
var out = "<table>";
for(i = 0; i < arr.length; i++) {
out += "<tr><td>" +
arr[i].Name +
"</td><td>" +
arr[i].City +
"</td><td>" +
arr[i].Country +
"</td></tr>";
}
out += "</table>";
document.getElementById("id02").innerHTML = out;
}
</script>
</body>
</html>
What variable name should I change? I did the script once it worked but twice it didn't work.
I tried changing variable but it didn't work
I changed all the variable names.
Your two scripts exist in the same JS environment. They both create global variables with the same name and interfere with each other.
Wrap each script in an IIFE to create a new scope for each one to operate in.
<script>
(function () {
// Your code here
})();
</script>
It doesn't work because you're executing AJAX call across domains. You can't do an ajax call like that unless you are calling a page on the same domain. There are workarounds, but this is the problem in your case.
Instead create a local file to test your AJAX with.
This is why it works on the w3 Schools site, but not on your own code.
Re-edit of the InnerHtml to show how many Div's will be included in the finished code. Also a re-edit of the start function which now does not work and I'm not sure at what point I broke it.
var fname = name;
function load()
{
var x = new XMLHttpRequest();
x.open ("GET", "file1.xml",true);
x.onreadystatechange = handleServerInput;
x.send();
xml =x.responseXML;
fname = xml.getElementsByTagName("name")[0];
name = fname.childNodes[0].data;
function handleServerInput()
{
if (x.readyState == 4 && x.status == 200)
{
function DisplayDiv()
{
var html = "";
html+= " <div id = \"displayOuter\">";
html+= " <div id = \"displayInner\">";
html+= " <p id = \"fname\">";
html+= " </p>";
html+= " </div>";
html+= " <div id = \"displayInner2\">";
html+= " </div>";
html+= " <div id = \"displayInner3\">";
html+= " </div>";
html+= " </div>";
return html;
}
function start()
{
document.body.innerHTML+=DisplayDiv();
var displayOuterDiv = document.getElementById("displayOuter");
displayOuterDiv.style.display= "block";
var innerdiv = document.getElementById('displayInner');
innerdiv.innerHTML = fname;
}
// alert ( this.responseText );
}
}
}
window.onload = load;
So I put the DisplayDiv function inside my handleServerInput function and that does imput the data to the HTML Div but only when it is set to false which I don't want. Can someone explain to me why this is? Here is an update of the code.
var fname = name;
function load()
{
var x = new XMLHttpRequest();
x.open ("GET", "file1.xml",false);
x.onreadystatechange = handleServerInput;
x.send();
function handleServerInput()
{
if (x.readyState == 4 && x.status == 200)
{
document.body.innerHTML+=DisplayDiv();
div = document.getElementById('displayInner');
div.innerHTML = fname;
}
function DisplayDiv()
{
var html = "";
html+= " <div id = \"displayInner\">";
html+= " <p id = \"fname\">";
html+= " </p>";
html+= " </div>";
return html;
}
}
xml =x.responseXML;
fname = xml.getElementsByTagName("name")[0];
name = fname.childNodes[0].data;
}
Try assigning fname before you use it. I assume you only want to use x.responseXML on a 200 response, so you should move
xml =x.responseXML;
fname = xml.getElementsByTagName("name")[0];
name = fname.childNodes[0].data;
into your if statement, somewhere before
div.innerHTML = fname;
happens