I have a form where you have to add an image, either by adding a link or uploading an image. When you load the page there is an input text for the url, and there is a button I scripted to change the HTML of the input text to the input file one.
That works well, but the problem comes when submitting the form, the $_FILE array of that dynamic upload input doesn't exist.
This is the javascript code to swap the input:
function SwapImageMode()
{
if(imageMode == 0)
{
imageMode = 1;
$("#f_imagearea").html("<input type='file' name='addon_imgupld' id='f_upimgimput' name='addon_imgupld' style='margin-bottom:7px;' accept='image/*' onchange='inputFileChange();'/>");
}
else if(imageMode == 1)
{
imageMode = 0;
$("#f_imagearea").html("<input type='text' name='addon_imgurl' class='styled_imput f_imgimput' onFocus=imgUrlImputFocus(); onBlur=imgUrlImputBlur(); />");
}
}
Php code when the form is submitted:
if(isset($_POST["addon_imgurl"]) && !isset($_POST["addon_imgupld"]))
{
$formImgMethod = 1; // link
}
else if(isset($_POST["addon_imgupld"]) && !isset($_POST["addon_imgurl"]))
{
$formImgMethod = 2; // upload
}
if($formImgMethod == 2)
{
echo($_FILES["addon_imgupld"]["name"]);
}
And this is the error of php:
Notice: Undefined index: addon_imgupld in
C:\xampp\htdocs\addexp\agregar\index.php on line 49
The error is pretty straight-forward. You are trying to access an array key that doesn't exist, so you'll need to check for different types of form submissions.
Just write a simple conditional in your PHP form handler:
if( !empty($_FILES["addon_imgupld"]) ){
//file input
} elseif( !empty($_REQUEST["addon_imgurl"]) ) {
//text input
} else {
//error?
}
You'll want to swap $_REQUEST with whatever type of request was made ($_POST, I assume...).
UPDATE::
This conditional is wrong:
else if(isset($_POST["addon_imgupld"]) && !isset($_POST["addon_imgurl"]))
Should be:
else if(isset($_FILES["addon_imgupld"]) && !isset($_POST["addon_imgurl"]))
UPDATE 2::
Did you set your form encoding type to multipart? If not, add this attribute to your form tag:
enctype="multipart/form-data"
Related
I have a python flask webapp and JavaScript front-end. In my front end I am doing all form validations, before submitting it. One such validation is to check the value of a name input field against a list of names(array) I am passing to the template already on GET request. The code below works fine unless it's the last element in the array !!! Then it alerts properly, yet still submits the form. In other words - when rendering the page I am passing the list with all names existing in the database. Then if the same name is provided in the input field, I expect alert and stop execution. In my case, it works fine for all but the last element in the passed array. Then it alerts, yet still submits the form.
My HTML:
function submitServiceForm() {
if ($('#ingested_product_name').val() == '') {
alert("you must specify a product name");
return false;
} else if ($('#ingested_product_features').val() == '') {
alert("you must specify at least one feature");
return false;
} else if ($('#selected_quality_1').val() == null && !$('#no_qualities').is(':checked')) {
alert("you must select at least one Quality");
return false;
} else if ($('#selected_aspect_1').val() == null && !$('#no_qualities').is(':checked')) {
alert("you must select at least one Aspect");
return false;
} else if ($('#ingesting_service').val() == '') {
alert("you must select an ingesting service");
return false;
} else {
let no_qa_check = document.getElementById('no_qualities');
if (no_qa_check.checked) {
let allIngestInPlatform = {
{
allIngestInPlatform | safe
}
};
for (let i = 0; i < allIngestInPlatform.length; i++) {
if ($('#ingested_product_name').val() == allIngestInPlatform[i]['ingested']) {
alert("an Ingested Product with the same name already exists on that platform");
return false;
} else {
document.getElementById('ingested_product_form').submit();
}
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="form-row">
<table class="table">
<tr>
<td>
<button type="button" onclick="return submitServiceForm();" class="btn btn-primary">Add Ingested Product</button>
</td>
</tr>
</table>
</div>
Returning false in a submit button click doesn't do anything. A submit button click has a default action of submitting the form. You would need to specifically return false in the onsubmit event instead:
<form .. onsubmit="return submitServiceForm();">
Nowadays people also often prefer to avoid inline Javascript, so with jQuery, that might look more like this:
// Use a more specific selector than this
$('form').on('submit', function(){
return submitServiceForm();
});
Alternatively if you'd like to keep it in onclick, you can use event.preventDefault() instead.
// use a more specific selector than .btn-primary
$('.btn-primary').click(function(e){
if(!submitServiceForm()){
e.preventDefault();
}
});
Change this line on your code
From
for (let i = 0; i < allIngestInPlatform.length; i++)
To
for (let i = 0; i <= allIngestInPlatform.length; i++)
I'm trying to loop through all file input fields and set an error message if any are over 5MB as a first step to form validation.
I'm using a click event on the submit button. The problem is that "key" is not defined.
This form can have up to 10 file input fields, added via AJAX called images[]
/* loop through all file inputs to check size */
$("#my-form").find("input[type='file']").each(function(key, value) {
var el = this.files[key];
if(el.size > 5242880 || el.fileSize > 5242880) {
errorMessage = 'Files must be less than 5MB.';
}
});
If I use this.files[0] I can get the first field's size, but having trouble looping through all elements. Appreciate your input or other solutions. Thanks much!
You could do this
$("#my-form").find("input[type=file]").each(function(index, field){
const file = field.files[0];
if(file.size > 5242880 || file.fileSize > 5242880) {
errorMessage = 'Files must be less than 5MB.';
}
});
Here is a fiddle: https://jsfiddle.net/kmm67nLz/
For file inputs with multiple attribute
$("#my-form").find("input[type=file]").each(function(index, field){
for(var i=0;i<field.files.length;i++) {
const file = field.files[i];
if(file.size > 5242880 || file.fileSize > 5242880) {
errorMessage = 'Files must be less than 5MB.';
alert(errorMessage);
}
}
});
Here is a fiddle: https://jsfiddle.net/kmm67nLz/1/
The second one is perfect to use in any of single or multiple file input.
This is my file input element:
<input type="file" id="StudentPhoto" value="StudentPhoto" style="display: none;">
This is the validation function:
$(document).ready(function() {
$('#StudentPhoto').change(function()
{
var file_data = $("#StudentPhoto").prop("files")[0];
var size = file_data.size;
var type = file_data.type;
var name = file_data.name;
var input = $("#StudentPhoto");
if(type !== 'image/png' && type !== 'image/jpg' && type !== 'image/jpeg')
{
alert("Only JPG & PNG files are allowed to upload as student photo.");
$('#StudentPhoto').click();
}
else if(size > 2097152)
{
alert("The maximum photo size is 2MB\n");
$('#StudentPhoto').click();
}
});
});
If the file chosen by the user has an invalid format or size, it's supposed to pop up the dialog to ask him to choose the file again, but it doesn't, the statement $('#StudentPhoto').click(); in the function doesn't work. Why? Is there any other method?
Or you can use the .trigger() method to make the click event fire on the button. We'll also use input since you stored the file field already.
input.trigger('click');
Hope this helps.
You can use HTML DOM click() method:
document.getElementById('StudentPhoto').click();
Change your file input element to:
<input type="file" id="StudentPhoto" value="StudentPhoto" style="visibility: hidden">
Note that I used visibility: hidden, instead of display: none.
You cannot call the click event on a non-displayed file input.
you need to insert your callback withing the click event:
$(document).ready(function()
{
$('#StudentPhoto').change(function()
{
var file_data = $("#StudentPhoto").prop("files")[0];
var size = file_data.size;
var type = file_data.type;
var name = file_data.name;
var input = $("#StudentPhoto");
if(type !== 'image/png' && type !== 'image/jpg' && type !== 'image/jpeg')
{
alert("Only JPG & PNG files are allowed to upload as student photo.");
$('#StudentPhoto').click();
}
else if(size > 2097152)
{
$('#StudentPhoto').click(function(){
alert("The maximum photo size is 2MB\n");
});
}
});
});
I have a form called here:
<span class="aligncenter button">Submit</span>
And I have a JavaScript function here:
if (myForm == 'newIncident')
{
var vDemAge = document.forms['newIncident']['demAge'].value;
var vBibNumber = document.forms['newIncident']['bibNumber'].value;
// Run through validations before submitting form
validateTime();
validateDate();
validateAge();
validateGender();
validateLocation();
validateType();
validateDisposition();
if (vDemAge == 'Age' || vDemAge == '') // If Age is not entered, set the value to be blank
{
document.forms['newIncident']['demAge'].value = '';
}
if (vBibNumber == 'Bib #' || vBibNumber == '') // If Bib # is not entered, set the value to blank
{
document.forms['newIncident']['bibNumber'].value = '';
}
document.getElementById(myForm).submit();
}
else
{
document.getElementById(myForm).submit();
}
So I have each of the validations as a separate function that I am calling in sequence when submitting the form. If I comment out the "document.getElementById(myForm).submit();", the validations run as expected. However, if I leave it uncommented, it submits every time even if the validations fail. How can I stop this from happening?
Thanks!
EDIT:
So this is one of the validations I'm running. They're all structured the same way. Somewhere I should be returning a boolean true/false? How exactly would I insert that in this one below?
function validateDisposition()
{
var vIncidentDisposition = document.forms['newIncident']['incidentDisposition'].value;
if (vIncidentDisposition == '')
{
document.forms['newIncident']['incidentDisposition'].className = 'required';
}
else
{
document.forms['newIncident']['incidentDisposition'].className = 'formborder';
}
}
assuming your validation functions return a bool, you should have something like
if( validateTime() && validateDate() && validateAge()... etc ) {
if (vDemAge == 'Age' || vDemAge == '') // If Age is not entered, set the value to be blank
{
document.forms['newIncident']['demAge'].value = '';
}
if (vBibNumber == 'Bib #' || vBibNumber == '') // If Bib # is not entered, set the value to blank
{
document.forms['newIncident']['bibNumber'].value = '';
}
document.getElementById(myForm).submit();
}
I got it working! The boolean idea put me on the right path. Thanks!
I just added a "return true" and "return false" to each of the validations, then used the answer above with the "&&" if to build the logic into the myform "if". If it doesn't pass all of them the else does a "return false". Works like a charm!
I have this code:
if($('input[name=id]').length == 1 && $('input[name=submitted]').length != 1 )
{
var id = $('input[name=id]').val(),
name = $('input[name=staro_ime]').val();
img_upload(name, id);
}
When form is submitted, hidden input field with name submitted is created. How can I check when form is submitted and then disable code from above?(This function is outside submit_event).
just add a submit event to the form.
$('#your_form').on('submit',function() {
$('#your_form').append("<input type='hidden' id='hidden_form' name='submitted' value='something' />");
}
if you want to just run the function once, you can use a variable out side of the event that you set, or you can just check if the appended field exists in the form. using the variable method:
var formSubmitted = false;
$('#your_form').on('submit',function() {
if(!formSubmitted) {
$('#your_form').append("<input type='hidden' id='hidden_form' name='submitted' value='something' />");
//anything else you want to run one time
formSubmitted = true;
$('#your_form').submit();
} else {
//submit form
}