Preprocess before kendo ui upload - javascript

I want to pass some data(a guid) to the upload method of the kendoUpload so that the particular MVC Controller action method will receive that data. Each time the upload happens, I need to pass this data (guid).
$("#propertyAttachmentUpload").kendoUpload({
async: {
saveUrl: fileUploadUrl,
chunkSize: 1048576,
removeUrl: "remove"
},
multiple: true,
upload: function (e) {
e.data = { id: $("#fileUplpderParentObjectId").val(), fileId: fileId };
},
showFileList: false,
dropZone: ".propertyAttachmentDropZone",
success: onSuccess
});
The field is fileId. I can call the above code block in a click event of the upload button and it works but the Kendo UI styles are not applied to the upload button at the initialization.
$("#propertyAttachmentUpload").click(
function() {
var fileId = guid();
$("#propertyAttachmentUpload").kendoUpload({
async: {
saveUrl: fileUploadUrl,
chunkSize: 1048576,
removeUrl: "remove"
},
multiple: true,
upload: function (e) {
e.data = { id: $("#fileUplpderParentObjectId").val(), fileId: fileId };
},
showFileList: false,
dropZone: ".propertyAttachmentDropZone",
success: onSuccess
});
});
How can I initialize the fileId without loosing the Kendo UI styles.
Note: I cannot call guid() inside upload method since the upload method calls for each uploading chunk. For all the chunks the fileId should be same for a particular file.

I've resolved this problem using a global variable and setting that variable in the click event of the upload button,
var fileGuid = '';
$(document).on('click', '#propertyAttachmentUpload', function() {
fileGuid = "";
fileGuid = guid();
})
$("#propertyAttachmentUpload").kendoUpload({
async: {
saveUrl: fileUploadUrl,
chunkSize: 1048576,
removeUrl: "remove"
},
multiple: true,
upload: function (e) {
e.data = { id: $("#fileUplpderParentObjectId").val(), fileId: fileGuid };
},
showFileList: false,
dropZone: ".propertyAttachmentDropZone",
success: onSuccess
});

Related

How to create a single request when submit multiple forms using a common single submit button

I have a form which include 2 dropzone secrtions and a textboxes from and a single submti button on button submbit form submit but create three requests 2 dor dropzoen files and one form textboxes form but i need all this data in a single request. So how can we submti multiple form in a single request of array
Below is my JS Code
<script>
Dropzone.autoDiscover = false;
var file_after;
var fileList = new Array;
var i = 0;
// Dropzone class:
var myDropzone = new Dropzone("div#mydropzone", {
{{--url: "{{route('dropzone-files')}}",--}}
url: "{{route('case-submit')}}",
acceptedFiles: '.stl',
addRemoveLinks: true,
autoProcessQueue: false,
uploadMultiple: true,
paramName: "file_before",
params: {
_token: "{{csrf_token()}}"
},
});
var fileafterdropzone = new Dropzone("div#fileafterdropzone", {
{{--url: "{{route('dropzone-files')}}",--}}
url: "{{route('case-submit')}}",
acceptedFiles: '.stl',
addRemoveLinks: true,
parallelUploads: 10,
uploadMultiple: true,
paramName: "file_after",
autoProcessQueue: false,
params: {
_token: "{{csrf_token()}}"
},
});
</script>
<script>
$(document).ready(function (e) {
// Submit form data via Ajax
$("#case-form").on('submit', function (e) {
fileafterdropzone.processQueue();
myDropzone.processQueue();
e.preventDefault();
var formData = new FormData(this);
$.ajax({
type: 'POST',
url: '{{route('case-submit')}}',
// data: new FormData(this),
dataType: 'json',
data: formData,
contentType: false,
cache: false,
processData: false,
success: function (response) {
var files_before = Dropzone.forElement("div#mydropzone");
files_before.removeAllFiles();
var fiels_after = Dropzone.forElement("div#fileafterdropzone");
fiels_after.removeAllFiles();
$.notify("Case Registered Successfully", "success");
},
error: function (xhr, json, errorThrown) {
var response = JSON.parse(xhr.responseText);
$.each(response.errors, function (key, value) {
$("#" + key + "_error").text(value[0]);
var element = document.getElementById(key + "_error");
element.classList.add('fa', 'fa-times-circle-o');
$("#" + key + "_error").css("color", "red");
$.notify(" There might be a problem case not registered", "error");
});
}
});
});
});
</script>
Each dropzone has its own post request, denoted by the url attribute on the dropzone creation and will want to send a request for each file.
What I would suggest doing is creating a new method to store your files (eg. to a File model). You could then return the $file->id back to the front-end using the dropzone success callback and append those file ids to the form.
Then on submit the form will have all the file ids of the files so you can associate them on the backend.

