Stuck trying to parse XML using AJAX and Javascript with XMLHttpRequest - javascript

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

Related

How do I get scripts to work after a xhttps request

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

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 = '';

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>

Trying to delete items from a multidimensional array (html,javascript)

I have table that is created that shows each item added to the array. In the last row of each column is an action field that lets you either edit or delete from the row. I am not sure how I am supposed to accomplish this. What I have so far does not work properly.
function del(item) {
participantList.splice(item,1);
displayLIst();
}
function addInfo() {
var fname = document.getElementById("fname").value;
var lname = document.getElementById("lname").value;
var email = document.getElementById("email").value;
if(fname !='' && lname !="" && email !='') {
participantList[count] = new Object();
participantList[count].Fname = fname;
participantList[count].Lname = lname;
participantList[count].Email = email;
participantList[count].Action = "<button onclick='del("+count+")'>Delete</button>" + "<button onclick='edit("+count+")'>Edit</button>";
count++;
document.getElementById("fname").value ="";
document.getElementById("lname").value = "";
document.getElementById("email").value = "";
}
displayList();
}
I want to delete every object from the specified row in the array.
How are you getting the elements and putting them into the participant list?
Do you have references to the elements? Can you include the HTML as well and all the related code to what you want to do?
Below is how I would get all of the elements, and remove one.
You can remove an element by calling .remove() on it
Here is my example code: http://jsfiddle.net/gabs00/cxt170re/
var listItems = document.querySelectorAll('li');
var item = listItems[1];
item.remove();
querySelectorAll creates a live node list
I grab one of those elements (index 1) and delete it with Element.remove();
Check out the fiddle to see it in action.
Here is a current working version:
var participantList = [];
var edit = function(item) {};
var del = function(item) {
participantList.splice(item,1);
displayList();
};
function addInfo() {
var fname = document.getElementById("fname").value;
var lname = document.getElementById("lname").value;
var email = document.getElementById("email").value;
var count = participantList.length;
if(fname !='' && lname !="" && email !='') {
var item = {};
item.Fname = fname;
item.Lname = lname;
item.Email = email;
item.Action = "<button onclick='del("+count+")'>Delete</button><button onclick='edit("+count+")' disabled>Edit</button>";
participantList.push(item);
document.getElementById("fname").value ="";
document.getElementById("lname").value = "";
document.getElementById("email").value = "";
}
displayList();
};
var displayList = function () {
// clean previous data
console.log(participantList);
document.getElementById("results").innerHTML = "";
var content = "";
for(var i = 0; i<participantList.length; i++) {
content += "<tr>";
content += "<td>" + participantList[i].Fname + "</td>";
content += "<td>" + participantList[i].Lname + "</td>";
content += "<td>" + participantList[i].Email + "</td>";
content += "<td>" + participantList[i].Action + "</td>";
content += "</tr>"
}
document.getElementById("results").innerHTML = "<table>" + content + " </table>";
};
With the following HTML Code:
<input type="text" id="fname" />
<input type="text" id="lname" />
<input type="text" id="email" />
<button onclick="addInfo()">
Add
</button>
<div id="results">
EDIT: Missing JSFiddle link: https://jsfiddle.net/d64314uk/

Unexpected token } can not find the mistake

i tried everything but i don't know where the mistake should be its show me a unespekted token } in a line where i not even have this sign.
<script type="text/javascript">
function postToStatus(action,type,user,ta){
var data = _(ta).value;
if(data == ""){
alert("Type something first weenis");
return false;
}
_("statusBtn").disabled = true;
var ajax = ajaxObj("POST", "php_parsers/qp_system.php");
ajax.onreadystatechange = function() {
if(ajaxReturn(ajax) == true) {
var datArray = ajax.responseText.split("|");
if(datArray[0] == "post_ok"){
var sid = datArray[1];
data = data.replace(/</g,"<").replace(/>/g,">").replace(/\n/g," ><br />").replace(/\r/g,"<br />");
var currentHTML = _("statusarea").innerHTML;
_("statusarea").innerHTML = '<div id="status_'+sid+
'class="status_boxes"><div><b>Posted by you just now:</b><span >id="sdb_'+sid+
'"><a href="#" onclick="return false" >onmousedown="deleteStatus("'+sid+
'\',\'status_'+sid+
'\');" title="DELETE THIS STATUS AND ITS REPLIES">delete status</a> ></span><br />'+data+
'</div></div>"'+currentHTML;
_("statusBtn").disabled = false;
_(ta).value = "";
} else {
alert(ajax.responseText);
}
}
}
ajax.send("action="+action+"&type="+type+"&user="+user+"&data="+data);
}
You need to put a semi-colon after the last } just before the ajax.send() call.
This website is your best friend if you write JavaScript: http://closure-compiler.appspot.com/home
function postToStatus(action, type, user, ta) {
var data = _(ta).value;
if (data == "") {
alert("Type something first weenis");
return false;
}
_("statusBtn").disabled = true;
var ajax = ajaxObj("POST", "php_parsers/qp_system.php");
ajax.onreadystatechange = function() {
if (ajaxReturn(ajax) == true) {
var datArray = ajax.responseText.split("|");
if (datArray[0] == "post_ok") {
var sid = datArray[1];
data = data.replace(/</g, "<").replace(/>/g, ">").replace(/\n/g, " ><br />").replace(/\r/g, "<br />");
var currentHTML = _("statusarea").innerHTML;
_("statusarea").innerHTML = '<div id="status_' + sid + 'class="status_boxes"><div><b>Posted by you just now:</b><span >id="sdb_' + sid + '">delete status ></span><br />' + data + '</div></div>"' + currentHTML;
_("statusBtn").disabled = false;
_(ta).value = "";
} else {
alert(ajax.responseText);
}
}
};
ajax.send("action=" + action + "&type=" + type + "&user=" + user + "&data=" + data);
}
;

Categories