Reading XML returned from AJAX - javascript

I have defined this XML file
<?xml version="1.0" encoding="UTF-8"?>
<root>
<town>
<area>20000</area>
<population>10000</population>
</town>
</root>
with AJAX I load this and I try to parse it.
<script>
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function(){
if(this.readyState == 4 && this.status == 200){
myFunctionParsing(this);
}};
xhttp.open("GET", "towns.xml", false);
xhttp.send();
function myFunctionParsing(xml)
{
var xmlDoc = xml.responseXML;
var nodes = xmlDoc.getElementsByTagName("town");
var n = nodes[0].childNodes[0];
console.log(n.tagName);
var aDiv = document.getElementById("area");
aDiv.innerHTML = n.nodeValue;
}
With that script I want to write in div value of node "area" in some div with name "area".
Why can not I write this value? Why n.tagName is undefined?

A couple things:
I am using MDN's XMLHttpRequest example, which shows how to override the mime type to force it to parse the response as XML. That way you don't have to do responseXML.
querySelector is great! Use it. No need for getElementsByTagName.
function parseXML(xml) {
var area = xml.querySelector('town area');
console.log(area.textContent); // => 20000
}
var url = 'https://gist.githubusercontent.com/gabrielflorit/c618f26ac367fbaf91846efe73913c23/raw/b3c9c3e8d0f1dc747006103442b3b19bf7c91d9c/town.xml';
var xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
// If specified, responseType must be empty string or "document"
xhr.responseType = 'document';
// overrideMimeType() can be used to force the response to be parsed as XML
xhr.overrideMimeType('text/xml');
xhr.onload = function () {
if (xhr.readyState === xhr.DONE) {
if (xhr.status === 200) {
parseXML(xhr.response);
}
}
};
xhr.send(null);

Related

How can I parse this specific XML data?

I'm trying to parse this XML, and I can't extract all of the "" texts in that file, can someone please tell me what I'm doing wrong?
Here is the HTTP /GET that I'm trying to make a request to,
request_link:"https://cdnsecakmi.kaltura.com/api_v3/index.php/service/caption_captionAsset/action/serve/captionAssetId/0_o7nr2wfk/v/2/ks/djJ8MjAxMTUzMXyLXeiobMjq3pQ7i9wYSlwZHhVUdAP8C6IYMqJGpcDqOsBc4X5e0rTARtFc6ysPSkDTq_u7qfycIGeJquoL_O_3MlBxOn9rBGgQBZXeeAQrcd8tmZqjZo2h5bQVGtQXgFHVc7OyICn-cY2lHa4ZjRp6w2ueyIRqyNp9pHZ5onX2Z6gfjyNR4MubV3V6Qwfa3e0hbRdAoCap1dgO2QIawMKi/.dfxp"
const get_religion_notes = new XMLHttpRequest();
get_religion_notes.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
// Typical action to be performed when the document is ready:
console.log(get_religion_notes.responseXML)
let parser = new DOMParser();
xmlDoc = parser.parseFromString(get_religion_notes,"text/xml");
console.log(document.getElementById("demo").innerHTML = xmlDoc.getElementsByTagName("p")[0])
document.getElementById("demo").innerHTML = xmlDoc.getElementsByTagName("p")[0]; //Undefined why is that?
}
};
get_religion_notes.open("GET", "https://cdnsecakmi.kaltura.com/api_v3/index.php/service/caption_captionAsset/action/serve/captionAssetId/0_o7nr2wfk/v/2/ks/djJ8MjAxMTUzMXyLXeiobMjq3pQ7i9wYSlwZHhVUdAP8C6IYMqJGpcDqOsBc4X5e0rTARtFc6ysPSkDTq_u7qfycIGeJquoL_O_3MlBxOn9rBGgQBZXeeAQrcd8tmZqjZo2h5bQVGtQXgFHVc7OyICn-cY2lHa4ZjRp6w2ueyIRqyNp9pHZ5onX2Z6gfjyNR4MubV3V6Qwfa3e0hbRdAoCap1dgO2QIawMKi/.dfxp", true);
get_religion_notes.send();
Everything is correct.
just make sure your using responseText parser requires text xml not xml itself..
const get_religion_notes = new XMLHttpRequest();
get_religion_notes.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
// Typical action to be performed when the document is ready:
console.log(get_religion_notes.responseText)
let parser = new DOMParser();
xmlDoc = parser.parseFromString(get_religion_notes.responseText,"text/xml");
console.log(document.getElementById("demo").innerHTML = xmlDoc.getElementsByTagName("p")[0])
document.getElementById("demo").innerHTML = xmlDoc.getElementsByTagName("p")[0]; //Undefined why is that?
}
};
get_religion_notes.open("GET", "https://cdnsecakmi.kaltura.com/api_v3/index.php/service/caption_captionAsset/action/serve/captionAssetId/0_o7nr2wfk/v/2/ks/djJ8MjAxMTUzMXyLXeiobMjq3pQ7i9wYSlwZHhVUdAP8C6IYMqJGpcDqOsBc4X5e0rTARtFc6ysPSkDTq_u7qfycIGeJquoL_O_3MlBxOn9rBGgQBZXeeAQrcd8tmZqjZo2h5bQVGtQXgFHVc7OyICn-cY2lHa4ZjRp6w2ueyIRqyNp9pHZ5onX2Z6gfjyNR4MubV3V6Qwfa3e0hbRdAoCap1dgO2QIawMKi/.dfxp", true);
get_religion_notes.send();

