Explaining how document.getelementbyid.innerhtml prints text - javascript

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.

Related

Cannot read property 'getElementsByTagName' of null

I've been searching around for answers to this particular problem for about two days now. I can't seem to figure out what's going on with it. All this seemed to have worked in the past but isn't working anymore.
XML:
<ZipCodes>
<results>
<city>Chicago</city>
<state>IL</state>
<timezone>-6</timezone>
</results>
javascript:
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","_checkzip.php?zip="+str,true);
xmlhttp.send();
xmlDoc=xmlhttp.responseXML;
x=xmlDoc.getElementsByTagName("results");
i=0;
document.forms["signup"]["City"].value=(x[i].getElementsByTagName("city")[0].childNodes[0].nodeValue);
document.forms["signup"]["states"].value=(x[i].getElementsByTagName("state")[0].childNodes[0].nodeValue);
document.forms["signup"]["TimeZone"].value=(x[i].getElementsByTagName("timezone")[0].childNodes[0].nodeValue);
and the error I get is
Cannot read property 'getElementsByTagName' of null
when I try x=xmlDoc.getElementsByTagName("results"); The xml is deffinetly coming in on the network response when I look at the debug in Chrome.
You can use an event handler on an XMLHttpRequest's onreadystatechange to make sure the request is done. If the status of readyState is 4, the operation is complete.
Currently you're asking for data that hasn't been transmitted yet.
Apart from ensuring that xmlhttp.readyState==4 && xmlhttp.status==200, this error can also occur if you outputed any content, letter, character or string before sending your xml data from the server. For instance Assuming that in java you have a method/function called sendXMLdata, and then in your servlet you printed the string "connected" before calling the method:
....
out.println("Connected");
String data="My Name"
sendXMLdata(response,data);
....
Then the output when viewed from browser source will be this:
Connected
My Name
So this will certainly give you an error since the browser would not be able to parse the string "connected" since it is not the write format to render xml data.

Loading DIV content via ajax as HTML

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 ..........");

How to react on Response from a form post in JavaScript

I want to create a Login-Screen in HTML where the user can fill out his username and password. After that he sends the Data with a submit to the server which validate the data. If the Login is correct he sends back a message in JSON format with an id, like this:
{"id":"37"}
Now my question: How can i get this information in Javascript? I want to check the id and, if it's OK, redirect the user to a new HTML screen.
I'm working with PhoneGap to create a Android Application, so the only things I can use are HTML, CSS and JavaScript. To send the POST i use the HTML <form> tag, not a special JavaScript. If I test it in Firefox it works, I fill out my Username and Password and then the Message with the id is shown. Now I want to react on this response with JavaScript. Can somebody help me?
AJAX Code:
function loadXMLDoc() {
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) {
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
}
};
xmlhttp.open("POST",url,true);
xmlhttp.send(login);
A JSON parser will recognize only JSON text, rejecting all scripts. In browsers that provide native JSON support, JSON parsers are also much faster than eval. It is expected that native JSON support will be included in the next ECMAScript standard.
var myObject = JSON.parse(myJSONtext, reviver);
The optional reviver parameter is a function that will be called for every key and value at every level of the final result.
now access the id property like myObject.id

Run entire PHP-file from Javascript with AJAX

on $(document).ready(function() in index.php, the below AJAX is executed, running the file getData.php:
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("dataSuccess").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","getData.php",true);
xmlhttp.send();
In the getData.php file, data is gathered from MySQL and put in JS-arrays:
var guestData = new Array("<? for ($j=0;$j< sizeof($guestData);$j++) { print ($guestData[$j]); ?>","<?php } $j = $j+1; ?>");
And finally, store the data in my js arrays into LocalStorage:
var guestDataCols = new Array();
guestDataCols = guestData[0].split(",")
var arrayIndex=0;
for(arrayIndex=0;arrayIndex<guestData.length-1;arrayIndex++)
{
localStorage.setItem(arrayIndex, guestData[arrayIndex]); // storing
}
EVERYTHING works! But the problem is that my AJAX code doesn't seem to run through the entire getData.php file since LocalStorage in yet empty after the php-file is executed via AJAX. However (and this is a big one), if I simply refresh getData.php in another window, data is stored perfectly and evernything works. I've also tried using jQuery for this as suggested in another Stack Overflow question
$('#dataSuccess').load('getData.php'); //instead for the AJAX code
but with the exact same and somewhat mediocre result. So my questions is, why isn't the AJAX script running the entire php file and HENCE, why is no data stored in LocalStorage?
JavaScript on an HTML page is not run when called by an XMLHttp request. The browser doesn't parse the pages that JavaScript receives over XMLHttp requests and therefore does not run the JavaScript. You would have to output to the browser for it to be run. Your best bet would be do have the PHP return the data you need and then extract it from the XMLHttp request. For example, the getData.php could return a JSON string containing the data you need. Then on the page with the XMLHttp request, you could parse that JSON string and save it to the localStorage on that page.
I think you're looking for jQuery.getScript

Javascript XMLHttpRequests in Loop?

I am trying to save an array of records into a mysql database but I always get the abort message in firebug except for the last save. How do I save the records using a loop for XMLHttpRequest? Here is my code:
function savingContent()
{
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
var rowindex = 0;
for (x in globalObj.AddedRows)
{
var rowData = "?q=" + globalObj.AddedRows[rowindex];
xmlhttp.open("POST", "insertRowData.php"+rowData, true);
xmlhttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
xmlhttp.setRequestHeader("Content-Length",rowData.length);
xmlhttp.send(null);
rowindex += 1;
}
There are quite a few problems with this code. Here are just the first ones I found:
The for (x in object) syntax should only be used when you want to iterate over all fields in an object. In this case you want to iterate over an array, so you should do it like this:
for (var rowindex = 0; rowindex < globalObj.AddedRows.length; rowindex++) {
}
When doing an HTTP POST, you shouldn't put the data you want to change into the URL. Put it in the body of the request - as the argument to xmlhttp.send(). You're actually explicitly passing a content length - that length is supposed to be the length of the data you pass to xmlhttp.send() - so by passing NULL this is almost certainly your main error.
Rather than using Firebug, it'd be better to use xmlhttp.onreadystatechange to figure out which of your requests are succeeding or failing. Don't assume that once you have it debugged the first time, it will always succeed from then on. Handle errors.
In addition to dmazzoni:
Every time your for loop sends an async xml request it overrides the previous request and therefore the previous one is aborted. You should create a new XMLHttpRequest (or ActiveXObject for IE) inside your for-loop or wait for the HTTP return call, before sending a new request.

Categories