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
Related
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 = '';
This is a part of my code:
function addText(id, type){
alert("ID="+id);
alert("TYPE="+type);
var title = getData("title", id);
var text = getData("text", id);
var imageUrl = getData("imageUrl", id);
document.getElementById("contentArea").innerHTML += '<div id="' + id + '"> </div>';
if(type == 1){
allText = html1.responseText;
titleReplace = "K" + id + "title";
textReplace = "K" + id + "text";
imageReplace = "K" + id + "image";
allText.replace("K1title", titleReplace);
allText.replace("K1text", textReplace);
allText.replace("K1image", imageReplace);
}
document.getElementById(id).innerHTML = allText;
document.getElementById(titleReplace).innerHTML = title;
document.getElementById(textReplace).innerHTML = text;
document.getElementById(imageReplace).src = imageUrl;
}
function getData(Parameter, id){
var result = undefined;
var URL = phpGetURL + "?par=" + Parameter + "&id=" + id;
var xmlhttp = new XMLHttpRequest();
xmlhttp.open('GET', URL ,false);
xmlhttp.send();
result = xmlhttp.responseText;
xmlhttp.abort();
//lert(result);
return result;
}
And this is a part from the index.php where is call the function 4 times:
<script type="text/javascript" src="js/dataManager.js"></script>
<script type="text/javascript"> addText(1, 1); addText(2, 1); addText(3, 1); addText(4, 1); </script>
The first one displays, the second one displays but not with the replaced text. The fourth and the fifth doesn't display at all.
It's gets the data from a php script that gets it from a MYSQL database.
I don't get it to work.
thx
I had the same issue while working on an extension for chrome.
You should may try to initialize the "XMLHttpRequest()"-instance at the very beginning of your code, so that is only created once.
I'm posting this for others, because i've read that you had to solve this problem fast, years ago... So it is not urgent anymore i guess...
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.
Hi I have an issue with onclick events being writen using innerHTML I have tried doing it two ways and both have not work
the function it needs to call is
function loadnewsstory()
{
alert("123456");
}
at the moment it should show the alert box with 123456 but it is not firing.
the function loading it is the following
function newsstories()
{
document.getElementById("activecontent").innerHTML = "<h1 class='newsheader'>Latest News</h1>";
xmlhttp=new XMLHttpRequest();
xmlhttp.open("POST","test.com?uri=loadnews",false);
xmlhttp.send();
var newsreponse = JSON.parse(xmlhttp.responseText);
var countstories = 0;
for (var i = 0, len = newsreponse.length; i < len; ++i) {
var news = newsreponse[i];
if(i % 2 == 0){
cssclass = "even";
}
else
{
cssclass = "odd";
}
// alert(news.featured_image);
document.getElementById("activecontent").innerHTML += "<div class='news " + cssclass + "'><div class='newstitle'><div class='newstitlecolor'><a href='#' onclick='loadnewsstory();'>" + news.post_title + "</a></div></div><div class='base' style='background: url('" + news.featured_image + "');'><img src='" + news.featured_image + "' style='width:100%; height:100%;' id='news_"+ countstories +"'/></div></div>";
document.getElementById("news_"+countstories).onclick = function(){ loadnewsstory();}
countstories++;
}
}
as you can see I have also ran document.getElementById("news_"+countstories).onclick = function(){ loadnewsstory();} because i read that onclick events could not be written by javascript innerHTML which I know I have been able to do before. If someone else knows of a fix to this issue that would be great. this is for a cordova iphone app
Thanks
EDIT
I have found that this
document.getElementById("activecontent").innerHTML += "<div class='news " + cssclass + "'><a href='javascript:openextlink();'><img src='" + news.featured_image + "' style='width:100%; height:100%;'/></a></div>";
works but it seems to only work on the last news story, am I missing something.
I suspect it's because your request is attempting to read/parse the response from the server too soon here:
xmlhttp.send();
var newsreponse = JSON.parse(xmlhttp.responseText);
Because this is an asyncronus (Ajax) request you need to give the script time to wait for the server to respond. You do this by creating an event handler that waits for the response.
xmlhttp.onreadystatechange=function() { // checks if the state of the request has changed
if (xmlhttp.readyState==4 && xmlhttp.status==200) { // checks that the response is ready
// code to handle the response here
var newsreponse = JSON.parse(xmlhttp.responseText);
// etc.
}
}
Also note that you should create this handler before calling xmlhttp.send();
First of all, appending to innerHTML is usually very bad. If you run the code like something.innerHTML += 'lots of html' in a loop, browser has to update the DOM tree and re-render the page on every iteration. This may greatly slow down the things. Use the buffer string instead.
I also suspect that this might have caused issues with event attachment. Try attaching events after all the divs have been attached to the tree. The code in this case would be something like this:
function newsstories()
{
// Use a variable that would store the newly generated HTML:
var html = "<h1 class='newsheader'>Latest News</h1>";
xmlhttp=new XMLHttpRequest();
xmlhttp.open("POST","test.com?uri=loadnews",false);
xmlhttp.send();
var newsreponse = JSON.parse(xmlhttp.responseText);
for (var i = 0, len = newsreponse.length; i < len; ++i) {
var news = newsreponse[i];
// Notice the 'var' keyword!
if(i % 2 == 0){
var cssclass = "even";
} else {
var cssclass = "odd";
}
// Append to our buffer variable
html += "<div class='news " + cssclass + "'><div class='newstitle'><div class='newstitlecolor'><a href='#' onclick='loadnewsstory();'>" + news.post_title + "</a></div></div><div class='base' style='background: url('" + news.featured_image + "');'><img src='" + news.featured_image + "' style='width:100%; height:100%;' id='news_"+ i +"'/></div></div>";
}
// Now that new html is ready, insert it into the tree
// and attach events
document.getElementById("activecontent").innerHTML = html;
for (var i = 0, len = newsreponse.length; i < len; ++i) {
var img = document.getElementById('news_'+i);
if(img) img.addEventListener('click', loadnewsstory);
}
}
it was due to z-index in my css that this was not working, I have fixed this by removing z-index:-1 and now all works fine, it is interesting that it was due to a css error that this bug come to alight
My end goal is to have a home page that pulls RSS feeds and displays them on my home page for my personal website. This is all done from the client side and I'm not looking to build a server site script to do this (I will though only if no other way is possible).
Below is the page load code. (I don't think this is a problem area but it nice to see the starting point)
$(document).ready(function () { // Here
loadpageF(); //<- problems is in this function
GetBackGround(document.body); //this just messes with the css of the site
});
function loadpageF() {
addTableFeed("http://www.npr.org/rss/rss.php?id=1001");
addTableFeed("http://news.yahoo.com/rss/odd");
addTableFeed("http://www.nfl.com/rss/rsslanding?searchString=team&abbr=DAL");
addTableFeed("http://www.npr.org/rss/rss.php?id=1007");
$(".MainArea").css("width",$("iframe").length * (270));
}
//This function sets up where the RSS data will be place after formatting
function addTableFeed(feedlink) {
var numOfCell = maintb.getElementsByTagName("iframe").length;
maintb.innerHTML += "<iframe id='f" + numOfCell + "' class='iframeFeed'></iframe>";
getRSSFeed(feedlink, "f" + numOfCell);
}
This code basically calls a function for each rss to add and iframe and the passes the iframe id and the URL to another function (shown below and I am 99% sure is the problem) which getting the data.
function getRSSFeed(feedlink, iframeid) {
/*var xmlhttp; old way I did it below realizing it did not work in firefox
if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
}
else {// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var hold = xmlhttp.responseText
loadData(hold, iframeid);
}
}
xmlhttp.open("get", feedlink, false);
xmlhttp.send();*/ //end of the old way
//new way to try to use JSON of course failing at my in goal
$.ajax({
type: "GET",
url: feedlink,
async: true,
dataType: "text",
success: function(data){
loadData(data, iframeid);
},
error: function(data, statusCode) {
alert("ERROR: "+data.error)
}
});}
The function loadData works fine when called, however it is not called for the Yahoo.com and NFL.com feed. Instead I get an alert as shown below.
//Note I has to transcribe from dialog box there may be errors
ERROR: function () {
if( list ) {
// First, we save the current length
var start = list length;
(function add( args ) {
jQuery.each( args, function( _, arg ) {
¡f( jQuery.isFunction( arg ) && (!options unique || self.has( arg)
list .push( arg);
else if( arg && arg.length ) {
// Inspect recursively
add( arg);
}
});
})( arguments);
//Do we need to add the callbacks to the
// current firing batch?
if (firing ) (
firingLength = list length;
//wiIh memory, if we’re not firing then
// we should call right away
J else if ( memory ) (
firingstart = start;
fire( memory);
Just in case it is needed, below is the load data code.
function loadData(xml, ifid) {
var htmlStr;
var artCount = 0;
var $xml = $($.parseXML(xml));
$("#" + ifid)[0].contentDocument.open();
$("#" + ifid)[0].contentDocument.close();
$("#" + ifid)[0].contentDocument.write("<head><link rel='Stylesheet' type='text/css' href='" + document.getElementById("StyleSheet").href + "' /></head>");
//RSS 2.0 handler
$xml.find("channel item").each(function () {
var $article = $(this);
var title = $article.find("title").text();
var description = $article.find("description").text();
var link = $article.find("link").text();
var pubDate = $article.find("pubDate").text();
htmlStr = "<div id='" + artCount + "Span" + ifid + "' class='ArticalHead'><h3>" + title + "</h3></div>\n";
htmlStr += "<div class='ArticalBody' id='" + artCount + "Div" + ifid + "'>\n";
htmlStr += "\t<p>" + description + "</p><a href='" + link + "' target='_blank' > Click Here For more </a>\n";
htmlStr += "\t<h6>" + pubDate + "</h6><br />\n";
htmlStr += "</div>\n"
$("#" + ifid)[0].contentDocument.write(htmlStr);
$("#" + ifid).contents().find("#" +artCount + "Span" + ifid).click(function () {
$("#" + ifid).contents().find("#" + $(this).attr("id").replace("Span", "Div")).toggle();
});
artCount++;
});
//Atom 1.0 handler
$xml.find("feed entry").each(function () {
var $article = $(this);
var title = $article.find("title").text();
var description = $article.find("summary").text();
var link = $article.find("link").attr("href");
var pubDate = $article.find("published").text();
htmlStr = "<div id='" + artCount + "Span" + ifid + "' class='ArticalHead'><h3>" + title + "</h3></div>\n";
htmlStr += "<div class='ArticalBody' id='" + artCount + "Div" + ifid + "'>\n";
htmlStr += "\t<p>" + description + "</p><a href='" + link + "' target='_blank' > Click Here For more </a>\n";
htmlStr += "\t<h6>" + pubDate + "</h6><br />\n";
htmlStr += "</div>\n"
$("#" + ifid)[0].contentDocument.write(htmlStr);
$("#" + ifid).contents().find("#" + artCount + "Span" + ifid).click(function () {
$("#" + ifid).contents().find("#" + $(this).attr("id").replace("Span", "Div")).toggle();
});
artCount++;
});
//$("#" + ifid).contents().find(".ArticalBody").hide();
}
Please forgive me for any typos or spelling errors. I can also post the whole web page if needed.