Integrating Dropzone Into An AngularJS Page - javascript

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>

Related

Display Jquery Response in HTML

I am learning PHP and JavaScript. I have form using DropZone.js which upload files and giving response using Jquery Like below
<form class="dropzone" id = "image-upload" method="POST" action="upload.php">
<div class="form-label-group">
<input type="text" id="brand" class="form-control" placeholder="Brand Name" required autofocus>
<label for="brand"></label>
</div>
<div class="form-label-group">
<input type="text" id="reference" class="form-control" placeholder="Reference" required>
<label for="reference"></label>
</div>
<div class="form-label-group">
<input name="attached_files" value="" />
</div>
</form>
and JavaScript Like below
<script type="text/javascript">
Dropzone.autoDiscover = false;
jQuery(".dropzone").dropzone({
acceptedFiles: "image/*",
maxFilesize: 2, // MB
success : function(file, response) {
//console.log(file);
console.log(response);
if (response['target_file'] != '') {
var currentValue = jQuery("#image-upload input[name='attached_files'").val();
if (currentValue == '') {
jQuery("#image-upload input[name='attached_files'").val(response['target_file']);
} else {
jQuery("#image-upload input[name='attached_files'").val(currentValue + ", " + response['target_file']);
}
}
}
});
</script>
Its working fine as expected and showing me uploaded files in
<input name="attached_files" value="" />
But instead I want it as comma separated and <pre></pre> so it can look more better. Let me know if someone can help me for achieving my goal.
Thanks!

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());
});
}
}

Laravel Dropzone without class form Invalid element

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.
});
}
});
}

how to add multi captcha in same page and check both checkbox its fill

I have two forms on a single page, one of them is a login form and the other is a register form (two tabs) and I want to check the the captchas, but when I click the check captcha from register form I can't login.
The login form:
HTML:
<div id="loginUserTab" class="tab-pane fade">
<form>
<div class="form-group login-width-100">
<label for="id_number" class="m-rtl-label"><span class="requiredMark">*</span>passport number:</label>
<input type="text" class="form-control" id="pNo" name="pNo" data-validetta="required,minLength[10],maxLength[10]" lang="fa" style="text-align: left;">
</div>
<div class="form-group login-width-100">
<label for="mNumber" class="m-rtl-label"><span class="requiredMark"></span> telephone :</label>
<input type="text" class="form-control" id="tNumber" name="tNumber" data-validetta="required,minLength[11],maxLength[11]" lang="fa" style="text-align: left;">
</div>
<div class="form-group" style="float:right;padding-right: 20px;">
<div class="g-recaptcha" data-sitekey="...."></div>
</div>
<div class="form-group login-width-100">
<button type="submit" class="btn btn-primary colorGreenBTN">login</button>
</div>
</form>
</div>
JS:
var v = grecaptcha.getResponse();
if (v.length == 0) {
alert("fill the form");
return;
} else if (!$("#Terms").prop("checked")) {
alert("check the rules");
}
Simplest Way to validate as much g-captcha validate
Hope you have included api.js before </head> tag as per below
<script src="https://www.google.com/recaptcha/api.js?onload=CaptchaCallback&render=explicit"></script>
Your HTML Code looks like below
<div class="g-recaptcha-contact" data-sitekey="Your Site Key" id="RecaptchaField2"></div>
<input type="hidden" class="hiddenRecaptcha" name="ct_hiddenRecaptcha" id="ct_hiddenRecaptcha">
<div class="g-recaptcha-quote" data-sitekey="Your Site Key" id="RecaptchaField1"></div>
<input type="hidden" class="hiddenRecaptcha" name="qt_hiddenRecaptcha" id="qt_hiddenRecaptcha">
After you add this code in footer with tag
var CaptchaCallback = function() {
var widgetId1;
var widgetId2;
widgetId1 = grecaptcha.render('RecaptchaField1', {'sitekey' : 'Your Site Key', 'callback' : correctCaptcha_quote});
widgetId2 = grecaptcha.render('RecaptchaField2', {'sitekey' : 'Your Site Key', 'callback' : correctCaptcha_contact});
};
var correctCaptcha_quote = function(response) {
$("#qt_hiddenRecaptcha").val(response);
};
var correctCaptcha_contact = function(response) {
$("#ct_hiddenRecaptcha").val(response);
};
And Last easy step for developer add Jquery Validation as per below
$("#form_id").validate({
ignore: [],
rules: {
ct_hiddenRecaptcha: { required: true, },
qt_hiddenRecaptcha: { required: true, },
},
});
If you have same class for both the forms, you can use it to validate above.

form submitting twice via ajax POST