Read all values from xml tags with javascript

im currently working on reading a xml file, i have successfully read the xml file so far but the problem comes next, instead of reading the xml file tag one by one i want to read the tags that are inside the items tag and extract the value of each one
So far this is what i got
var xmlDoc;
var xhr = new XMLHttpRequest();
xhr.open('GET', 'prueba.xml');
xhr.send();
xhr.onreadystatechange = function(){
xmlDoc = xhr.responseXML;
var items = xmlDoc.getElementsByTagName("items")[0];
for(i=0;i<items.length;i++){
item = items[i];
$(item).each(function(i,val){
console.log(val)
})
}
}
and here's the xml file
<!DOCTYPE StreamControl>
<items>
<timestamp>1510794812</timestamp>
<nombre>ayy</nombre>
</items>
I think i'm close, any tips?
try this:use node.firstChild.nodeType === 3 && node.firstChild.textContent.trim() !== '' to filter the text;
var xmlDoc;
var xhr = new XMLHttpRequest();
xhr.open('GET', 'prueba.xml');
xhr.send();
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
xmlDoc = xhr.responseXML;
var items = xmlDoc.getElementsByTagName("*");
let res = {};
Array.from(items).forEach(node => {
if (node.firstChild.nodeType === 3 && node.firstChild.textContent.trim() !== '') {
res[node.nodeName] = node.firstChild.textContent
}
});
console.log(res);//{timestamp: "1510794812", nombre: "ayy"}
}
}

Using Javascript to Create a XML Document from a HTML Form

I'm having a lot of difficulty with this project.
My aim is to write the results of a HTML form to an XML Document using Javascript.I have absolutely no idea how to do it.
Reason why I'm coming here is that I want to be sure that I'm on the right track. So far, I'm writing only one line "\n" just to test things out.
Here is my current JavaScript
var xhr = false;
if (window.XMLHttpRequest)
{
xhr = new XMLHttpRequest();
}
else if (window.ActiveXObject)
{
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
function StoreRegXml()
{
xhr.open("GET", "php.php?" + Number(new Date), true);
xhr.onreadystatechange = getData;
xhr.send(null);
}
function getData()
{
if ((xhr.readyState == 4) && (xhr.status == 200))
{
var xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
var fso = new ActiveXObject("Scripting.FileSystemObject");
var filename = "customer.xml";
var file = fso.CreateTextFile(filename, true);
file.WriteLine('<?xml version="1.0" encoding="utf-8"?>\n');
file.Close();
}
}
Am I on the right track?
Edit: I'm adding alerts('test1'); to see where the code is going wrong and it stops at
var xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
Any ideas?
Inside the browser to create and populate an XML DOM document you can use the W3C DOM APIs with e.g.
var xmlDoc = document.implementation.createDocument(null, 'root', null);
var foo = xmlDoc.createElement('foo');
foo.textContent = 'bar';
xmlDoc.documentElement.appendChild(foo);
console.log(xmlDoc);
This creates an in memory XML DOM document, not an XML file. You can then for instance send the xmlDoc with XMLHttpRequest to the server.

How to get array from ajax call in javascript

My ajax call looks like this:
request = new XMLHttpRequest();
request.open("GET","/showChamps?textInput=" + searchChamp.value,true);
request.send(null);
request.onreadystatechange = function () {
if (request.status == 200 && request.readyState == 4) {
//how do i get my array
}
};
}
I have sent an array from my node.js server but I don't know how to get that array because request.responseText does not give me back an array. Also it would be appreciated if the answer is in javascript.
Thanks in Advance!
var xhr = new XMLHttpRequest();
xhr.onload = function() {
if(xhr.status === 200) {
var responseHTML = xhr.responseText, // HTML
responseXML = xhr.responseXML, // XML
responseObject = JSON.parse(xhr.responseText); // JSON
}
};

