I want to upload files using javascript/jquery/ajax and in my case, I have to prevent the reload on form submitting on upload.
Also, I want to add a delete button, such that, when file is uploaded, the delete button can delete this and same is the scenario, that to prevent the page refresh/reload on form submitting.
Hence, I've three buttons in a single form, UPLOAD, DELETE, NEXT and in my case, only next allows to submit the form by refreshing/action of form. And obviously, when file is just selected and the user directly hits the next button, it first uploads and then take his action.
HTML:
<form name="myform" method="post" id="FORM2" enctype="multipart/form-data">
// OTHER VALUES OF FORM
<input type="file" name="FileUpload-1" id="FileUpload-1" class="file_upload" />
<input type="submit" value="Upload" id="upload" class="submitUpload" />
<input type="submit" value="Delete" id="delete" class="submitDelete" />
<input type="submit" name="" id="FORMSUBMIT">
</form>
JS:
$(".submitUpload").click(function(){ console.log('UPLOAD');
action = "upload.php";
$("#FORM").on('submit',function(){
var options={
url : action,
success : onsuccess
};
$(this).ajaxSubmit(options);
return false;
});
}
return false;
});
$(".submitDelete").click(function(){ console.log('DELETE');
return false;
});
$('.FORMSUBMIT').click(function () {
//CUSTOM HANDLING
});
To Directly answer your question:
$("#FORM").on('submit',function(evt){
evt.preventDefault();
});
This piece of code will prevent the normal form submitting.
My advice is to transform the Update and Delete buttons from type=submit to type=button. Like this:
<input type="button" value="Delete" id="Delete" class="submitDelete" />
This will prevent the form to be submitted when delete or update are pressed...
I wrote a jsfiddle for you:
https://jsfiddle.net/yL35bh10/
I recently prototyped a page needing image file upload. I found a package on GitHub that was easy to use and should provide the majority of the functionality you're needing.
https://github.com/blueimp/jQuery-File-Upload
My only question to you: Once a file is uploaded to the server, how are you going to know what to delete?
Related
I have a form which has a cancel button, a save (submit) button and a save continue link. Now the buttons work and the javascript is called via a function called from the form onsubmit method. This works as expected as does the cancel button. however the save and continue is not working. Follows is a simplified example:
<form id="save-form" class="admin-form" method="post" action="save-job" onsubmit="return jobFormSave(this);">
<input type="text" name="data" value="">
← cancel
<input class="button" type="submit" value="save">
<a class="button oklink" onclick="document.getElementById('save-form').submit();">ok →</a>
</form>
And the javascript for simplification just alerts ok (the real example has an ajax call to the save-job action):
<script>
window.jobFormSave = function (aForm) {
alert( "Ok" );
}
</script>
So when i click Save button the form is validated, saved and a message is displayed. Clicking on the Ok link however triggers the form submit action (save-job) but i want it to use the jobFormSave function. So I've a few questions:
can this be done while submitting the form data to the function?
can i determine whether i clicked the ok or the save button from within the javascript (or if not within the save-job action function)?
Is there a better way to achieve what seems an everyday thing.
I'm using php 7.2 to handle the forms action functionality and jQuery is available and used for the ajax query in the actual code.
I've kept the code short as mostly it is not relevent to the question but I can provide more code if you guys need it.
Probably you are looking for:
<script>
window.jobFormSave = function (aForm, action) {
alert('User '+ action + " form with data "+ JSON.stringify(aForm))
if (action == 'okayed')
aForm.submit();
}
</script>
<form id="save-form" class="admin-form" method="post" action="save-job" onsubmit="return jobFormSave(this, 'submitted');">
<input type="text" name="data" value="">
← cancel
<input class="button" type="submit" value="save">
<a class="button oklink" href="javascript:{}" onclick="return jobFormSave(document.getElementById('save-form'), 'okayed');">ok →</a>
</form>
Form can be passed as an argument as I did in anchor tag's onclick and then it can be decided to submit at function level based on the action
I am trying to implement upload file , I want to call the file input to select the file first, after selected the file , then will do form submit. However in my code , it will call form submit immediately. I have tried use ajax but not work. Any way I want to do the form submit just after the user have selected the file. But it seems cannot find a way to wait the finishing of the file input click function ( I mean until the user have selected a file)
Here is my html:
<input type="text" id="body" name="body" >
<button type="submit" id="sent_1" value="Send">Submit</button>
<input type="file" id="image_file" name="image" size="chars">
<button id="send_img_btn" value="image">Image</button></td>
Here is my javascript:
$('#send_img_btn').click(function(e){
e.preventDefault();
$('#image_file').click();
$('#form').submit();
});
function imageClick(){
$('#image_file').click();
}
function submit(){
$('#form').submit();
}
Edited: Maybe I am not clearly saying my problem. The problem is that when
I click the button, it just submit the form instantly, not waiting me for selected file. I want it to wait me until I selected the file then submit.
Add attribute type="button" in <button> tag.
By default, <button> tag acts like <input type="submit"> inside <form> tag.
<button type="button" id="send_img_btn">Image</button>
If you want to submit the form as soon as the file is selected, use change event of that input.
<form action="formActionUrl" name="myForm">
<input type="file" name="myInput"/>
</form>
In Script
$(":file").change(function(e){
$("[name=myForm]").trigger('submit');
});
I have a form that has a "preview" submit input, which submits the same form as the others, but with a "visualize" parameter which has to open a new window (in order to keep the form in its temporary state). If I was designing for shiny-clean HTML5 browsers, I could do this nicely using the new formTarget attribute:
<form id="myForm" action="somecontroller/action">
<input type="text" name="someValue" />
<input type="submit" id="visualize" value="Visualize" name="visualize" formTarget="_blank" />
<input type="submit" value="Submit" name="submit" />
</form>
Sadly, the main userbase of this product is using IE8 still (it's an internal network) so this website has to handle IE8 only. I have yet to find a way to make this simple thing work in javascript.
I found this very nice answer and tried to apply it, it doesn't work in my case since I guess it does not submit the form with a "visualize" parameter, so my action does not process it as a preview. So I asked jQuery to click the right button instead of submitting the form:
$('#visualize').click(function(e) {
if (!$('#myForm').prop('target')) {
e.preventDefault(); //prevents the default submit action
$('#myForm').prop('target', '_blank');
$('#visualize').click();
}
else {
$('#myForm').prop('target', null);
}
});
This still does not work. It just submits the form in the same window.
Alright, I finally worked this out, so here's a (dirty but working) solution:
$('#visualize').click(function(e) {
e.preventDefault(); //prevents the default submit action
var $form = $(this).closest('form');
$('<input />').attr('type', 'hidden')
.attr('name', "visualize")
.attr('id', "visualizeTemp")
.attr('value', "1")
.appendTo($form);
$form.prop('target', '_blank').submit().prop('target', '_self');
$('#visualizeTemp').remove();
});
Basically I create an entire temporary hidden input named just like my button (visualize) and submit the form. Then, I just remove my temporary input.
As a side note, I also stumbled upon this issue when calling $form.submit() so I had to rename my submitting button:
<form id="myForm" action="somecontroller/action">
<input type="text" name="someValue" />
<input type="submit" id="visualize" value="Visualize" name="visualize" formTarget="_blank" />
<input type="submit" value="Submit" name="save" />
</form>
I am trying to initiate upload of a file as soon as the user selects the file. The form should disappear replaced by the "Uploading your picture..." message.
So far, all I get is the form being hidden (and message showing), but the upload is not happening. The form is not being submitted. Any ideas why?
This is the JS
<script>
$(function(){
$("#file_select").change(function(){
$(this).parents("#upload_form").submit();
$("#upload_form_div").hide();
$("#loading").show();
});
});
</script>
and the HTML
<div class="float_left" id="upload_form_div">
<h3>Select a picture for your profile (4 MB max):</h3>
<form action="http://example.com/profile/upload_picture"
id="upload_form"
enctype="multipart/form-data"
method="post" accept-charset="utf-8">
<input type="file" name="userfile"
id="file_select" />
<input type="hidden" name="upload" value="upload" />
<button id="submit" type="submit"><img height="24" width="24"
alt="Upload" src="images/icons/small/white/bended%20arrow%20right.png">
<span>Upload</span>
</button>
</form>
<form action="http://example.com/profile/remove_picture"
method="post" accept-charset="utf-8">
<button type="submit"><img height="24" width="24"
alt="Remove" src="images/icons/small/white/trashcan.png">
<span>Remove</span>
</button>
</form>
</div>
<div id="loading" style="display:none;">
Uploading your picture...
</div>
It probably has something to do with this part:
<input type="file" name="userfile"
value="onchange="return validateFileExtension(this)""
id="file_select" />
An input type=file should not have a value= attribute (and even if it did, you shouldn't put javascript in there!)
You also have some javascript in the form:
onsubmit="return validateFileExtension(this.userfile)"
If the function validateFileExtension() returns false then the form will not submit.
However, the way you have written the jQuery means that the message will still appear.
EDIT:
Change the id on your submit button to something other than "submit".
In the jQuery docs:
Forms and their child elements should not use input names or ids that conflict with properties of a form, such as submit, length, or method. Name conflicts can cause confusing failures. For a complete list of rules and to check your markup for these problems, see DOMLint.
HOWEVER:
You should consider #Abdul's solution, since the working submit will take you away from your message.
If you are using CodeIgniter and you don't want to use Ajax, you should consider using the flash functionality to display the message to the user after the form submits.
You should think of using jquery form plugin to submit your form and jquery validate plugin to validate your form for file extensions and everything.Jquery form plugin submits your form using ajax. In that way you won't be redirected to form action. Also
if you want you can consider using jquery dialog to display the result.
$("#upload_form").validate({
rules: {
MyFile: {
required: false,
accept: "jpg|jpeg|png|gif"
}
}
});
$("#file_select").change(function(){
("#upload_form").ajaxSubmit();
$("#upload_form_div").hide();
$("#loading").show();
});
Submit form on file selection and validate for CSV file input
$('#file').change($('form').submit());
$('form').submit(function(){
if($('#file').val().toLowerCase().indexOf('.csv') != -1){
$('#spinner').show();
return true;
}
else{
alert('Invalid File format. Please, upload CSV file')
return false;
}
});
There is a way to automatically submit a form without clicking to a "submit" button?
I have a form with one "file" input. I would submit the form after the user have selected one file.
yes, you can use the form.submit() function. Add an onchange listener on the file input and link it to the form.submit() function, like so:
<form action="upload.php" method="post" enctype="multipart/form-data">
<input type="file" onchange="this.form.submit()" name="myFile"/>
</form>
Yes, you can add the following to the onchange event of the file input:
<input type='file' .... onchange='this.form.submit();'>
this submits the form right after the user has picked a file.
However, the user can't correct a mistaken selection before submitting - be sure to check whether this is really wise.
This solution works for me.
<form enctype="multipart/form-data" method="POST" action="/upload">
<input id="myfilefield" type="file" name="file">
<input type="submit">
</form>
document.getElementById('myfilefield').onchange = function() {
this.form.submit();
};
By the way, you don't need to use flash. Gmail do it by XHR Level 2.
I don't believe you can do this. Browsers are very, very strict about what you can do to file upload fields, because of the potential for abuse. If the user accidentally selects a private file, they wouldn't want it to immediately start uploading that file to a random server.
I'm not sure what the restrictions are with doing this in an HTML form.
You can, however, do it with Flash. Gmail does it - when I click "Attach a file", I get prompted with a file browse dialog, and when I OK that dialog the upload begins immediately, and also gives me a progress bar.
Googling for "Flash uploader" will give you many options, but I don't have experience with any of them.
The solutions that were here to add an event listener in the input didn't work for me, so I found another solution, and I wanted to share it.
HTML:
<form id="attachUpload" method="POST" action="javascript:void(0)" accept-charset="utf-8" enctype="multipart/form-data">
<input id="uploadAttachment" type="file" name="files[]" placeholder="Computer" multiple />
</form>
The code to submit the form:
$(document).on('change', '#uploadAttachment', function() {
$('#attachUpload').trigger('submit');
});
And than if you want to post that data after the form is submitted:
$(document).on('submit', '#attachUpload', function(e) {
// code here
})