Laravel Dropzone without class form Invalid element - javascript

i am trying to make a multiple upload with dropzone on laravel and i take a look on documentation of dropzone.
The example must be using form and give class dropzone , here my case i want to use dropzone and others text field
and got error Uncaught Error: Invalid dropzone element. here is the screenshot : error screenshot
here is my html code :
<form method="POST" action="/backend/blog" enctype="multipart/form-data" id="formku">
<div class="form-group label-floating">
<label class="control-label">Title</label>
<input type="text" name="title" class="form-control">
</div>
<div class="form-group label-floating">
<label class="control-label">Written By</label>
<input type="text" name="written_by" class="form-control">
</div>
<div class="form-group" id="place_image" style="display: none;">
<img src="" id="image_category" style="width: 95px;height: 50px;">
</div>
<div class="form-group">
<a class="btn btn-primary" id="btn_choose_image" onclick="$('#choose_image').click();">Choose Image</a>
<input style="display: none;" type="file" id="choose_image" name="image"></input>
</div>
<textarea id="bodyField" name="description"></textarea>
#ckeditor('bodyField', ['height' => 250])
<div class="form-group label-floating">
<div class="row">
<label class="control-label">Category</label>
<select class="selectpicker" data-style="btn btn-primary btn-round" title="Single Select" data-size="7" name="category">
<option disabled selected>Choose Category</option>
#foreach( $categories as $key => $category):
<option value="{{ $category->id }}">{{ $category->name }}</option>
#endforeach;
</select>
</div>
</div>
<div class="dropzone" id="imageUpload">
<h3>Upload Multiple Image By Click On Box</h3>
</div>
<div class="checkbox">
<label>
<input type="checkbox" name="status"> Status
</label>
</div>
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<input type="submit" class="btn btn-fill btn-rose" value="Submit">
</form>
and here is my JS code :
Dropzone.autoDiscover = false;
var imageUpload = new Dropzone("div#imageUpload", {
url: "dropzone/store",
autoProcessQueue:false,
uploadMultiple: true,
maxFilesize:5,
maxFiles:3,
acceptedFiles: ".jpeg,.jpg,.png,.gif",
init: function() {
var submitButton = document.querySelector("#submit-all")
//imageUpload = this; // closure
submitButton.addEventListener("click", function(e) {
e.preventDefault();
e.stopPropagation();
imageUpload.processQueue(); // Tell Dropzone to process all queued files.
});
// You might want to show the submit button only when
// files are dropped here:
this.on("addedfile", function() {
// Show submit button here and/or inform user to click it.
});
}
});
anyone have solution of this trouble ?

You could try to check if the imageUpload element is there first :
Dropzone.autoDiscover = false;
if (document.getElementById('imageUpload')) {
var imageUpload = new Dropzone("div#imageUpload", {
url: "dropzone/store",
autoProcessQueue:false,
uploadMultiple: true,
maxFilesize:5,
maxFiles:3,
acceptedFiles: ".jpeg,.jpg,.png,.gif",
init: function() {
var submitButton = document.querySelector("#submit-all")
//imageUpload = this; // closure
submitButton.addEventListener("click", function(e) {
e.preventDefault();
e.stopPropagation();
imageUpload.processQueue(); // Tell Dropzone to process all queued files.
});
// You might want to show the submit button only when
// files are dropped here:
this.on("addedfile", function() {
// Show submit button here and/or inform user to click it.
});
}
});
}

Related

What is the best practice to turn input File Browse Button into a Dropzone?

