how to remove a file from an input after submit button - javascript

i have a form , there is an input type file , that element has a button with a on click event calling a function to upload the file (image), after that user has filled all his data hit the button validate ,
i want to clear the input type file once the user has clicked upload file and file has been uploaded , because what happening is that file to be uploaded to the server it takes time when the user hit upload file and also when he clicks validate button because it's passing in http request as an element of the form so what i want is to remove the file from the input once it is uploaded , this is my code i tested different scenarios none of them has worked.
<div>
<input type='file' name='img1' id='img1'>
<input type="button" value="upload" onclick="uploadFile()">
<progress id="progressBar" value="0" max="100" style="width:300px;"></progress>
</div>
js
function _(el){
return document.getElementById(el);
}
function uploadFile(){
var file = _("img1").files[0];
var e = document.getElementById("img1");
var formdata = new FormData();
formdata.append("img1", file);
var ajax = new XMLHttpRequest();
ajax.upload.addEventListener("progress", progressHandler, false);
ajax.addEventListener("load", completeHandler, false);
ajax.addEventListener("error", errorHandler, false);
ajax.addEventListener("abort", abortHandler, false);
ajax.open("POST", 'distination');
ajax.send(formdata);
formdata.delete("img1");
formdata = '';
_("img1").files[0] = '';
e.value ='';
$('#img1').val('');
$('#img1')[0].reset();
}
the action of the form is PHP_SELF

I found this by searching StackOverflow for what you are specifically trying to do:
function resetForm($form) {
$form.find('input:file').val('');
}
// to call, use:
resetForm($('#myform'));
This solution was derived entirely from Resetting a multi-stage form with jQuery
Example usage when you submit the form would be:
$('#validateButton').click(function (e) {
e.preventDefault();
resetForm($('#myform'));
$('#myform').submit();
});
Where #validateButton and #myform should be replaced with the actual names of your DOM elements.

Related

$_FILES not receiving input after AJAX with vanilla Javascript

I have a form that passes various types of input to an ajax call, which opens a php script. The script will do various things including processing the file, before echoing an array of variables.
All inputs go through $_POST regularly, and the file data is passed, too, but the file itself is not accessible from $_FILES.
I am not using jQuery, so most posts are hard to translate to my case.
I have seen a similar issue here,https://stackoverflow.com/questions/56878395/files-empty-after-ajax-upload but that solution doesn't seem to apply.
Here are the key excerpts from the code, thank you in advance for any tips!
var ajaxResponse = "";
var qForm = document.getElementById('myForm');
qForm.addEventListener("submit", function(e) {
e.preventDefault();
var formData = new FormData(qForm);
checkForm(formData);
console.log(ajaxResponse); //this shows the $_FILES var_dump
});
function checkForm(formData) {
var vars = "startDate=" + formData.get('startDate') +
"&qInvited=" + formData.get('qInvited');
ajaxRequestReturn("checkForm.php", vars);
}
function ajaxRequestReturn(phpRequest, vars) {
var req = new XMLHttpRequest();
req.open("POST", phpRequest, false); //not asynchronous, because I pass results to a global variable
req.setRequestHeader('Content-type', 'application/x-www-form-urlencoded'); //removing the setRequestHeader doesn't seem to make any difference.
req.onload = function() {
ajaxResponse = this.responseText;
}
req.onerror = function() {
throw new Error("Bad request.");
}
req.send(vars);
// form.submit();
}
<form class="loginForm" id="myForm" method="post" enctype="multipart/form-data" action="thisPage.php">
<div>
<input type="date" id="startDateInput" name="startDate">
</div>
<div>
<input type="file" name="qInvited" required>
</div>
<input type="submit" id="submitBtn">
</form>
and the checkForm.php file is currently simply:
<?php
echo var_dump($_FILES);
?>
the var_dump($_FILES) should show the qInvited file in it, but it prints
array(0) {
}
instead.
To upload a file via ajax you have to pass a FormData object in your call to XMLHttpRequest.send.
Get rid of the checkForm function and call ajaxRequestReturn with formData as the second parameter.
Also, application/x-www-form-urlencoded is not the correct content type(its multipart/form-data), remove that line. The correct content type will be set automatically when you use the FormData object.

