Loading DIV content via ajax as HTML - javascript

I think I have a very simple question, but I couldn't find a solution.
So what I want is to load a DIV content via HTML. The problem is that it is not just a text, but also an image. The ajax call returns the HTML code, but this is displayed in the DIV as HTML and is not executed. Difficult to explain, but obvious from the example...
The AJAX call returns the string:
<img src="/images/weather/1.png" width="80px"><br>3.3 °C
The problem is obvious. Instead of an image and the 3.3°C in the div, I get the actual code, so instead of the image I see img src=....
I know that i need to somehow decode the HTML, but I have no clue how to do this and would very much appreciate any help.
My Javascript code is:
var xmlhttp;
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) {
newtext = xmlhttp.responseText;
}
}
xmlhttp.open("GET", "message_ajax.php", true);
xmlhttp.send();
$('#text').fadeOut(function () {
$(this).text(newtext).fadeIn();
})

Are you looking for something like this ?
https://api.jquery.com/load/
Where you can just load HTML into a DIV using ajax. Seems to be what you're asking...
$( "#result" ).load( "ajax/test.html" );
Where your ajax/test.html file contains
<img src="/images/weather/1.png" width="80px">
Edited... to be more specific. This is using jQuery.

You should use $(this).html(newtext) instead of $(this).text(newtext).
They are quite different. .text() will "escape" your HTML and insert it as simply text. Or as the documentation states:
We need to be aware that this method escapes the string provided as
necessary so that it will render correctly in HTML. To do so, it calls
the DOM method .createTextNode(), does not interpret the string as
HTML.
You should always read the documentation first.
If you are already using jQuery, you could use it's AJAX methods which make your life much easier.

document.getElementById("divId").innerHTML = "<img ..........";
OR
$("#divId").html("<img ..........");

Related

Using javascript and XML to populate a drop-down box

Very new to all this, so please bear with me and use simple answers!
I am trying to dynamically populate a drop down box (theSecondBox), with a list of items which is dependent on the selection made in another drop down box (theCriteria).
I have been able to do an AJAX request and am getting an XML document back.
So far my script looks like this:-
<script type="text/javascript">
var xmlHttp;
function triggerAction(){
xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = handleStateChange;
criteria = document.getElementById("theCriteria").value;
xmlHttp.open("GET","MyURL?criteria=" + criteria, true);
xmlHttp.send(null);
}
function handleStateChange(){
if(xmlHttp.readyState == 4){
if(xmlHttp.status == 200){
parseResults();}
}
}
This returns an XML document to me that looks like this :-
<list>
<string>FirstDropDownItem</string>
<string>SecondDropDownItem</string>
<string>ThirdDropDownItem</string>
</list>
So, I'm trying to populate my second drop down box with these items, using something like ...
function parseResults(){
var results
var selectTag
results = xmlHttp.responseXML;
selectTag = document.getElementById("theSecondBox");
...and this is where I need a few 'simple' pointers.
How do I populate the secondBox with the items returned in the XML document? Everything I've tried so far (and I won't reproduce it to save my embarrassment!) just gives me nulls.
Apologies for the simple question, but as I said, I'm not a programmer by any means, so any pointers to either a solution, or a good tutorial which will help to educate me would be much appreciated.
w3schools is not a good source but this one time pls take a look
at (that "if" for IE5 is absolete now):
http://www.w3schools.com/ajax/tryit.asp?filename=tryajax_first
Frankly document.getElementById("myDiv").innerHTML=xmlhttp.responseText
is what you need.
Just before that you can just replace "list" with "ul" and string with "li".
It would be better to change xml in backend but if you can't give str.replace a try...
var new_text = text.replace(/want/g, "dont want");

Explaining how document.getelementbyid.innerhtml prints text

