Read XML using ASP/JavaScript - javascript

I will send some information from one site to another site. I have an XML generated, using the script below.
How can I read the XML into readxml.asp?
var xmlServer = "http://www.****/readxml.asp";
var xmlStr = "";
xmlStr+='<hm>';
xmlStr+='<debnr>Debnr</debnr>';
xmlStr+='<date>'+getToday()+'</date>';
xmlStr+='<time>'+getTime()+'</time>';
xmlStr+='<ip>'+ipNum+'</ip>';
xmlStr+='</hm>';
var xmlhttp = Server.CreateObject ("MSXML2.ServerXMLHTTP");
xmlhttp.open ("POST", xmlServer, false);
xmlhttp.setRequestHeader("Content-Type", "text/xml")
xmlhttp.send(xmlStr);
var node = ""+xmlhttp.responseText;

Instead of var node I believe the code you're looking for is:
var xmldoc = CreateObject("Microsoft.XMLDOM");
xmldoc.loadXML(xmlhttp.responseText);
However, your code is rather dangerous in that the XML request you're sending could be invalid XML. For instance, if Debnr, getToday(), getTime() or ipNum contains invalid characters (e.g. if they themselves contain symbols like <, > or &) then the request you're building will be malformed. I recommend that the request be built using the XMLDOM too.

I believe you can load XML data directly from ASP Request object if it is being sent from the client as follows :
' Load the specified XML file
'------------------------------
mydoc.load(Request)

Related

The response received in javascript is not XML while on browser it displays an XML

I am new to javascript and REST services. I am trying to fetch some data from a url. The javascript code I wrote is as below:-
<script>
var request = new XMLHttpRequest();
request.open("GET", "https://findtest.akamai.com/_api/search/query?querytext=%27Agora%27&sourceid=%2782cdf98b-cc8b-48c3-a706-d88c1333cc4b%27&QueryTemplatePropertiesUrl=%27spfile://webroot/queryparametertemplate.xml%27&rowlimit=60&selectproperties=%27Title,Author,Url,Date%27&StartRow=%270%27&trimduplicates=%27true%27", false);
request.send();
var xml = request.responseText;
document.write(xml);
</script>
The responseText received looks something like below:-
While when I open it in browser IE/Chrome:-
This same response flashes on the screen for a moment and then proper XML is displayed like below:-
I am unable to get the response XML in my javascript. Is it some kind of encoding that I have to decode ? I want the proper XML response.
Remember that when writing to an HTML page, you're writing HTML, not plain text. < and & (at a minimum) have to be encoded as entities.
document.write has virtually no place in 2018 (or really the 21st century at all). You can instead append a text node so the string is used as text, not HTML:
document.body.appendChild(document.createTextNode(xml));
Example:
var xml = "<root><thing/><another-thing/></root>";
document.body.appendChild(document.createTextNode(xml));
You might even wrap it in a code element:
var code = document.createElement("code");
code.appendChild(document.createTextNode(xml));
document.body.appendChild(code);
Example:
var xml = "<root><thing/><another-thing/></root>";
var code = document.createElement("code");
code.appendChild(document.createTextNode(xml));
document.body.appendChild(code);

Reading text data from a file stored in Parse.com

