Cannot read property 'getElementsByTagName' of null - javascript

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.

Related

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.

XMLHttpRequest does nothing....?

I am new to javascript and AJAX, and have spent the last 8 hours on this one problem, and its beating me. I know its simple, just can't find what I am doing wrong. I have an image on my site with a with an on-click=SendCommand() . This is the js code that I have
function SendCommand(){
alert("BingoBango!");
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET","https://www.justanexample.com/API/MobileAPP/SendCommand.php?apikey=7785adf3a5d3a3adsf555nb5v55bsaer5v&mac=b827eb6ffa19&command=2",true);
xmlhttp.send();
};
I get the alert message, and I get no errors using firebug or in chrome javascript console. However that page is not executed. I can however copy and paste that exact url into the browser and it executes successfully.
Any help would be GREATLY appreciated, its kickin my butt.
The page it is calling is calling a python script as well as updating a mysql record. Is there something i can do in my request to ask it to not use the browser cache and actually hit my server?
You should not use a GET request for things that execute actions on the server. Use POST instead, which should not be cached.
If that doesn't help, adapt your HTTP cache headers or, as a last resort, append random strings to the url.
This is how I would do it
JS
function SendCommand()
{
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;
}
}
xmlhttp.open("GET","https://www.justanexample.com/API/MobileAPP/SendCommand.php?apikey=7785adf3a5d3a3adsf555nb5v55bsaer5v&mac=b827eb6ffa19&command=2",true);
xmlhttp.send();
}
HTML
<button type="button" onclick="SendCommand()">My button</button>
<div id="myDiv"></div>

Unable to synchronize Java Script and CGI

I am facing a problem in synchronizing my CGI with web-page. I have one CGI which is written in C Language and is responsible for creating XML file and continuously updating it. My web page reads that XML and displays the content on the page. And Both (CGI and Web-page) are continuously running. Some times when my CGI writing the data in to the xml file, web-page tries to read it at the same time and my function which is written in java script fails to read Data. Is there any way to synchronize this. (Like in linux we use mutex) Something like that.
Some snap of my code which i am using to read XML file:
<xml ID="noteXML"
SRC="note.xml"></xml>
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","note.xml?"+ Math.random(),false);
xmlhttp.send();
xmlDoc=xmlhttp.responseXML;
document.getElementById("to").innerHTML=
xmlDoc.getElementsByTagName("to")[0].childNodes[0].nodeValue;
Part Of my CGi to create XML
void CreateXMLFile()
{
char buffer[300];
sprintf(buffer,"<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?> \n <note> \n <to>%d</to> \n <status>%s</status> <upgraded>%d</upgraded> <remaining>%d</remaining> \n </note>",100,"Welcom to XML",10,15);
FILE *xml = fopen("/var/www/html/note.xml","w");
if(xml)
{
fprintf (xml,"%s",buffer);
fclose(xml);
}
When debugging its giving error in following line (Java Script):
"document.getElementById("to").innerHTML= xmlDoc.getElementsByTagName("to") [0].childNodes[0].nodeValue;"
Use file locking (flock) to mark when a file is in use so you block reading from it until it is updated. You'll probably have to read it through another CGI application so that you can respect the lock.
Better yet - don't store your data in an XML file in the first place. Use an RDBMS and generate the XML on the fly.

how to abort a xmlhttprequest before starting a new request?

I got a cgi-script the performs a search according to the query-string it gets submitted.
That works all fine.
But since the search can take some time and the user might start another search. I want the first search to get aborted before a second search is started, but if I insert a xmlhttp.abort() at the beginning of my AJAXRequest function the cgi-script doesn't get started at all.
Can anyone tell me how this could be performed?
Thanks in advance!
and here is the AJAX-code snippet
var xmlhttp;
function AJAXRequest()
{
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)
{
window.document.getElementById("resultlist").innerHTML=xmlhttp.responseText;
}
}
var queryString= "from=03-01-2006&to=04-30-2006&pattern=345";
xmlhttp.open("POST","../cgi-bin/search.exe?"+queryString);
xmlhttp.send();
}
Yea, XMLHttpRequest.abort() is a correct method to use for AJAX request aborting.
In my opinion your problem is more kind of design problem and not technical.
Therefore my suggestion is to review the flow of how the user interacts with your application.
For example, the classical solution is to show the progress bar or spinner and disable the "Search" button while your request is not completed and revert this state on success or error.
I found my problem.
I tried to abort a request object that has just been created. The object has to be global. At least that's the only way I see how to achieve this.

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

Categories