BlobBuilder ruins binary data

I have a problem with BlobBuilder (Chrome11)
I try to obtain an image from server with XHR request. Then i try to save it to local FS with BlobBuilder / FileWriter. Every example on the internet is about working with text/plain mime type and these examples work fine. But when i try to write binary data obtained with XHR, file size becomes about 1.5-2 times bigger than the original file size. And it cannot be viewed in Picasa / Eye Of Gnome.
var xhr = new XMLHttpRequest();
var photoOrigUrl = 'http://www.google.ru/images/nav_logo72.png';
xhr.open('GET', photoOrigUrl, true);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
var contentType = xhr.getResponseHeader('Content-type');
fsLink.root.getFile('nav_logo72.png', {'create': true}, function(fileEntry) {
fileEntry.createWriter(function(fileWriter) {
var BlobBuilderObj = new (window.BlobBuilder || window.WebKitBlobBuilder)();
BlobBuilderObj.append(xhr.responseText);
fileWriter.write(BlobBuilderObj.getBlob(contentType));
}, function(resultError) {
console.log('writing file to file system failed ( code ' + resultError.code + ')');
});
});
}
}
xhr.send();
fsLink exists, this is extension.
The problem is that BlobBuilder.append(xhr.responseText) is detecting its argument as a UTF-8 string, which is what XHR returns, and not binary data, which is what it really is. There's a couple of tricks to get the BlobBuilder reading it as binary data instead of string data:
var xhr = new XMLHttpRequest();
var photoOrigUrl = 'http://www.google.ru/images/nav_logo72.png';
xhr.open('GET', photoOrigUrl, true);
// CHANGE 1: This stops the browser from parsing the data as UTF-8:
xhr.overrideMimeType('text/plain; charset=x-user-defined');
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
var contentType = xhr.getResponseHeader('Content-type');
fsLink.root.getFile('nav_logo72.png', {'create': true}, function(fileEntry) {
fileEntry.createWriter(function(fileWriter) {
// CHANGE 2: convert string object into a binary object
var byteArray = new Uint8Array(xhr.response.length);
for (var i = 0; i < xhr.response.length; i++) {
byteArray[i] = xhr.response.charCodeAt(i) & 0xff;
}
var BlobBuilderObj = new (window.BlobBuilder || window.WebKitBlobBuilder)();
// CHANGE 3: Pass the BlobBuilder an ArrayBuffer instead of a string
BlobBuilderObj.append(byteArray.buffer);
// CHANGE 4: not sure if it's needed, but keep only the necessary
// part of the Internet Media Type string
fileWriter.write(BlobBuilderObj.getBlob(contentType.split(";")[0]));
}, function(resultError) {
console.log('writing file to file system failed ( code ' + resultError.code + ')');
});
});
}
}
xhr.send();
This gave me a file with the same length as what xhr.getResponseHeader('Content-Length') suggests it should have been.
You can use xhr.responseType='arraybuffer' though:
BlobBuilder = window.MozBlobBuilder || window.WebKitBlobBuilder || window.BlobBuilder;
var xhr = new XMLHttpRequest();
xhr.open('GET', '/path/to/image.png', true);
xhr.responseType = 'arraybuffer';
xhr.onload = function(e) {
if (this.status == 200) {
var bb = new BlobBuilder();
bb.append(this.response); // Note: not xhr.responseText
var blob = bb.getBlob('image/png');
...
}
};
xhr.send();
I think Stoive is spot on but I want to point out that instead of BlobBuilder there is now Blob constructor available that will do the trick
var b = new Blob([byteArray.buffer], {'type': 'application/type'});
I think this is more in keeping with current standards. Thanks much Stoive, very helpful.
Btw XHR2 sets a better way for implementing my task:
var xhr = new XMLHttpRequest();
xhr.open('GET', 'http://www.google.ru/images/nav_logo72.png', true);
xhr.responseType = 'blob';
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
// xhr.responseBlob is needed blob data
}
}
xhr.send();
The only disappointment is that this is still a bug in Chrome: http://code.google.com/p/chromium/issues/detail?id=52486
XMLHttpRequest cannot load http://www.google.ru/images/nav_logo72.png. Origin file:// is not allowed by Access-Control-Allow-Origin.

Categories

Resources