AJAX: multiple file upload separately

I'm configuring a multiple file upload with Jquery and Ajax, here the source code.
HTML:
<div id="dropzone-zone">
<button type="submit" class="btn btn-primary btn-xs" id="add_file" name="add_file" form="upload-form" style="display:none;">Subir archivos</button>
<form action="" id="upload-form" method="post" enctype="multipart/form-data">
<div id="dropzone" class="drop-zone" style="display:none;">
<span class="drop-zone__prompt">Haga click o arrastre los archivos que desea subir.</span>
<input type="file" name="file-upload[]" style="display:none;" id="file-upload" class="drop-zone__input" multiple>
</div>
</form>
</div>
JS:
const inputElement = document.getElementById("file-upload");
const dropZoneElement = document.getElementById("dropzone");
dropZoneElement.addEventListener("dragover", (e) => { e.preventDefault(); });
dropZoneElement.addEventListener("drop", (e) => {
e.preventDefault();
inputElement.files = e.dataTransfer.files;
dropZoneElement.querySelector(".drop-zone__prompt").remove();
for(var i=0; i<inputElement.files.length; i++) {
var file = inputElement.files[i];
var formdata = new FormData();
formdata.append("file-upload", file);
var ajax = new XMLHttpRequest();
ajax.upload.addEventListener("progress", function (event){
if(event.lengthComputable){
var percent = (event.loaded / event.total) * 100;
document.getElementById("load-progress").value = Math.round(percent);
}
}, false);
ajax.open("POST", "pruebas.php");
ajax.send(formdata);
}
//document.getElementById('add_file').click();
});
With this code, I want that with more than one file, first proccesses the first file, uploading to the location defined in pruebas.php, and meanwhile, completing the progress bar.
After the first file, starts with the second file, uploading it and completing its bar.
And the third and the fourth, etc; until all have been completed, then the form is being submitted and the redirect is done.
Now it's working, I mean it uploads the files to the server, but I can't proccess the upload progress bar because it doesn't wait for the end of the first upload, and I don't know how can evaluate the end of the upalods to determine when I have to submit the form.
Can someone explain me what do I have to change, or some post related?
Thanks in advance.
XMLHttpRequest.open() is asnychronous by default. This means, that the Request is sent and the code is not halted. You can set the property in .open(METHOD, URL, ASYNC) async to false, therefore the .send() method wont return until the response is recieved. This would cause the for-loop to wait for the Upload to finish.
I've edited your code below, I simply added another parameter to .open() which determines of the Method should be executed asynchronously.
const inputElement = document.getElementById("file-upload");
const dropZoneElement = document.getElementById("dropzone");
dropZoneElement.addEventListener("dragover", (e) => { e.preventDefault(); });
dropZoneElement.addEventListener("drop", (e) => {
e.preventDefault();
inputElement.files = e.dataTransfer.files;
dropZoneElement.querySelector(".drop-zone__prompt").remove();
for(var i=0; i<inputElement.files.length; i++) {
var file = inputElement.files[i];
var formdata = new FormData();
formdata.append("file-upload", file);
var ajax = new XMLHttpRequest();
ajax.upload.addEventListener("progress", function (event){
if(event.lengthComputable){
var percent = (event.loaded / event.total) * 100;
document.getElementById("load-progress").value = Math.round(percent);
}
}, false);
// Changed the parameter for 'async' to false
ajax.open("POST", "pruebas.php", false);
ajax.send(formdata);
}
//document.getElementById('add_file').click();
});

Submit a form obtained via XMLHttpRequest?

I am trying to a download a html page via javascript, parse it and submit the form with the following code. Everything seems to work perfectly in this function, yet I am unable to see the desired server side changes. Could someone point me if there's something wrong in this approach ?
function get_page(url){
var xhr = new XMLHttpRequest();
xhr.responseType = "document"; //parse html
xhr.open("GET", url);
xhr.send(null);
xhr.onload = function(){
// get form here
var dom = xhr.responseXML;
var form = dom.forms[0];
// set values in fields
form[0].value='hello';
form[1].value=form[0].value;
//change action from # to url
form.action = url;
//EDIT: attach form to body
document.getElementsByTagName('body')[0].appendChild(form);
//form submit
form.submit();
//print form last value
console.log(form[3].value);
}
}

