Alasql import from upload button vs file onchange event - javascript

I am trying to figure out how to import a file into ALASQL from a file input. There is documentation on how to do this but my client wants to have to press a load button vs when choosing the file.
Here is the documentation from ALASQL:
<script src="xlsx.core.min.js"></script>
<p>Select CSV file to read:</p>
<input id="readfile" type="file" onchange="loadFile(event)"/>
<script>
function loadFile(event) {
alasql('SELECT * FROM FILE(?,{headers:true})',[event],function(data){
// Process data here
});
}
</script>
https://github.com/agershun/alasql/wiki/How%20to%20upload%20form%20for%20txt%20and%20xlsx%20in%20javascript
My client wants something like this:
<script src="xlsx.core.min.js"></script>
<p>Select CSV file to read:</p>
<input id="readfile" type="file"/>
<button onclick="loadfile()">Load</button>
<script>
function loadFile() {
var file=document.getElementById('readfile').files[0]
alasql('SELECT * FROM FILE(?,{headers:true})',[file],function(data){
// Process data here
});
}
</script>
I have tried various methods to achieve this but nothing has worked so far. Some of the methods I have tried include creating custom jQuery events and the above example.
I have found a SF article that asks something similar but was unanswered.
Loading CSV file with AlaSQL and JQuery
Thank you

One answer I came up with is to split the loadfile process into two functions such as this:
<script src="xlsx.core.min.js"></script>
<p>Select CSV file to read:</p>
<input id="readfile" type="file" onchange="loadfile(event)"/>
<button onclick="loadfile2()">Load</button>
<script>
var loadFileTempData=[];
function loadFile() { //load data file into variable
var file=document.getElementById('readfile').files[0]
alasql('SELECT * FROM FILE(?,{headers:true})',[file],function(data){
loadFileTempData=data;
});
}
function loadFile2(){ //process data from variable
var data=loadFileTempData;
loadFileTempData=[];
// Process data here
}
</script>

Related

PHP - Use API That Only Offers HTML + JS With PHP Script

I have a conversion (HTML2PNG) I need to automate in a PHP script using a REST API. However, the only example provided on the website was via HTML and JavaScript where one can only upload the HTML file to be converted in a form.
My PHP script already generates HTML files in a loop, thus, I'd like to simply pass these generated HTML files to the API which then returns the download URL of the converted PNG file which I know I can use wget to retrieve. This is the code as offered by the service.
<form action="#" method="post" enctype="multipart/form-data" name="conversionform" id="conversionform">
<p>Local file: <input id="file" name="file" type="file" /></p>
<p>Target format:
<select name="targetformat" id="targetformat"">
<option value="png">PNG</option>
</select>
</p>
<p><input type="button" value="Convert" onclick="convertpdfform()" /></p>
<p><span id="resulttext">Conversion Results: </span></p>
</form>
<script src="https://www.aconvert.com/js/jquery.min.js"></script>
<script src="https://www.aconvert.com/js/jquery.form.js"></script>
<script type="text/javascript">
$(document).ready(function() {
});
function showResponse(responseText, statusText, xhr, $form) {
resulttext.innerHTML=responseText;
}
function showError(responseText, statusText, xhr, $form) {
}
function convertpdfform() {
options = {
success: showResponse,
error: showError,
url: "https://s2.aconvert.com/convert/api-win.php",
};
$('#conversionform').ajaxForm(options);
$('#conversionform').ajaxSubmit(options);
return false;
}
</script>
What I've Tried
Emailed them to ask for PHP examples and I got 'there are no PHP examples' as response.
I know value="png" is what the API gets to determine the output file.
How can I simply pass the file without using a web browser and still get the download URL of the converted file?
P:S - I'm not only using the site because of html2png, they offer tons of other conversion services.
maybe you can create a file based on the HTML code produced by your PHP script and try to emulate the uploading on the form it self. like how web scraping works but simulating the clicks and upload too.
you can definitely do it by looking at the web request. Use Chrome to see the actual request from beginning to end

Trying to read a local file on page load in HTML

I'm creating a web application that references a local txt (or csv) file which will change every year. I want to be able to load the contents of the file into a <textarea> on page startup.
Right now, I have functional code for loading the contents into a <textarea> by using the <input> element (thanks to a previous StackOverflow question in 2015). The file is selected and an event listener will call a function once the input state gets changed. My challenge is modifying the code so that the file can be hard-coded and loaded on startup and still calling the function using an event (or changing the function to work without an event call).
index.html
<input type="file" id="fileinput" />
<script type="text/javascript" src="dataLoad.js"></script>
<script type="text/javascript">
document.getElementById('fileinput').addEventListener('change', readSingleFile, false);
</script>
<textarea rows=20 id="area"></textarea>
dataLoad.js
function readSingleFile(evt) {
//Retrieve the first (and only!) File from the FileList object
var f = evt.target.files[0];
if (f) {
var r = new FileReader();
r.onload = function(e) {
var display = "";
//a lot of unimportant stuff here
document.getElementById('area').value = display;
}
r.readAsText(f);
} else {
alert("Failed to load file");
}
}
This works fine, but I don't want to manually select the file to load, I want to hard-code the file. The "a lot of unimportant stuff here" parses the data in the file so I left it out for clarity sake.
You cannot due to security reasons.
You don't want the websites you visit to be able to do this, do you?
Try This:
<object width="300" height="300" type="text/plain" data="password.txt" border="0" >
</object
Assuming the <input type="file" /> has autocomplete on (which I believe it does by default), any files that were chosen/dragged onto the element should still be present on page load, so all you would need to do is manually trigger the change event that you added an eventListener for, like so:
<input type="file" id="fileinput" />
<textarea rows=20 id="area"></textarea>
<script>
var fileInput = document.getElementById('fileinput');
var event = new Event('change');
fileInput.addEventListener('change', readSingleFile, false);
fileInput.dispatchEvent(event);
function readSingleFile(evt) {
var f = evt.target.files[0];
if (f) {
alert("Processing file...");
}
}
</script>
This won't work in JSFiddle as it rebuilds the HTML when you refresh the page, however this works offline for me.