Following other documentation, I have succesfully printed out a text file separated by line.
<!DOCTYPE html>
<html>
<head>
<script>
function readFile()
{
var xmlhttp;
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)
{
document.getElementById("myDiv").innerHTML=xmlhttp.responseText.split("\n");
}
}
xmlhttp.open("GET","OFCaddresses.txt",true);
xmlhttp.send();
}
</script>
</head>
<body>
<div id="myDiv"><h2>"FILE.txt"</h2></div>
<button type="button" onclick="readFile()">FILE</button>
</body>
</html>
I am trying to better understand how this works if someone could explain. I understand how they define xmlhttp depending on the browser, but what does
document.getElementById("myDiv").innerHTML=xmlhttp.responseText.split("\n");
actually do? Does it change the content of myDiv from the text to the file content? What does onreadystatechange have to do with the button?
It appears you need to do a lot more reading on what javascript does and how it works.
xmlhttp.onreadystatechange=function() is assigning a function to the xmlhttp object that will get executed when the readystate changes. This means that as the xmlhttp object goes through it's various stages of requesting data, it will execute this function a number of times.
Within that function you have a check: if (xmlhttp.readyState==4 && xmlhttp.status==200)
This is saying if the readystate is 4 (complete - see here for more info on readystates) then continue to execute everything within the {} blocks.
Finally, you have this code
document.getElementById("myDiv").innerHTML=xmlhttp.responseText.split("\n");
This is using the document object which holds all the html on the page. The getElementById method searches the html objects for an item with the given id. You've got the following html
<div id="myDiv"><h2>"FILE.txt"</h2></div>
so document.getElementById("myDiv") finds this div. The innerHTML property returns the html of that div, which is currently your <h2> header.
xmlhttp.responseText.split("\n"); gets the response from your xmlhttp object and splits it into an array by new lines and sets this as the new value innerHTML object. When an array is printed in html, it is comma-separated.
Hope this gives you a better understanding. But these are pretty basic javascript commands so you have a lot of learning to go.
document.getElementById("myDiv")
access the element with ID myDiv.
document.getElementById("myDiv").innerHTML
access the innerHTML of element with ID myDiv
xmlhttp.responseText
get the body of the xmlhttp response (as opposed to the header or other information sent along with the response)
xmlhttp.responseText.split("/n")
split the response into an array, with the delimiter being the newline character.
document.getElementById("myDiv").innerHTML=xmlhttp.responseText.split("\n");
Replace everything that is inside the element with id myDiv with the response text, changing newlines into commas (since the array, when treated as a string, will use commas to separate array values).
Note: an AJAX request (which is what the whole xmlhttpRequest is all about) is asynchronous, that is, it will happen outside the normal course of the code you are running. So, you need a way to use the information once you get a response back. onreadystatechange is an event that will resolve when a response is received from the server (success or failure). which is why the function further tries to figure out readyState and status: to ensure the response was successful. If you have a slow internet connection or the server is far away you'll notice the asynchronous part more obviously than when it's all happening on your own computer: it may take a second or two to resolve.

Read XML File using Javascript from a Local Folder