show loading percentage text in php

I'm new here and I'm sorry if i have posted this in the wrong place or anything.
What i want to implement is a text which displays percentage from 1%-100% which shows how much a file has been uploaded.
Right now, It shows just "Loading.." Instead of uploading..
I'm using PHP and JS in the website. Here is the script for the "Loading" button.
echo "<form id=\"uploads\" action=\"\" method=\"post\" enctype=\"multipart/form-data\"><input type=\"hidden\" value=\"myForm\" name=\"$upload_name\">
<center><input type=\"file\" value=\"Upload\" name=\"upload_file[]\" class=\"file\" multiple class=\"button2\"/> <br><br><input type=\"button\" id=\"upload\" class=\"button2\" value=\"Upload\" onclick=\"document.getElementById('upload').disabled = 'disabled'; document.getElementById('upload').value = 'Loading...'; document.getElementById('uploads').submit();\"><br><br></center>
</form></center>
";
How can i implement this? Please direct me to the path where i can implement this feature.
So a "without library" solution. Provide the URL of your server upload handler, select your file and click on upload. You should see the progression as a percentage.
document.querySelector("#upload").addEventListener("click",function(){
var oReq = new XMLHttpRequest();
oReq.addEventListener("progress", updateProgress, false);
oReq.addEventListener("load", transferComplete, false);
oReq.addEventListener("error", transferFailed, false);
oReq.addEventListener("abort", transferCanceled, false);
var upload_to_URL= document.querySelector("#upload_to").value;
oReq.open('POST', upload_to_URL , true);
var formData = new FormData();
formData.append("upload", file.files[0]);
oReq.send(formData);
});
// progress on transfers from the server to the client (downloads)
function updateProgress (oEvent) {
if (oEvent.lengthComputable) {
var percentComplete = oEvent.loaded / oEvent.total;
// ...
document.querySelector("#upload-progress").innerHTML= (percentComplete * 100 ) + "%"
} else {
// Unable to compute progress information since the total size is unknown
}
}
function transferComplete(evt) {
document.querySelector("#upload-progress").innerHTML= " <span style='color:green'>100%</span>";
}
function transferFailed(evt) {
alert("An error occurred while transferring the file.");
}
function transferCanceled(evt) {
alert("The transfer has been canceled by the user.");
}
<form id="upload-form">
<input type="text" id="upload_to" placeholder="Upload handler URL"/><br />
<input type="file" id="file"/>
<input type="submit" value="upload" id="upload" />
</form>
<div id="upload-progress"></div>

XMLHttpRequest to Post HTML Form