How to make a feature to upload image from local?

I want to make a feature on a website from which anyone can upload an image from desktop into a server get a link.
Like used in https://stackoverflow.com where it is uploaded and the link is pasted.
I want the link.
Is there any way to work on it?
You can use Ospry.io - here is a usage example:
<script src="https://code.ospry.io/v1/ospry.js"></script>
<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
<form id="up-form">
<input type="file" multiple />
<button type="submit">Upload image</button>
</form>
<script>
var ospry = new Ospry('YOUR_PUBLIC_KEY');
$('#up-form').submit(function(e) {
e.preventDefault();
ospry.up({
form: this,
imageReady: function(err, metadata, i) {
alert("Find file at: " + metadata.url);
}
});
});
</script>
P.S. - you need to sign up to get your API key.

How do I use ajax to upload a text field and a file?

I'm new at AJAX and am working on an implementation of a form that will upload a name and a file to a php file that processes the data and sends it to a database for insertion using mysqli. I've tested the php file and it does work. My problem is in the AJAX code. I've tried an implementation using XMLHTTP and using jQuery. Both leave the page and open the PHP file in the browser. As a disclamer, I posted this question to another coding site, a fight ensued between two posters, and so I'm trying here to hopefully get a reasoned and calm response with productive suggestions.
I realize that currently "get" is being sent to the PHP file rather than "post", but PHPStorm tells me that "post" is not available in that form. What's my alternative? Am I on the right track or is there another direction I should go? How do I refresh only the form and keep the PHP page from loading?
Here's the relevant snippet of my code,
<!DOCTYPE html>
<html>
<head>
<script src="jquery.min.js"></script>
<script src="jquery.validate.js"></script>
<script>
$(document).ready(function() {
$('#addForm').validate({
submitHandler: function (form) {
$('input[name="usingAJAX"]', this).val('true');
var url = $(form).prop('action');
var dataToSend = $(form).serialize();
var callback = function(dataReceived) {
$(form).hide();
//result message
$('body').append(dataReceived)
};
var typeOfDataToReceive = 'html';
$.get(url, dataToSend, callback, typeOfDataToReceive),
return false;
}
});
});
</script>
</head>
<body>
<form id="addForm" action="addInfo.php" enctype="multipart/form-data">
<input type="hidden" name="usingAJAX" value="false"/>
<label for="aname">Name: </label>
<input type="text" name="aname" id="aname" class=required/>
<label for="aimage">Photo: </label>
<input id="aimage" type="file" name="aimage" class="required">
<input type="submit" value="ADD"/>
</form>
</body>
</html>
Until recently you could not upload files with ajax.
You still cannot upload the file directly with ajax, but you can do it programatically with HTML5 File API.
Still, if you are looking for simple solutions, try traditional IFrame approach.
If you want bleading edge technology, use File API. Here is some tutorial how to read files with javascript.
The steps to upload with ajax:
Read file with javascript FileReader API.
Post the content of the file, encoded to base64 or something, to the server.
Serverside, decode the contents of the file programatically.
When using this approach, the file will not be handled as a file upload by the server. It will be just another request field with text inside. It is up to you to decode it on the server side.
The filereader API allows you to read the file portion by portion and upload fragments of file, so it would be possible to upload huge files in chunks, but you need to handle it yourself.
Try using plugin jQuery form.js http://www.malsup.com/jquery/form/#file-upload You can upload files with ajax and jQuery. It is easy to use, just need to give #form-id in ajaxSubmit function.
<script>
$(document).ready(function() {
$('#addForm').validate({
submitHandler: function (form) {
$('input[name="usingAJAX"]', this).val('true');
var options = {
url : $(form).prop('action'),
dataToSend : $(form).serialize(),
callback : function(dataReceived) {
$(form).hide();
//result message
$('body').append(dataReceived) },
typeOfDataToReceive = 'html';
//your options here
};
$('#yourFormid').ajaxSubmit(options);
return false;
}
});
});
</script>

a jquery plugin to upload a single file 'silently'

In my web app,I need to upload a single file when a user selects that file and stay on the same html page.I am looking for a non-flash solution which probably uses jquery.and something which works on firefox.
By googling,I came across many plugins,most of them using elaborate html pages for showing input widgets / upload status indicators etc.I need something which I can use like this,using ajax.
mypage.html
<input type="file" id="myfileselect" > </input>
myjs.js
$(document).ready(function(){
$('#myfileselect').change(function(e){
//upload the file somehow
}
});
Is this possible?Can someone illustrate how I can do this?
I use this plugin in all my projects. Once the user selects the file, you simply call
$('#yourForm).ajaxSubmit()
and it will asynchronously upload your file.
http://jquery.malsup.com/form/
In your case, you would do it like this:
HTML
<form id="myForm">
<input type="file" id="myfileselect" > </input>
</form>
JQuery
$(document).ready(function(){
//set the options here
var options = {
url : 'yourScript.php',
method : 'post'
};
$('#myfileselect').change(function(e){
$('#myForm').ajaxSubmit(options);
}
});

Categories

Resources