I am trying to learn how to read into a web page data in an XML file. This is a static HTML page. I do not want a web server and I cannot use Ajax. The XML file is local (in the same directory as the HTML file). I want this to work in a Chrome browser.
What I need to do is:
Read the XML file on the page onLoad event.
Use innerHTML to insert the XML data into a div.
My problem is in reading the XML file. All of the examples I have found I think will only work if there is a web server running, which I have to avoid.
If you're reading another file the only way to do that with front end JS is another request (ajax). If this were node.js it would be different because node can access the filesystem. Alternatively if you get the xml into a javascript string on the same page, you can manipulate it. There are a number of good libraries (jquery's parseXML).
Original answer here: https://stackoverflow.com/a/48633464/8612509
So, I might be a little late to the party, but this is to help anybody else who's been ripping his/her hair out looking for a solution to this.
First of all, CORS needs to be allowed in the browser if you're not running your HTML file off a server. Second, I found that the code snippets most people refer to in these kind of threads don't work for loading local XML-files. Try this (example taken from the official docs):
var xhr = new XMLHttpRequest();
xhr.open('GET', 'file.xml', true);
xhr.timeout = 2000; // time in milliseconds
xhr.onload = function () {
// Request finished. Do processing here.
var xmlDoc = this.responseXML; // <- Here's your XML file
};
xhr.ontimeout = function (e) {
// XMLHttpRequest timed out. Do something here.
};
xhr.send(null);
The method (1st arg) is ignored in xhr.open if you're referring to a local file, and async (3rd arg) is true by default, so you really just need to point to your file and then parse the result! =)
Good luck!
Since you're only targeting Chrome, you could take a look at the File API. You'd have to prompt the user to select the file or drop it into a specific area of the page though, which might be something you'd rather avoid, or not. The following HTML5 Rocks article should help.
Assuming the HTML, XML and browser are all on the same machine, you might try using an Iframe in the HTML that references the XML using a URL like file:\.
You could do something like this:
<html>
<head>
<script type="text/javascript">
//If using jQuery, select the tag using something like this to manipulate
//the look of the xml tags and stuff.
$('#xframe').attr('style', 'thisxmltag.....');
</script>
</head>
<body>
...
<frame id="xframe" src="the_xml_doc"></src>
</body>
</html>
if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
}
else {// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET", file_Location, false);
xmlhttp.send();
xmlDoc = xmlhttp.responseXML;
document.getElementById(your_div_id).value =
xmlDoc.getElementsByTagName(The_tag_in_xml_you_want_to_display)
[0].childNodes[0].nodeValue;
Works with IE11
<head>
// To be hidden with a better method than using width and height
<OBJECT id="data1" data="data.xml" width="1px" height="1px"></OBJECT>
// to work offline
<script src="lib/jquery-2.2.3.min.js"></script>
</head>
<body>
<script>
var TheDocument = document.getElementById("data1").contentDocument;
var Customers = TheDocument.getElementsByTagName("myListofCustomers");
var val1 = Customers[0].getElementsByTagName("Name")[0].childNodes[0].nodeValue;

Having an error reading a text file with javascript

I've been trying to learn how to read a text file locally using JavaScript and Ajax. I've been looking on some tutorials online, and have followed them, but no matter what I do I cannot get my text to display what is in the .txt file.
function loadDoc(){
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState==4 && xmlhttp.status==200){
xmlhttp.open("GET","names.txt",true);
allText = xmlhttp.responseText;
lines = xmlhttp.responseText.split("\n");
}
}
xmlhttp.send(null);
document.getElementById("myDiv").innerHTML=allText;
}
I think this is meant to change the div I have (id "myDiv") to read what is in the text file, but it does not seem to do this, no matter what I try. Any help would be appreciated - I'm still new to JavaScript and Ajax.
Use Firebug or Chrome's developer tools to make sure that the AJAX call is returning the correct text.
Is names.txt in the same directory as the HTML page?

Loading a text file into javascript

I have a text file with a lot of values and I want to know if there is a way of loading these text file values into java script so that these values van be used by the script itself. Note I'm a newbie...
You haven't provided much context, but if we assume you mean "JavaScript running in a browser via an HTML page loaded from the same server as the text file", then you want to use the XMLHttpRequest object.
(Which is well documented in many places, so rather then providing yet another tutorial here, I'll let people use Google in the unlikely event of the above link breaking).
There are no shortage of libraries that abstract XHR. e.g. YUI, a host of tiny libraries and jQuery.
Assuming the text file is on your web server and you are loading from the browser, you could use jQuery like so:
jQuery.get('http://localhost/mytextfile.txt', function(data) {
alert(data);
});
Using XMLHttpRequest, you can achieve.
Example:
function ajaxCall() {
var xmlhttp;
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
}
else if (window.ActiveXObject) {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
else {
alert("Your browser does not support XMLHTTP!");
}
return xmlhttp;
}
xmlhttp = ajaxCall();
xmlhttp.open('GET', 'YOURFILE.txt');
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4) {
alert(xmlhttp.responseText);
}
}
with jQuery:
$('#result').load('ajax/test.txt');
Html code:
<div id="result">Text loaded here</div>
After loading the text will be replaced with the text file.

Categories