"GET" multiple xml file in html - javascript

I am trying to show multiple xml file into html. I able get single xml file show in html table by using xmlhttp.open("GET", "204S_2000_02_17_00_30_357.xml", true). However, I can't get multiple xml file using this function.
I had tried using xmlhttp.open("GET", "*.xml", true) but doesn't get any output.
It's any solution or method to "GET" the multiple xml file into html?
Noted: xml file will continuously generate in folder with random name.(example 204S_2000_02_XX_XX_XX_XX.xml).
code that show single xml file in html table
function loadXMLDoc() {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
myFunction(this);
}
};
xmlhttp.open("GET", "204S_2000_02_17_00_30_357.xml", true);
xmlhttp.send();
}
function myFunction(xml) {
//coding....
}

One HTTP request gets one HTTP response.
In general, you can't get multiple files back from a single request using a wildcard.
You could, if you wrote suitable server-side code, have the server recognise a wildcard in the URL and respond by (for example) sending a zip file containing all the files that matched, or generating a new XML document containing the contents of all the files that matched.
Generally, however, you will make a separate request for each resource you want. Having determined all the URLs you wanted to request, you would probably want to use an API that supported promises (i.e. fetch instead of XMLHttpRequest) so you could feed them into Promise.all and run the next stage of the program once you had collected all the data.

Related

Loading Images into Gallery using PHP and JavaScript takes very long sometimes

A callback function triggers when my XMLHttpRequest has finished. I use an asynchronous JavaScript Function to load the content of a file that has been created by the PHP file_put_contents() function.
My problem is, that sometimes loading the gallery elements takes a very long time. I should rather return the html code I want to load as a string instead of writing it into a file.. but I do not know how?
This is my Javascript:
function xhr(php, form, after) {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState == XMLHttpRequest.DONE) {
after();
}
}
xhr.open('POST', php, true);
xhr.send(new FormData($(form)));
}
How can I get the corresponding PHP script to export a String? I would need something that puts $myExportString as parameter inside after() then I could use it like this:
xhr("../session/searchquery.php", "searchfilterterms", function( myExportString ) {
document.getElementById("someDiv").innerHTML = myExportString;
});
How can this be done?
There's no need to save a file on the server. You can just return the generated HTML string in the response to your XmlHttpRequest, and then write some Javascript to put that HTML into your page.
Otherwise a) you've got the overhead of disk I/O, and b) you're having to make 2 requests to the server (one to generate the HTML, and another to retrieve the file it's been saved to). This is not efficient at all.
In the PHP, instead of saving the generated HTML string to the disk, you can echo it, e.g. something like
echo $finalVariableWithHTMLString;
(I don't know your exact code as it's not shown in the question). If you echo it, then it becomes the contents of the response to the AJAX call. That's how you return a response to a HTTP request in PHP - you echo stuff to the output.
You can then get it from the xhr.responseText variable in the JavaScript. So you'd be able to write
after(xhr.responseText);
in your example, to pass the HTML to your after() function.

how to get a html page as response in xmlhttprequest

var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
alert(this.responseText);
}
};
xhttp.open("GET", "https://zbapi.herokuapp.com/", true);
xhttp.setRequestHeader("Content-type", "application/json");
xhttp.send();
This is my code. It is returning html text but i want it to load html output.
It is returning html text but i want it to load html output.
alert expects to be passed plain text.
You need to put the HTML source code somewhere which expects HTML source code.
For example, the innerHTML of an Element object.
The URL you are requesting, however, includes relative URLs and has its own JS. It doesn't make much sense to request it with JS and then try to render it. You would also certainly be better off just triggering navigation with location = "https://zbapi.herokuapp.com/".
You need to parsing HTML page to JSON with some parser on the server and send parsed data to the client in JSON format. For example, Himalaya (in Node.js).
Official repository of Himalaya
or use html2json (NPM Repository) to parse on client

How to create file object from server file using Javascript

I have one html which display data in table format by reading XLS file.This page giving two option to user. first is to ask user to upload xls file and second is to user already uploaded files by other users.
for first option (user upload file)
I am using JavaScript to fetch file data and convert it into html data.
beginFileHandling(e) {
let file = (e.target.files || e.dataTransfer.files)[0]
convertTodata(file) //this function has logic of reading file and convert it to data array for presentation in HTML
}
but for the second option (user can choose server files)
I need to have file object to make it work by upper method convertTodata(file). How can I achieve it using JavaScript or nodejs.
suppose I have file on server at following path 'docs/Test-files/employee.xls'
I am using xmlhttp to grab that file but how can I write it to JavaScript file object to use same method convertTodata(file).
var result = null;
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", 'docs/Test-files/employee.xls', false);
xmlhttp.send();
if (xmlhttp.status == 200) {
result = xmlhttp.responseText;
}

Javascript, read file in folder

I have a large file format "json". I need to use this information when you open the page in a browser. the only solution - is to place the data into a variable in the ".js" file, but it turns out 5000 lines. Maybe there is an option to read data? I open the page in folder
The JSON.parse() method parses a JSON string, constructing the
JavaScript value or object described by the string.
-MDN
If you need those objects to render out your webpage / webapp you're going to have to get them to the browser. Break up the JSON. Don't forget to minify.
I think the desired architecture would be to use XHR or filesystem (if that's really your use case / local only) to grab what JSON you need on demand.
If you want to have the data directly, you have to put it in a .js file like you did. You could write a build rule to create this .js file from the .json file.
Another solution is using Ajax, which will allow from the js to fetch the content of the .json and store it into a variable.
You can use <link> element with rel attribute set to "import", get and pass link.import.body.textContent to JSON.parse() to create javascript object from JSON.
<script>
let json;
function handleJSON(link) {
json = JSON.parse(link.import.body.textContent);
}
window.onload = function() {
console.log(json)
}
</script>
<link id="json" rel="import" type="application/json" href="https://gist.githubusercontent.com/guest271314/ffac94353ab16f42160e/raw/aaee70a3e351f6c7bc00178eabb5970a02df87e9/states.json" onload="handleJSON(this)"/>
//basic method !! think about handling the exceptions...
if (window.XMLHttpRequest) { // Objet standard
xhr = new XMLHttpRequest(); // Firefox, Safari, ...
} else if (window.ActiveXObject) { // Internet Explorer
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
// Ajax req
xhr.onreadystatechange = function () {
// if ok 200
if (this.readyState == 4 && this.status == 200) {
data = this.response
// your data
console.log(data[0].title);
}
}
xhr.open("GET", "resc/placeholder.json", true)
xhr.responseType = "json"
xhr.send(/*prams if needed */)

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.

Categories