I'm new to dropzone, and I want to turn my browse button into my dropzone that accepts files.
This is my form now.
#extends('layouts.be.master')
#section('content')
<script src="//cdn.ckeditor.com/4.8.0/standard/ckeditor.js"></script>
<div class="card-body card-padding">
<div class="row">
{!! Form::open(array('class' => 'form-horizontal dropzone', 'role' =>'form', 'url'=>'portfolio/store','files' => true)) !!}
<div class="col-sm-12">
{{-- Name --}}
<div class="form-group">
<label for="email" class="col-sm-2 control-label">Name</label>
<div class="col-sm-10">
<input type="text" value="{{Request::old('name')}}" value="" name="name" class="form-control" id="name" placeholder="Name">
</div>
</div>
{{-- Type --}}
<div class="form-group">
<label for="email" class="col-sm-2 control-label">Type</label>
<div class="col-sm-10">
<select name="type" class="form-control">
#foreach($portfolioTypes as $item)
<option value="{{ $item }}">{{ $item }}</option>
#endforeach
</select>
</div>
</div>
{{-- Tags --}}
<div class="form-group">
<label for="email" class="col-sm-2 control-label">Tags</label>
<div class="col-sm-10">
</div>
<input id="tags" name="tag">
</div>
{{-- URL --}}
<div class="form-group">
<label for="url" class="col-sm-2 control-label">URL</label>
<div class="col-sm-10">
<input name="url" type="text" value="" class="form-control" placeholder="URL">
</div>
</div>
{{-- URL --}}
<div class="form-group">
<label for="url" class="col-sm-2 control-label">Images</label>
<div class="col-sm-10 ">
<input id="images" name="images[]" type="file" multiple>
</div>
</div>
{{-- Description --}}
<div class="form-group">
<label for="email" class="col-sm-2 control-label">Description</label>
<div class="col-sm-10">
<textarea name="description" rows="20" cols="80" id="description">
</textarea>
<script>
CKEDITOR.replace( 'description' );
CKEDITOR.config.height = 500;
</script>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-4 col-sm-8">
<a class="btn btn-default" href="/portfolio"> Cancel </a>
<button type="submit" class="btn btn-info">Create</button>
</div>
</div>
</div>
{!!Form::close()!!}
</div>
</div>
#stop
#section('custom-scripts')
{{-- Tags --}}
<link rel="stylesheet" type="text/css" href="/css/jquery.tag-editor.css">
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.11.1.min.js"></script>
<script src="https://code.jquery.com/ui/1.10.2/jquery-ui.min.js"></script>
<script type="text/javascript" src="/js/jquery.caret.min.js"></script>
<script type="text/javascript" src="/js/jquery.tag-editor.js"></script>
<script type="text/javascript" src="/js/ckeditor.js"></script>
<script type="text/javascript" src="/js/dropzone.js"></script>
<script type="text/javascript">
$('#tags').tagEditor({
autocomplete: {
delay: 0,
position: { collision: 'flip' },
source: [<?php echo '"'.implode('","', $skillList).'"' ?>]
},
forceLowercase: false,
delimiter: ',', /* space and comma */
placeholder: 'Enter tags ...',
initialTags: ['HTML','CSS','Javascript','jQuery','Bash']
});
$("#images").dropzone();
</script>
#stop
This is my result
The documentation suggested to add the class"dropzone" to the form element, but that if I my entire form only have file upload, but I have other inputs as well.
Right now, my browse button works perfectly (100% tested), and I don't want to break that functionality at all.
I just want to improve the look of it, added the ability to drop files, and submit those files as soon as form submit.
How would one deal with that ?
Update
I tried what #Kunal suggested
Dropzone.options.myDropzone= {
url: 'portfolio/store',
autoProcessQueue: false,
uploadMultiple: true,
parallelUploads: 5,
maxFiles: 5,
maxFilesize: 1,
acceptedFiles: 'image/*',
addRemoveLinks: true,
init: function() {
dzClosure = this; // Makes sure that 'this' is understood inside the functions below.
// for Dropzone to process the queue (instead of default form behavior):
document.getElementById("submit-all").addEventListener("click", function(e) {
// Make sure that the form isn't actually being sent.
e.preventDefault();
e.stopPropagation();
dzClosure.processQueue();
});
//send all the form data along with the files:
this.on("sendingmultiple", function(data, xhr, formData) {
formData.append("name", jQuery("input[name ='name']").val());
formData.append("name", jQuery("select[name ='type']").val());
formData.append("name", jQuery("input[name ='tag']").val());
formData.append("name", jQuery("input[name ='url']").val());
formData.append("name", jQuery("textarea[name ='description']").val());
});
}
}
I don't see anything submit to my back end, and also it seems to submit 2 times, because I see 2 records created.
You can add the dropzone.js with other inputs in your form by just changing some setting in the dropzone.js. And they are as follows
1: Create a normal form (don't forget the method and enctype args since this is not handled by dropzone anymore).
2: Put a div inside with the class="dropzone" (that's how Dropzone attaches to it) and id="yourDropzoneName" (used to change the options).
3: Set Dropzone's options, to set the url where the form and files will be posted, deactivate autoProcessQueue (so it only happens when user presses 'submit') and allow multiple uploads (if you need it).
4: Set the init function to use Dropzone instead of the default behavior when the submit button is clicked.
5: Still in the init function, use the "sendingmultiple" event handler to send the form data along wih the files.
HTML
<form action="upload.php" enctype="multipart/form-data" method="POST">
<input type="text" id ="firstname" name ="firstname" />
<input type="text" id ="lastname" name ="lastname" />
<div class="dropzone" id="myDropzone"></div>
<button type="submit" id="submit-all"> upload </button>
</form>
Dropzone.js
Dropzone.options.myDropzone= {
url: 'upload.php',
autoProcessQueue: false,
uploadMultiple: true,
parallelUploads: 5,
maxFiles: 5,
maxFilesize: 1,
acceptedFiles: 'image/*',
addRemoveLinks: true,
init: function() {
dzClosure = this; // Makes sure that 'this' is understood inside the functions below.
// for Dropzone to process the queue (instead of default form behavior):
document.getElementById("submit-all").addEventListener("click", function(e) {
// Make sure that the form isn't actually being sent.
e.preventDefault();
e.stopPropagation();
dzClosure.processQueue();
});
//send all the form data along with the files:
this.on("sendingmultiple", function(data, xhr, formData) {
formData.append("firstname", jQuery("#firstname").val());
formData.append("lastname", jQuery("#lastname").val());
});
}
}

When I select the options from the dropdown the button should be triggered automatically and produce the unique Id

I have a drop down and when I select one option from the dropdown the button has to be triggered automatically and it produces some unique id. I am not sure how the trigger can happen when we select the value from the dropdwon.
I have refered this link
Auto trigger click on a button when selecting from dropdown list
but its not working and its not showing any error. I can see that its not going inside the button click function. can someone help me how to do the auto click when we select the dropdown option?
I am attacching the code here
<div id="dialog-form" title="Send Email Invite">
<form>
<fieldset>
<label for="select1">Round Level</label>
<div class="col-md-4">
<select name="select1" class="form-control" id="select1" style="width:200px; height:30px;" required>
<option value="">Select the below option</option>
{% for each_round in round_names %}
<option value="{{each_round.round_id,each_round.round_name}}">{{each_round.round_name}}</option>
{% endfor %}
</select>
<div class="valid-feedback">Valid</div>
<div class="invalid-feedback">Please fill out this field</div>
<div class="col-md-4" id="generateButton" style="display:none;" required>
<input id="generateUrl" value="generate url" size="40%" readonly />
<input type="button" class="btn btn-info" value="Generate URL" id="urlbutton"></input>
</div>
<div id="result">
<textarea name="rdesc" id="rdesc" style="width:200px; height:300px; display:none;"
required></textarea>
</div>
</div>
<script>
$("#select1").on('change', function () {
$("[name='select1']:submit").trigger("#urlbutton")
var dropdownValue = document.getElementById("select1");
var roundName = dropdownValue.options[dropdownValue.selectedIndex].value;
$.ajax({
type: 'POST',
url: 'blah',
data: {
'blah': blah
},
success: function (results) {
$("#rdesc").show();
$("#rdesc").text(results.round_description);
}
})
})
</script>
<input type="submit" tabindex="-1" style="position:absolute; top:-1000px">
</fieldset>
</form>
</div>
<script>
$("#urlbutton").click(function () {
console.log("i am coming here");
$.ajax({
type: 'POST',
url: 'blah',
data: {
'blah':blah
},
success: function (data) {
var url_textbox = document.getElementById("generateUrl");
url_textbox.setAttribute('value', data.url);
}
})
})
</script>
You can click the button programmatically like this.
On your select change click the button.
("#urlbutton").click()

Submit form not working when using jQuery

I have a form and when the user clicks submit, I would like the form to hide and a thank you message to appear. Unfortunately with the code I have, it's not working and I can't figure out why. I think it might be something with the jQuery so I'd like to try and re-write this function using vanilla JS, but I'm not sure how.
It is the last part of the function, the if (empty.length), hide form, show thank you message that is causing me problems. Everything else is working fine, so its this function I would like to try and write in JavaScript, or try another way using jquery to make it work. The problem is it doesn't work in my code, but when I open this in a jsfiddle, it doesnt just hide the form it opens a new page and I get an error. I don't want the user to be directed to a new page, I just want the form to close and thank-you message to appear. I am very new to this so I apologize if my code is messy.
UPDATE: I really think the issue here is the jQuery, can I write this in plain JS and would that fix it?
var $subscribe = $('#click-subscribe');
var $subscribeContent = $('#subscribe-content');
var $subscribeClose = $('#subscription-close');
$subscribeContent.hide();
$subscribe.on('click', function(e) {
e.preventDefault();
$subscribeContent.slideToggle();
});
$subscribeClose.on('click', function(e) {
e.preventDefault();
$subscribeContent.slideToggle();
})
var $form = $('#signup-form'),
$signupForm = $('.form-show'),
$formReplace = $('#thank-you');
$formReplace.hide();
$form.on('submit', function() {
var empty = $(this).find("input, select, textarea").filter(function() {
return this.value === "";
});
if (empty.length <= 0) {
$signupForm.hide();
$formReplace.show();
} else {
return false;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="click-subscribe">Show / hide form</button>
<div id="subscribe-content">
<div class="subscription-signup">
<div class="subscription-close" id="subscription-close"></div>
<div class="email-signup">
<p class="cat-title subscription-text">lorem ipsum</p>
<p class="subscription-text">lorem ipsum</p>
<p class="subscription-text">lorem ipsum</p>
<div class="subscription-form">
<form id="signup-form" class="form-show" name="signup-form" method="post" action="${URLUtils.url('Newsletter-SubscribeMobile')}">
<div class="form-row salutation header">
<label for="salutation">Title</label>
<div class="chzn-row valid salutation">
<select id="title" name="title" class="chzn-global-select input-select optional required">
<option value="">--</option>
<option value="Mr">Mr.</option>
<option value="Mrs">Mrs.</option>
<option value="Ms">Ms.</option>
<option value="Miss">Miss</option>
</select>
</div>
</div>
<div class="form-row required">
<label for="firstname">
<span aria-required="true">First Name</span>
<span class="required-indicator">*</span>
</label>
<input class="input-text required" id="firstname" type="text" name="firstname" value="" maxlength="500" autocomplete="off">
</div>
<div class="form-row required">
<label for="lastname">
<span aria-required="true">Surname</span>
<span class="required-indicator">*</span>
</label>
<input class="input-text required" id="lastname" type="text" name="lastname" value="" maxlength="500" autocomplete="off">
</div>
<div class="form-row required">
<label for="signup-email" style="display:none;">Email</label>
<input class="header-signup-email" type="text" id="signup-email-header" name="signup-email" value="" placeholder="Email" />
</div>
<div class="form-row text-center">
<input type="submit" name="signup-submit" id="signup-submit" class="subscribe-submit" value="Submit" />
</div>
</form>
<div id="thank-you">
<p>Thanks for subscribing!</p>
</div>
</div>
</div>
</div>
</div>
I think some other javascript/jQuery code are making issues to run the codes, for simple solution make your code as plugin and called it like following.
create new js file called validation.js
(function($){
$.fn.validation = function(){
var $subscribe = $('#click-subscribe');
var $subscribeContent = $('#subscribe-content');
var $subscribeClose = $('#subscription-close');
$subscribeContent.hide();
$subscribe.on('click', function(e) {
e.preventDefault();
$subscribeContent.slideToggle();
});
$subscribeClose.on('click', function(e) {
e.preventDefault();
$subscribeContent.slideToggle();
});
var $form = $('#signup-form'), $signupForm = $('.form-show'), $formReplace = $('#thank-you'); $formReplace.hide();
this.on('submit', function(e){
var empty = $(this).find("input, select, textarea").filter(function() {
return this.value === "";
});
if(empty.length == 0){
$signupForm.hide();
$formReplace.show();
}
e.preventDefault();
});
};
})(jQuery);
Now, call the validation.js at the head like below
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="validation.js"></script>
<script type="text/javascript">
$(function(){
$('#signup-form').validation();
});
</script>

Integrating Dropzone Into An AngularJS Page

I'm trying to integrate a Dropzone into an AngularJS page, but I'm not having much luck. I was able to get the Dropzone code to work in a page by itself, but when I put it into the file with the AngularJS code, it doesn't work. I need the Dropzone to work with other form elements (i.e. text fields, text areas, combo-boxes, etc.), not just by itself. Here is my code:
<div ng-show="error" class="alert alert-danger">{{error}}</div>
<div ng-if="CustomerID > 0">
<form name="crForm" action="php/process_cr_form.php" enctype="multipart/form-data" ng-submit="login()" role="form">
<!-- <form name="form" ng-submit="login()" role="form"> -->
<div class="form-group">
<label for="summary">Summary/Title of the Request</label>
<input type="text" name="summary" id="summary" class="form-control" ng-model="summary" required />
<span ng-show="form.summary.$dirty && form.summary.$error.required" class="help-block">Summary/Title is required</span>
</div>
<div class="form-group">
<label for="description">Description of the Request</label>
<textarea name="description" id="description" class="form-control" ng-model="description" required></textarea>
<span ng-show="form.description.$dirty && form.description.$error.required" class="help-block">Description is required</span>
</div>
<div class="dropzone" id="my-awesome-dropzone"><span>Drop files here to upload</span></div>
<div class="form-actions">
<button id="submit" type="submit" ng-disabled="form.$invalid || dataLoading" class="btn btn-danger">Submit</button>
</div>
</form>
</div>
<div ng-if="!CustomerID > 0">
Logout
</div>
<script>
Dropzone.options.myAwesomeDropzone = {
paramName: "files", // The name that will be used to transfer the file
maxFilesize: 5, // MB
parallelUploads: 25,
maxFiles: 25,
autoProcessQueue: false,
uploadMultiple: true,
acceptedFiles: 'image/*,.xls,.xlsx,.doc,.docx,.pdf',
init: function() {
var submitButton = document.querySelector("#submit-all")
myDropzone = this; // closure
document.getElementById('submit').addEventListener("click", function() {
myDropzone.processQueue(); // Tell Dropzone to process all queued files.
});
this.on("addedfile", function() {
});
this.on("complete", function(file) {
myDropzone.removeFile(file);
});
}
};
</script>

Repeating data after form submit

I have 4 links ( view car, hand car, retrieve car and add car). Every link is load by Ajax. The problem is in (add car), the first time I click submit the data gets recorded in the database once ... when I click (view car) and go back to (add car) and submit the form again it adds the data to the database 3 times. Also when I press (view car) and back to add car and submit the from again it records the data 6 times.
ajax.js
$(document).ready(function(){
$('#viewCar').click(function(){
$("#show").load('view');
});});//end click
$(document).ready(function(){
$('#handCar').click(function(){
$("#show").load('handcar');
});//end load
});//end click
$(document).ready(function(){
$('#retrieveCar').click(function(){
$("#show").load('retrieve');
});//end load
});//end click
$(document).ready(function(){
$('#addCar').click(function(){
enter code here $("#show").load('add');
});//end load
});//end click
$(document).ready(function(){
$("#submit").click(function(e)
{
e.preventDefault();
var postData = $('#cForm').serialize();
var formURL = 'car/add';
var LT = $("#LT").val();
var LN = $("#LN").val();
if(LT == ''|| LN == '')
{
console.log('error some form is empty !!');
}
else
{
$.ajax({
url : formURL,
type: "POST",
data : postData,
success:function()
{
$('#cForm').find("input[type=text]").val(" ");
console.log('saved !!');
}
});
}
return null;
}); //end click
}); //end of ready
car_links.html
<div class="container">
<ul class="ul">
<li class="li"><a id="viewCar" href="#" >view cars</a></li>
<li class="li"><a id="handCar" href="#">hand car</a></li>
<li class="li"><a id="retrieveCar" href="#">retrieve car</a></li>
<li class="li"><a id="addCar" href="#">add a car</a></li>
</ul>
car_add.html
<div class="col-md-4 col-md-offset-4">
<form id="cForm" class="form-horizontal" >
<?php echo validation_errors(); ?>
<legend>add a new car</legend>
<div class="form-group">
<label class="col-sm-5 control-label" for="LN">License #:</label>
<div class="col-sm-13">
<input class="form-control form-size" type="text" id="LN" name="LN" value="" /></li>
</div>
</div>
<div class="form-group">
<label class="col-sm-5 control-label" for="LT">License Ltr:</label>
<div class="col-sm-13">
<input class="form-control form-size" type="text" id="LT" name="LT" value="" />
</div>
</div>
<div class="form-group">
<label class="col-sm-5 control-label" for="Model">Model:</label>
<div class="col-sm-13">
<select class="form-control form-size" name="Model">
<option value="Toyota"> Toyota</option>
<option value="Audi"> Audi</option>
<option value="Hundai"> Hundai</option>
<option value="BMW"> BMW</option>
</select>
</div>
</div>
<div class="form-group">
<label class="col-sm-5 control-label" for="Year"> Year:</label>
<div class="col-sm-13">
<select class="form-control form-size" name="Year">
<option value="2010"> 2010</option>
<option value="2014"> 2014</option>
</select>
</div>
</div>
<div class="form-actions btn-action">
<button class="btn btn-success" id="submit" value="save" type="button" name="submit">save</button></li>
<button class="btn btn-danger" type="reset" name="reset"> Reset </button></li>
</div>
</form>
</div>
For starters you have each click function in its own .ready function. The .ready function is initiated when the page is loaded. If you want the function to load only on a click then you need to place the click function into a function like this.
$(function() {
$('#viewCar').click(function() {
$("#show").load('view');
});
$('#handCar').click(function() {
$("#show").load('handcar');
});
$('#retrieveCar').click(function() {
$("#show").load('retrieve');
});
$('#addCar').click(function() {
$("#show").load('add');
});
$("#submit").click(function(e) {
e.preventDefault();
var postData = $('#cForm').serialize();
var formURL = 'car/add';
var LT = $("#LT").val();
var LN = $("#LN").val();
if(LT == ''|| LN == '') {
console.log('error some form is empty !!');
} else {
$.ajax({
url : formURL,
type: "POST",
data : postData,
success:function() {
$('#cForm').find("input[type=text]").val(" ");
console.log('saved !!');
}
});
}
return null;
});
}
If that doesn't work or is not what you wanted please leave me a comment.

Categories

Resources