Populating a dropzone with files from the server - async

I'm trying to populate my dropzone with files I'm getting from the server. I found this post which seems to do what I want, however it seems I can only call this addCustomFile function while in the init function, and not later after I've asychronisily received my data from the server (with the list of files associated with the object I'm viewing).
Dropzone.options.imageDrop = {
url: "upload.php",
previewTemplate: previewTemplate,
params: { taskId: urlParams.get('id')},
init: function() {
this.addCustomFile = function(file, thumbnail_url , response){
this.files.push(file);
this.emit("addedfile", file);
this.emit("thumbnail", file, thumbnail_url);
this.emit("processing", file);
this.emit("success", file, response , false);
this.emit("complete", file);
}
this.addCustomFile ({ //THIS WORKS
processing: true,
accepted: true,
name: "The name",
size: 12345,
type: 'image/jpeg',
status: Dropzone.SUCCESS
}, "fine.jpg", {
status: "success"
})
}
}
let imageDropZone = $("#imageDrop").dropzone();
imageDropZone.addCustomFile ({ //THIS DOESN'T WORK - addCustomFile is not a function
processing: true,
accepted: true,
name: "The name",
size: 12345,
type: 'image/jpeg',
status: Dropzone.SUCCESS
}, "fine.jpg", {
status: "success"
})
Any thoughts on how to best modify this so I can call it in a async function after the dropzone has been created?
I was able to resolve this using promises. I had to define a variable for a promise as well as one for the data that would both be in scope across the code. Then create the promise during the init and resolve it inside my other async call. Updated code below:
var imageLoadDefer; //Variable that will get a promise
var slowLoaded; //Variable that will get loaded with data async
Dropzone.options.imageDrop = {
url: "upload.php",
previewTemplate: previewTemplate,
params: { taskId: urlParams.get('id')},
init: function() {
this.addCustomFile = function(file, thumbnail_url , response){
this.files.push(file);
this.emit("addedfile", file);
this.emit("thumbnail", file, thumbnail_url);
this.emit("processing", file);
this.emit("success", file, response , false);
this.emit("complete", file);
}
//Create the promise using jQuery
imageLoadDefer =$.Deferred();
//Important: Make sure to put this into a variable that can be used in the following function
var imDrop = this;
imageLoadDefer.always(function(){
//promise is resolved and variable is now populated
imDrop.addCustomFile ({ //THIS WORKS NOW, ASYNC
processing: true,
accepted: true,
name: slowLoaded.name,
size: slowLoaded.size,
type: 'image/jpeg',
status: Dropzone.SUCCESS
}, slowLoaded.thumbnail, {
status: "success"
});
});
}
}
let imageDropZone = $("#imageDrop").dropzone();
$.getJSON('images.json', function (data) {
slowLoaded = data;
imageLoadDefer.resolve(); //data loaded so resolve image promise
}

Unable to load the dropdown list on a kendo window from a method using Webservice

On clicking Edit button on a Page a method is triggered and a window which uses a kendo template is opened . One of the control on the kendo window is Kendo dropdown list which needs to have values comming from the webmethod.The error i am getting on clicking of the edit button is 'Object doesn't support property or method 'slice'. Below is my code for the Edit button.
function edit(item) {
var editTemplate = kendo.template($("#editTemplate").html());
var treeview = $("#treeview").data("kendoTreeView");
var selectedNode = treeview.select();
var node = treeview.dataItem(selectedNode);
$("<div/>")
.html(editTemplate({ node: node}))
.appendTo("body")
.kendoWindow({
modal: true,
activate:function(){
$("#roles").kendoDropDownList({
dataTextField: "Countryname",
dataValueField: "CountryId",
dataSource: {
transport: {
read: {
url: "/Services/MenuServices.asmx/getcountries",
contentType: "application/json; charset=utf-8", // tells the web service to serialize JSON
type: "POST", //use HTTP POST request as the default GET is not allowed for ASMX
}
}
}
})
},
deactivate: function () {
this.destroy();
}
})
.on("click", ".k-primary", function (e) {
var dialog = $(e.currentTarget).closest("[data-role=window]").getKendoWindow();
var textbox = dialog.element.find(".k-textbox");
var Id = $('#ID').val();
node.set("id", Id);
dialog.close();
var treenode = treeview.dataSource.get(itemid);
treenode.set("id", Id);
treenode.ID = Id;
console.log(JSON.stringify(treenode));
})
}
IS there any property for Kendo window that triggers this service when its opened.Right now i am using activate event but its not working.tried using 'Open' event also.
Thanks
I added the Schema part to the datasource and it worked.
schema: {
data: function (response) {
return JSON.parse(response.d); // ASMX services return JSON in the following format { "d": <result> }.
},
model: { // define the model of the data source. Required for validation and property types.
id: "CountryId",
fields: {
CountryId: { editable: false, nullable: false, type: "string" },
Countryname: { editable: true, nullable: true, type: "string" },
}
},
},

How to add headers at runtime in fine uploader

I am using fine uploader for uploading file on server, For this I need to make 2 web api calls.
On button click, First web api saving value and returning result in integer, and I need to pass that integer result in header for each file while uploading.
But I am not able to pass values in headers,
code,
uploader = new qq.FineUploader({
element: $('#manual-fine-uploader1')[0],
request: {
endpoint: Url.AddEvaluationFiles,
},
autoUpload: false,
text: {
uploadButton: '<i class="icon-plus icon-white"></i> Select Files'
},
debug: true,
callbacks: {
onSubmit: function (id, fileName) {
},
onStatusChange: function (id, oldStatus, newStatus) {
if (newStatus == "uploading") {
alert("Add header");
}
},
onUpload: function (id, name) {
alert("Onupload");
this.append("RequestId", $("#ReqId").val());
}
}
});
I am calling upload function in success block of first request,
$.ajax({
type: "POST",
url: Url.Details,
data: fileData,
async: false,
success: function (result) {
if (result == 0) {
toastr.error("Please pass user id");
} else {
$("#ReqId").val(result);
alert($("#ReqId").val());
uploader.uploadStoredFiles();
}
},
error: function (err) {
toastr.error("Not able to upload art details");
}
});
Here I want to pass RequestId header in onUpload event, but it's not working, What changes I need to make to make it happen.
The request option has a customHeaders property, that allows you to set any custom header.
Your constructor call should look something like
artistmanualuploader = new qq.FineUploader({
...
request: {
endpoint: "FoaUrl.AddEvaluationFiles",
customHeaders: {
"EvaluationRequestId": $("#CurrentEvaluationReqId").val()
}
},
...
});

Jquery-ui open dialog from js loop

I'm developing a web site with JQuery
I have encountered the following problem:
Going through an array in a loop, and every value is sent to a function that sends it to the server by Ajax.
On success a message is generated in JQuery- Dialog, in which buttons and button- functions are adjusted by the values returned from the server.
The problem is, that the JQuery-dialog is only triggered at the end of the loop, so I cannot tell which message refers to what value.
The loop func:
$('#List').find('option').map(function () {
semelO= $(this).val();
**getData**("Insert_hashala", "Inserthashala", false, "***setAlert***", false, "inserthasala", ["semelO", semelO], null, "RefershLendGrid", null);
});
The function signature:
function **getData**(procAlias, funcName, empytFields, ***onSuccessEvent***, isAsync, dataGroup, moreValues, onFailure, setDisplay, onFailureEvent)
The Ajax
jQuery.ajax({
type: "POST",
contentType: 'application/json',
dataType: "json",
url: "SvcSifria.asmx/" + funcName,
data: dataJsonString,
success: function (data) {
if (onSuccessEvent != undefined) eval(***onSuccessEvent*** + '(data)');
if (setDisplay != undefined) eval(setDisplay + '(data)');
},
async: isAsync
});
}
The Dialog function:
function ***setAlert***(data, error) {
myJson = jQuery.parseJSON(data.d);
text = data.d;
$("#dialog:ui-dialog").dialog("destroy");
$("#dialog-mess").dialog({
autoOpen: false,
modal: true, appendToBody: true,
buttons: [{
text: textButton,
id: "cancle",
click: function () {
$(this).dialog("close");
},text: textButton,
id: "ok",
click: function () {
getData("Insert_hashala", "Inserthashala", false, "setAlert", isAsync, "inserthasala", [returnValue, "true", "sumHashala", sumHashala, "semelOtek", semelOtek], null, "RefershLendGrid");
$(this).dialog("close");
}
}]
});
$("#ok").focus();
$("#dialog-mess").dialog("open");
}

Categories

Resources