Current Setup
I have an HTML form like so.
<form id="demo-form" action="post-handler.php" method="POST">
<input type="text" name="name" value="previousValue"/>
<button type="submit" name="action" value="dosomething">Update</button>
</form>
I may have many of these forms on a page.
My Question
How do I submit this form asynchronously and not get redirected or refresh the page? I know how to use XMLHttpRequest. The issue I have is retrieving the data from the HTML in javascript to then put into a post request string. Here is the method I'm currently using for my zXMLHttpRequest`'s.
function getHttpRequest() {
var xmlhttp;
if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
} else {// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
return xmlhttp;
}
function demoRequest() {
var request = getHttpRequest();
request.onreadystatechange=function() {
if (request.readyState == 4 && request.status == 200) {
console.log("Response Received");
}
}
request.open("POST","post-handler.php",true);
request.setRequestHeader("Content-type","application/x-www-form-urlencoded");
request.send("action=dosomething");
}
So for example, say the javascript method demoRequest() was called when the form's submit button was clicked, how do I access the form's values from this method to then add it to the XMLHttpRequest?
EDIT
Trying to implement a solution from an answer below I have modified my form like so.
<form id="demo-form">
<input type="text" name="name" value="previousValue"/>
<button type="submit" name="action" value="dosomething" onClick="demoRequest()">Update</button>
</form>
However, on clicking the button, it's still trying to redirect me (to where I'm unsure) and my method isn't called?
Button Event Listener
document.getElementById('updateBtn').addEventListener('click', function (evt) {
evt.preventDefault();
// Do something
updateProperties();
return false;
});
The POST string format is the following:
name=value&name2=value2&name3=value3
So you have to grab all names, their values and put them into that format.
You can either iterate all input elements or get specific ones by calling document.getElementById().
Warning: You have to use encodeURIComponent() for all names and especially for the values so that possible & contained in the strings do not break the format.
Example:
var input = document.getElementById("my-input-id");
var inputData = encodeURIComponent(input.value);
request.send("action=dosomething&" + input.name + "=" + inputData);
Another far simpler option would be to use FormData objects. Such an object can hold name and value pairs.
Luckily, we can construct a FormData object from an existing form and we can send it it directly to XMLHttpRequest's method send():
var formData = new FormData( document.getElementById("my-form-id") );
xhr.send(formData);
The ComFreek's answer is correct but a complete example is missing.
Therefore I have wrote an extremely simplified working snippet:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="X-UA-Compatible" content="IE=Edge, chrome=1"/>
<script>
"use strict";
function submitForm(oFormElement)
{
var xhr = new XMLHttpRequest();
xhr.onload = function(){ alert(xhr.responseText); }
xhr.open(oFormElement.method, oFormElement.getAttribute("action"));
xhr.send(new FormData(oFormElement));
return false;
}
</script>
</head>
<body>
<form method="POST"
action="post-handler.php"
onsubmit="return submitForm(this);" >
<input type="text" value="previousValue" name="name"/>
<input type="submit" value="Update"/>
</form>
</body>
</html>
This snippet is basic and cannot use GET. I have been inspired from the excellent Mozilla Documentation. Have a deeper read of this MDN documentation to do more. See also this answer using formAction.
By the way I have used the following code to submit form in ajax request.
$('form[id=demo-form]').submit(function (event) {
if (request) {
request.abort();
}
// setup some local variables
var $form = $(this);
// let's select and cache all the fields
var $inputs = $form.find("input, select, button, textarea");
// serialize the data in the form
var serializedData = $form.serialize();
// fire off the request to specific url
var request = $.ajax({
url : "URL TO POST FORM",
type: "post",
data: serializedData
});
// callback handler that will be called on success
request.done(function (response, textStatus, jqXHR){
});
// callback handler that will be called on failure
request.fail(function (jqXHR, textStatus, errorThrown){
});
// callback handler that will be called regardless
// if the request failed or succeeded
request.always(function () {
// reenable the inputs
});
// prevent default posting of form
event.preventDefault();
});
With pure Javascript, you just want something like:
var val = document.getElementById("inputFieldID").value;
You want to compose a data object that has key-value pairs, kind of like
name=John&lastName=Smith&age=3
Then send it with request.send("name=John&lastName=Smith&age=3");
I have had this problem too, I think.
I have a input element with a button. The onclick method of the button uses XMLHTTPRequest to POST a request to the server, all coded in the JavaScript.
When I wrapped the input and the button in a form the form's action property was used. The button was not type=submit which form my reading of HTML standard (https://html.spec.whatwg.org/#attributes-for-form-submission) it should be.
But I solved it by overriding the form.onsubmit method like so:
form.onsubmit = function(E){return false;}
I was using FireFox developer edition and chromium 38.0.2125.111 Ubuntu 14.04 (290379) (64-bit).
function postt(){
var http = new XMLHttpRequest();
var y = document.getElementById("user").value;
var z = document.getElementById("pass").value;
var postdata= "username=y&password=z"; //Probably need the escape method for values here, like you did
http.open("POST", "chat.php", true);
//Send the proper header information along with the request
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.setRequestHeader("Content-length", postdata.length);
http.onreadystatechange = function() {//Call a function when the state changes.
if(http.readyState == 4 && http.status == 200) {
alert(http.responseText);
}
}
http.send(postdata);
}
how can I post the values of y and z here from the form

Categories