I've found a mound of questions on SO regarding uploading a file using AJAX although none of them really seem to find my needs.
What I need to do is have a user upload an XML file and have the script run through the XML file and take out the data that is in certain tags in the file and then push the data into a corresponding array which reflects the tag. So say I found a book in an xml, it would push the data into an array NewBooks.
I don't have any experience with PHP, quite honestly its confusing to me. If there is a way without PHP, that would be grand.
reader.onload = function (e) {
console.log('reading file')
$(document).ready(function () {
console.log('analyzing ajax')
$.ajax({
type: "GET",
dataType: "xml",
success: function (xml) {
$(xml).find('book').each(function () {
UploadBooks.push($(this).text());
});
}
})
})
console.log(UploadBooks);
}
That is the code I have although the printed UploadBooks has no elements, even though when I look into the XML file, there are clearly book tags.
Not all browsers can upload files via Ajax. Only those supporting XMLHttpRequest2. Getting that to work with jQuery (as per your example) is going to take some tricks too.
You say you'd rather not use PHP, which would mean no point uploading a file anyway. Check out the HTML5 FileReader API if you want to try and parse the XML file on the client side. You might be able to load the file into a DOM structure to achieve what you're trying to do.
Related
I need to write to the file system of my web application. Please don't respond "you can't do that" because it isn't helpful. I see that it can be done with HTML5, php, python, etc. I am just doing 1 basic write. The written file is crawled by a search engine, which is why I have this weird requirement.
To perform the file read I do something like this:
$.ajax({
type: "POST",
url: "./engine-text.txt",
dataType: "text",
async: false,
success: function (data) {
text_data = data;
}
});
I'd like to do something simple to write. I'm just adding or removing lines of text to this file and writing it back. As it stands I don't have php or python. I basically have JQuery, HTML5, and Ruby. Remember another program needs to be able to read this file, so I don't think HTML5 will work.
Thanks!
Generally you can't in your browser due to security concerns.
However it doesn't mean you can't get your browser to make your server to do it -> eg Server Side JavaScript Node.js.
eg using Filesystem
var fs = require('fs');
fs.writeFile("yourpath", "Hello", function(err) {
if(err) {
console.log(err);
} else {
console.log("The file was saved!");
}
});
Some browsers do now allow File system access through the File Api:
https://developer.mozilla.org/en-US/docs/Web/API/File_and_Directory_Entries_API
see this link for a more detailed answer:
Local file access with javascript
I have a complex table generated via javascript that I'd like to save as PDF on the server. I've looked around at the pdf generation libraries and they all seem to be limited in terms of style, fonts, etc (that's what I meant by 'complex'). The table can be download client side as PDF or printed.
Let's say my function that generates the form to be printed is reportBody(data); - is there a way I can use AJAX to send the document as PDF to a php file that will save it server-side instead of downloading it client-side? The reportBody(data) is a collection of other variables, function calls etc.
So basically the question is - since we can generate a PDF file client-side, can we POST it (the pdf) via ajax to the server?
Short answer is Yes. Your provided information is still limited as it's not clear what is ran in the reporBody(data) but most PDF libraries on client side are able to give you the PDF file as base64 encoded data in form of a string.
You can then simply send that string to the server and save that as a PDF file.
A simple implementation will be something like this:
// I have used jQuery for convenience but you can use any lib or Vanilla JS
var saveData = $.ajax({
type: 'POST',
url: "url-to-the-php-script",
data: { pdfData: 'base64StringDataHere'},
dataType: "JSON",
success: function(resultData) { alert("Save Complete") }
});
Then on server side, do something like this:
$pdfData= $_POST['pdfData'];
file_put_contents('filename.pdf', base64_decode($pdfData));
Yes, there are a lot of ways. One would be, if you have html code in your reportBody(data); you could:
Send the html to a php file via ajax
in this php you could use https://wkhtmltopdf.org/ to generate a pdf file
In the client side you could point to that pdf generated
Ok, so the following is what I want to achieve:
I want to use jquery to load a file inside my javascript file.
Normaly you can do a $.ajax request with a POST to a .php file. And select something in a database that looks like the POST I sended with. Now I want the same thing, but instead using a .php file, I will use a .js file.
This also works, the code loads the file with the text alert('Hello World!'); and shows the alert. All fine. But what I want when I load that .js file, it needs to send a value with it. So it could be alert(data); and it will say hello world. How can i achieve this without using cookies or something else that stores values.
EDIT: this a GET request, a POST request is not allowed. Unless you're using GET variables to rewrite your javascript file before returning it you can't modify it or make it do anything other than what would happen if you just requested it with the <script> tag with the async attribute. /edit
Well I just learned something new. You can get a javascript file with an ajax call and execute it using eval but I'm almost 100% certain this is not how you should be doing whatever you're trying to do (also - when is JavaScript's eval() not evil)
$.ajax({
url: '/path/to/script',
type: 'GET',
success: function (response) {
eval(response.toString());
};
});
You're calling the server, which then returns the javascript file and you're parsing it as javascript using eval. I never considered doing this but I supposed it's one way to load a javascript file on demand.
I develop a javascript application which display data from xml with charts and lists.
For now I put some sample files onto the server's directory that I load with :
$.ajax({ type: 'GET', url: 'data/default.xml', dataType: 'xml', ...})
The Xml files can be very heavy so when one of them is loaded I put the data in an IndexedDB.
In a second time I would like to let the visitor loads its own xml file by giving the filepath of the xml (f.i. : /home/user/sample.xml). I do not want to upload this file onto the server because I do not need it and it could be too big. But I do want to load those data in the IndexedDB and let the app displays data without any call to the server.
I do not know if browsers could work this way?
If they could, how can I do such a trick?
You can't use Ajax to get data from a file on the client system, but in sufficiently modern browsers you can use the File API. MDN has a guide to the File API that is friendlier then the specification.
I am new to HTML/Javascript, as well as coding in general so bear with me :). I am trying to create a "Spot the Difference" game in html5 using javascript. Everything is local (on my machine). I have two pictures, of the same size, one with differences. To generate data about the clickable fields, I have a java program that reads both of the images and outputs all of the positions in which pixels are different into a XML file. My plan was to then use this XML file with my javascript to define where the user could click. However, it appears (correct me if I'm wrong) that javascript cannot read local XML files for security reasons. I do not want to use an ActiveXObject because I plan on putting this onto mobile devices via phone gap or a webkit object. Does anyone have a better approach to this problem, or perhaps a way to read local XML files via javascript? Any help would be greatly appreciated, thanks.
If you are planning to put this into a smart phones (iOS and Android) and read local files, I have done similar things with JSON (yes, please don't use XML).
Convert your output to JSON
Put this as part of your application package. For example, in Android, I put it as part of the .apk in /appFiles/json
Create a custom content provider that would read the local file. I create mine as content:// but you create whatever scheme you want. You could leverage android.content.ContentProvider in order to achieve custom URL Scheme. iOS has its own way to create custom scheme as well. The implementation simply read your local storage and give the content
To read it from Javascript, I simply call ajax with the custom scheme to get the json file. For example content://myfile/theFile.json simply redirect me to particular directory in local storage with /myfile/theFile.json appended to it
Below is the sample to override openFile() in the ContentProvider
public ParcelFileDescriptor openFile (Uri uri, String mode) {
try {
Context c = getContext();
File cacheDir = c.getCacheDir();
String uriString = uri.toString();
String htmlFile = uriString.replaceAll(CUSTOM_CONTENT_URI, "");
// Translate the uri into pointer in the cache
File htmlResource = new File(cacheDir.toString() + File.separator + htmlFile);
File parentDir = htmlResource.getParentFile();
if(!parentDir.exists()) {
parentDir.mkdirs();
}
// get the file from one of the resources within the local storage
InputStream in = WebViewContentProvider.class.getResourceAsStream(htmlFile);
// copy the local storage to a cache file
copy(in, new FileOutputStream(htmlResource));
return ParcelFileDescriptor.open(htmlResource, ParcelFileDescriptor.MODE_READ_WRITE);
} catch(Exception e) {
throw new RuntimeException(e);
}
}
I hope it helps
I would suggest modifying your java program to output a JSON formatted file instead of XML. JSON is native to JavaScript and will be much simpler for you to load.
As for actually loading the data, i'm not sure what the best option is as you say you want to evenutally run this on a mobile device. If you were just making a normal website you could setup a web server using either Apache or IIS depending on your OS and put the files in the document root. Once you've done that you can load the JSON file via Ajax, which can easily be googled for.
Not sure if this helps any.
Since this is a local file, you can do this with jQuery
$.ajax({
type: "GET",
url: "your.xml",
dataType: "xml",
success: function(xml){
///do your thing
}
});
http://api.jquery.com/jQuery.ajax/