Inserting into mysql using php file called via AJAX. Before insert statement php code performs select query to find duplicate records and continue to insert statement.
Issue: When calling php file from ajax. it executed twice and getting response as duplicate record.
well i tried error_log from insert function its called twice.
Trigger point of form validation
$("#load-modal").on("click","#addcountryformsubmitbtn",function(e){
e.preventDefault();
var $form = $("#addcountryform"), $url = $form.attr('action');
$form.submit();
});
This is how form submitted after validation:
}).on('success.form.bv', function(e){
e.preventDefault();
var $form = $("#addcountryform"), $url = $form.attr('action');
$.post($url,$form.serialize()).done(function(dte){ $("#load-modal").html(dte); });
});
using bootstrapvalidator, Core PHP, mysqli, Chrome Browser.
Actual JS:
$(document).ready(function() {
$php_self_country="<?php echo $_SERVER['PHP_SELF']."?pg=countrycontent"; ?>";
$("#country-content").load($php_self_country,loadfunctions);
$("#country-content").on( "click", ".pagination a", function (e){
e.preventDefault();
$("#country-loading-div").show();
var page = $(this).attr("data-page");
$("#country-content").load($php_self_country,{"page":page}, function(){
$("#country-loading-div").hide();
loadfunctions();
});
});
$("#country-content").on("click","#closebtn",function(e){
e.preventDefault();
$("#country-content").load($php_self_country,loadfunctions);
});
});
function loadfunctions(){
$("[data-toggle='tooltip']").tooltip();
$("#country-content").on("click","#addcountrybtn, #addcountrylargebtn",function(e){
e.preventDefault();
$.ajax({
url: $php_self_country,
type: "POST",
data: { 'addcountry':'Y' },
dataType: "html",
cache: false
}).done(function(msg){
$("#load-modal").html(msg);
$("#load-modal").modal('show');
$('input[type="radio"]').iCheck({ checkboxClass: 'icheckbox_minimal', radioClass: 'iradio_minimal' });
modalvalidation();
}).fail(function() {
$("#load-modal").html( "Request Failed. Please Try Again Later." );
});
});
$("#country-content").on("click",".tools a",function(e){
e.preventDefault();
var recordid = $(this).attr("record-id");
$.ajax({
url: $php_self_country,
type: "POST",
data: { 'modifycountry':recordid },
dataType: "html",
cache: false
}).done(function(msg){
$("#load-modal").html(msg);
$("#load-modal").modal('show');
$('input[type="radio"]').iCheck({ checkboxClass: 'icheckbox_minimal', radioClass: 'iradio_minimal' });
modalvalidation();
}).fail(function() {
$("#load-modal").html( "Request Failed. Please Try Again Later." );
});
});
$("#load-modal").on("click","#addcountryformsubmitbtn",function(e){
e.preventDefault();
var $form = $("#addcountryform"), $url = $form.attr('action');
$form.submit();
});
$("#load-modal").on("hide.bs.modal", function () {
window.location.href=$php_self_country_pg;
});
}
function modalvalidation(){
$('#addcountryform').bootstrapValidator({
message: 'This value is not valid',
feedbackIcons: {
valid: 'glyphicon glyphicon-ok',
invalid: 'glyphicon glyphicon-remove',
validating: 'glyphicon glyphicon-refresh'
},
fields: {
[-------Validation part comes here----------]
}
}).on('success.form.bv', function(e){
e.preventDefault();
var $form = $("#addcountryform"), $url = $form.attr('action');
$.post($url,$form.serialize()).done(function(dte){ $("#load-modal").html(dte); });
});
}
HTML
this html is called on button click addcountrybtn via AJAX and write in to div load-modal which is in base html file.
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title"><i class="fa fa-exchange"></i> <?php echo COUNTRYLABEL; ?></h4>
</div>
<div class="modal-body">
<form role="form" method="POST" action="self.php" name="addcountryform" id="addcountryform" class="form-horizontal">
<div class="form-group">
<div class="col-xs-3">
<label for="countryname" class="pull-right">Country Name</label>
</div>
<div class="col-xs-9">
<div class="lnbrd">
<input type="text" class="form-control" name="countryname" placeholder="Enter Country Name">
</div>
</div>
</div>
<div class="form-group">
<div class="col-xs-3">
<label for="crncyname" class="pull-right">Currency Name</label>
</div>
<div class="col-xs-9">
<div class="lnbrd">
<input type="text" class="form-control" name="crncyname" placeholder="Enter Currency Name">
</div>
</div>
</div>
<div class="form-group">
<div class="col-xs-3">
<label for="crncycode" class="pull-right">Currency Code</label>
</div>
<div class="col-xs-9">
<div class="lnbrd">
<input type="text" class="form-control" name="crncycode" placeholder="Enter Currency Code">
</div>
</div>
</div>
<div class="form-group">
<div class="col-xs-3">
<label for="forrate" class="pull-right">Foreign Currency Rate<?php echo isset($icon)?$icon:''; ?></label>
</div>
<div class="col-xs-9">
<div class="lnbrd">
<input type="text" class="form-control" name="forrate" placeholder="Enter Foreign Currency Rate.">
</div>
</div>
</div>
<div class="form-group">
<div class="col-xs-3">
<label for="taxpercent" class="pull-right">Tax %</label>
</div>
<div class="col-xs-9">
<div class="lnbrd">
<input type="text" class="form-control" name="taxpercent" placeholder="Enter Tax Percentage">
</div>
</div>
</div>
</form>
</div>
<div class="modal-footer clearfix">
<button type="button" class="btn btn-danger pull-right" id="addcountryformsubmitbtn">Add</button>
</div>
</div>
Note:- in Database point of view code works as expected.
Couple of things that I have seen could possibly be the cause.
If you are using IE, I have seen that perform a GET immediately before doing a POST (to the same URL, with the same data being sent over), so it could be worth trying to check for that on your server (and ignore the GET)
Something else it maybe to add the following to the end of your button click events after the AJAX call (actually, normally I'd put the first line at the top with the prevent default, and the return statement obviously goes very last)...
e.stopImmediatePropagation();
return false;

Categories

Resources