I'm saving large text files as objects in Parse. They are too large to save directly as text in a normal String column.
Later, I want to retrieve these files and process the text in JavaScript.
Here's the code I'm using to store the text in a Parse file:
// Inputs
var long_text_string = '...'; // A long string
var description = '...'; // Description of this string
// Convert string to array of bytes
var long_text_string_bytes = [];
for (var i = 0; i < long_text_string.length; i++) {
long_text_string_bytes.push(long_text_string.charCodeAt(i));
}
// Create Parse file
var parsefile = new Parse.File("long_text_string.txt", long_text_string_bytes);
parsefile.save({
success: function() {
// Associate file with a new object...
var textFileObject = new Parse.Object("TextFile");
textFileObject.set('description', description);
textFileObject.set('file', parsefile);
textFileObject.save();
}
});
How do I then retrieve the content of the data file, convert it back from bytes to string, and end up with it stored in a normal string variable in JavaScript?
UPDATE
I've tried three different approaches, all to no avail...
Method 1 [preferred]
Use Parse commands to process the file
It's simple to use the Parse JS API to retrieve my TextFile object, and use parseFile = object.get('file'); to get the Parse file itself. The URL of the file is then parseFile.url().
But then what? I can't do anything with that URL in JS because of cross-origin restrictions.
There is no documentation on how to use the JS API to access the byte data contained within the file. There appears to be an Android command, getDataInBackground, documented here, so I am hopeful there is a JS equivalent....
Method 2
Use the Parse REST API to fire a XMLHTTP request
Unfortunately, it seems that Parse have not enabled CORS for their file URLs. I have tried the following code, adapted from a Parse.com blog post (blog.parse.com/learn/engineering/javascript-and-user-authentication-for-the-rest-api/):
var fileURL = textFileObject.get('file').url();
var xhr = new XMLHttpRequest();
xhr.open("GET", fileURL, true);
xhr.setRequestHeader("X-Parse-Application-Id", appId);
xhr.setRequestHeader("X-Parse-REST-API-Key", restKey);
xhr.setRequestHeader("Content-Type", "application/json");
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
alert(xhr.responseText);
}
};
var data = JSON.stringify({ message: "" });
xhr.send(data);
But I get the following error:
Response to preflight request doesn't pass access control check:
No 'Access-Control-Allow-Origin' header is present on the requested resource.
Origin '<my host>' is therefore not allowed access.
The response had HTTP status code 403
A bit of a Google suggests that the file URLs are not CORS-enabled (parse.com/questions/access-control-allow-origin--2).
(Note that the above code works for a normal object request, it's only when you use the fileURL that it errors).
Method 3
Use a browser to circumvent cross-origin restrictions
I can create a webpage with an empty iframe and set iframe.src to parseFile.url(). The content of the file appears on the web page. But I still end up with cross-origin issues when I try to access the DOM content of the iframe! Not to mention loading each file onto a webpage one by one is an incredibly substandard solution.

Passing a URL which includes an ampersand from Javascript to PHP to a MySQL data bsae

Objective:
I am trying to place a URL into a MySQL database.
The URL contains many special characters.
The specific character that causes a problem is the & character. (The process works correctly as long as there is no & character in the string).
I pass the URL from JavaScript to a PHP script.
The URL starts out as http://www.example.com/?def&ghi in the Javascript.
I then code
rssURL = encodeURIComponent(rssURL); // perform encode
which displays the following value in the console.log
http%3A%2F%2Fwww.example.com%2F%3Fdef%26ghi%20
I send the URL to the PHP script using the following code in the Javascript
xhr = new XMLHttpRequest();
xhr.open("POST", "updatecontent.php", true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.send(userdata);
The userdata variable contains:
“datastring” = username^password^rssURL^ varX^ varY
In the PHP script, I have the following code
$URLgroup= $_POST['datastring'];
$datalist = explode ('^', $URLgroup);
$ws_user = $datalist[0];
$ws_pass = $datalist[1];
$ws_urlX = $datalist[2];
// this is the rssURL element passed from the Javascript
$ws_url = rawurldecode ($ws_urlX); // perform decode
$ws_title = $datalist[3];
$ws_category = $datalist[4];
I place the URL in the data base using the following code
$sql = "INSERT INTO global_feeds_table (global_feed_category, global_feed_name, global_feed_title, global_feed_link)
VALUES ( '$ws_category', '$ws_div_id', '$ws_title', '$ws_url') ";
The data base field called global_feed_link now contains the following URL
http://www.example.com/?def&ghi
The URL should just contain an “&” (after “def” and before “ghi”) BUT it also has “amp;” after the & character THIS IS THE PROBLEM
Environment:
Using UTF8 encoding throughout
Windows 10
Google Chrome Version 40
Dreamweaver 5 (IDE)

Dynamically create list items from local xml file

I'm trying to create a menu from an XML file. The HTML file that I want to create the menu in, is located my main project folder. This folder also contains an xml folder in which my xml file (fruitDB.xml) is located. I understood that there are several ways of loading XML files and that some ways only work online. Eventually the menu is used for an HTML5 mobile app (don't know if this is usefull information), build using Appcelerator.
I've read some sources but it's still not clear to me how I can load an XML file. I have the following code in my header tag:
<script type="text/javascript">
function init(){
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", "xml/fruitDB.xml", false);
xmlhttp.setRequestHeader('Content-Type', 'text/xml');
xmlhttp.send();
var xmlDoc = xmlhttp.responseXML;
var Fruits = xmlDoc[];
alert(Fruits);
for (var i = 0; i < Fruits.children.length; i++) {
alert("hi");
var Fruit = Fruits.children[i];
var Name = Fruits.getElementsByTagName("name");
var Thumb = Fruits.getElementsByTagName("image");
var list = document.getElementById("menuButtons");
var listEntry = document.createElement("LI");
listEntry.document.createTextNode(Name);
list.appendChild(listEntry);
}
}
</script>
What I try to do here is open the init(); function using , load the xml file, though I'm not sure if giving a path (like I'm doing) is correct. After the XML is loaded it should create new 's in my HTML file and give them name (and eventually an image) which are stored in the xml file until all items from the xml are placed as list items. Sorry for the long sentence :P.
At xmlhttp.send(); I recieved the following error in my console:
XMLHttpRequest cannot load file:///D:/folder/folder/folder/xml/fruitDB.xml. Received an invalid response. Origin 'null' is therefore not allowed access.
Does this mean that using XMLHttpRequest won't work on local files and if not what other way can I use in order to achieve my goal?
XML doesn't have great support in Titanium. Also XML is often a pain to work with..
Why not use a JSON payload / document instead!
Format the JSON so it is an array of fruit objects
Then you just parse the payload into a javascript object that comes back from the web-service or your local file something like this:
var fruits = JSON.parse(yourHTTPObj.responseData);
Now you can loop over the fruit objects and say:
if (fruits[i].type === 'Apple') { //do something };

Load XML formatted files with different extension than .xml using XMLHttpRequest object

I have this code that loads an xml file using javascript:
function getXmlDocument(sFile) {
var xmlHttp, oXML;
// try to use the native XML parser
try {
xmlHttp = new XMLHttpRequest();
xmlHttp.open("GET", sFile, false); // Use syncronous communication
xmlHttp.send(null);
oXML = xmlHttp.responseXML;
} catch (e) {
// can't use the native parser, use the ActiveX instead
xmlHttp = getXMLObject();
xmlHttp.async = false; // Use syncronous communication
xmlHttp.resolveExternals = false;
xmlHttp.load(sFile);
oXML = xmlHttp;
}
// return the XML document object
return oXML;
}
If the extension of the 'sFile' is not .xml the function returns "" always. What should I do to fix this?
I think it's a problem on the server side: files with another extension than .xml don't get the MIME type of text/xml or something alike and the browser('s XML parser) doesn't recognize it as XML.
Be sure that your content is served with the correct MIME type by your server software. With Apache, you can change this in the .htaccess file. Dynamically generated XML should be sent with an appropriate Content-Type: header. In PHP, you can do this with the header function.

Categories