Forum Moderators: open

Message Too Old, No Replies

get ElementbyId help null value

         

mantech

8:03 pm on Jun 1, 2017 (gmt 0)

5+ Year Member



I am new to AJAX and XML. I was trying to extract XML date from this site however the getElementById('FIRSTNAME') return null, what is the correct code?
Below is the code I use

<!DOCTYPE html>
<html>
<body>

<button id="ajaxButton" type="button">Make a request</button>

<script>
(function() {
var httpRequest;
document.getElementById("ajaxButton").addEventListener('click', makeRequest);

function makeRequest() {
httpRequest = new XMLHttpRequest();

if (!httpRequest) {
alert('Giving up :( Cannot create an XMLHTTP instance');
return false;
}
httpRequest.onreadystatechange = alertContents;
httpRequest.open('GET', 'http://www.example.com/sqlrest/CUSTOMER/18/');
httpRequest.send();


}

function alertContents() {

if (httpRequest.readyState === XMLHttpRequest.DONE) {
if (httpRequest.status === 200) {
alert(httpRequest.responseText);
} else {

alert(httpRequest.status);
alert(getElementById('FIRSTNAME'));

}

}

}

})();
</script>
</body>
</html>

[edited by: phranque at 11:09 pm (utc) on Jun 1, 2017]
[edit reason] disabled graphic smile faces [/edit]

Fotiman

11:55 pm on Jun 1, 2017 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



alert(getElementById('FIRSTNAME'));

getElementById is a method of the document, so you can't just call it like a global function, you'd need to call it on some document object.
Additionally, you haven't actually added the response from your httpRequest to the DOM, so you wouldn't find it in the DOM even if you call it with document.getElementById.

If your request is being treated as XML, then you may want to use httpRequest.responseXML instead of httpRequest.responseText. The value stored in responseXML is a document object, so you could do:
alert(httpRequest.responseXML.getElementById('FIRSTNAME'));

lucy24

12:44 am on Jun 2, 2017 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



You've shown the script, but you haven't shown the part of your HTML that actually contains the object--whatever it may be--whose ID is "FIRSTNAME", case sensitive. So it's pretty impossible to know where the problem lies. Does the element exist? Does it have content? Is the content guaranteed to be in a form that can be used by the requesting function?