Krajee Bootstrap fileinput how can i change the uploadExtraData dynamically - javascript

Hi Am using Krajee Bootstrap fileinput , i need to change the uploadExtraData dynamically on submitting the form. So i made it as a call back function. But it doesn't work for me. As i think uploadExtraData callback function work at on initialization only.
here is my code
$(".file-loading").fileinput({
uploadUrl: document.location.origin + "/discussions/add",
uploadAsync: false,
uploadExtraData:getFormData(),
});
function getFormData(){
var project_id = $("#DiscussionProjectId").val();
var discussion_title = $("#DiscussionDiscussionTitle").val();
var comment = $('#discussionComment').attr('value');
var data = {
project_id:project_id,
discussion_title:discussion_title,
comment:comment
};
return data;
}
Am doing to save the input files and data on form submit only.

I met the same problem with you,you can try this:
$(".file-loading").fileinput({
uploadUrl: document.location.origin + "/discussions/add",
uploadAsync: false,
uploadExtraData:function(previewId, index) {
var data = {
project_id : $("#DiscussionProjectId").val(),
discussion_title:$("#DiscussionDiscussionTitle").val(),
comment:$('#discussionComment').attr('value')
};
return data;
},
});

Its also possible to destroy the control and recreate it again
self.jqueryObjects.fileInput.fileinput('destroy');
self.jqueryObjects.fileInput.fileinput({
showCaption: false,
uploadUrl: self.urls.uploadDocument.replace(/<patient_id>/g, self.selectedPatient.id),
allowedFileExtensions: ["txt"]
});

Related

How to update data row in datatables

I want to get value from the database and showing to the datatables with a condition, and if I change input form value (This input value is a condition for query so if i change the value the data in the datatable will change) but when i use on change it's work but when i try twice to change value they say i reinitialise, any suggestion to make it right?
I already try to that code, it's work but if i change the value again it's error says 'DataTables warning: table id=dataTr - Cannot reinitialise DataTable. For more information about this error, please see http://datatables.net/tn/3
var asset = $('#formasset').find('input[name="ckdasset"]').val();
$(document).ready(function() {
$('#ckdasset').on('change',function(){
var dataTable = $('#dataTr').DataTable( {
"processing": true,
"ajax":{
url :"<?php echo base_url();?>index.php/Logged/get_detail_data/"+kode_asset_new+",
type: "post", // method , by default get
error: function(){ // error handling
$(".employee-grid-error").html("");
$("#dataTr").append('<tbody class="employee-grid-error"><tr><th colspan="3">No data found in the server</th></tr></tbody>');
$("#employee-grid_processing").css("display","none");
}
}
} );
});
} );
Try this, You're initializing the datatable again instead of reset/redraw.
var asset = $('#formasset').find('input[name="ckdasset"]').val();
$(document).ready(function () {
var dataTable = $('#dataTr').DataTable({
"processing": true,
"ajax": {
url: "<?php echo base_url();?>index.php/Logged/get_detail_data/" + kode_asset_new + ",
type: "post", // method , by default get
error: function () { // error handling
$(".employee-grid-error").html("");
$("#dataTr").append('<tbody class="employee-grid-error"><tr><th colspan="3">No data found in the server</th></tr></tbody>');
$("#employee-grid_processing").css("display", "none");
}
}
});
$('#ckdasset').on('change', function () {
var Dt = $('#dataTr').DataTable();
Dt.fnDraw();
});
});

Issue with setting value to select dropdown in MVC

I am using MVC.
I am having two drop down and one change of 'primaryspec' the 'primarysubspec' should get loaded.
Everything is working fine for passing values to controller and it got saved to DB.
When I am trying to retrieve the saved details,'primarysubspec' saved values are not getting displayed.
But displaying save data for 'primarySpec'.
Here is my .cshtml code:
#Html.DropDownListFor(m => m.PSpec, Model.PSpec, new { id = "ddUserSpec", style = "width:245px;height:25px;", data_bind = "event: {change: primaryChanged}" }, Model.IsReadOnly)
#Html.DropDownListFor(m => m.PSubspec, Model.PSubspec, new { id = "ddUserSubSpec", style = "width:245px;height:25px;", data_bind = "options: primarySubSpec,optionsText: 'Name',optionsValue: 'Id'" }, Model.IsReadOnly)
Here is my JS Code to retrieve the values for :
this.primarySubSpec = ko.observableArray([]);
this.primarySpecChanged = function () {
var val = $("#ddetailsPrimarySpec").val();
primarySubStartIndex = 0;
primarySubSpecialityUrl = '/PlatformUser/GetSpecandSubSpec?primarySpe=' + val+//model.primarySpecID() +'&secondarySpec=';
loadPrimarySubSpec();
};
function loadPrimarySubSpec() {
$.ajax({
type: 'GET',
url: primarySubSpecUrl,
contentType: 'application/json; charset=utf-8',
dataType: 'json',
processdata: false,
cache: false,
success: function (data) {
primarySubSpec = [];
model.primarySubspec('0');
try {
if (data.length == 0) {
primarySubSpeacId.empty();
}
model.primarySubSpec(data);
},
error: function (request, status, error) {
primarySubSpeacId.prop("disabled", true);
}
});
}
Everything is working fine,but facing issue only while displaying the saved values from the DB.
Showing fine for 'primarySpec'
The values showing empty for 'PrimarySubSpec' instead of saved values in dropdown.
Please let me know what is the issue how can i show the saved value as selected value in 'primarySubSpec'dropdown.
The Problem:
when you load the page to view saved values, the change event is never called.
Why:
When your page is loaded with saved values, the select box has the saved value selected before knockout knows anything about it. Hens the change event isn't called.
Simplest solution:
change the primarySpecilaityChanged as follows
this.primarySpecilaityChanged = function () {
var val = $("#ddUserDetailsPrimarySpeciality").val();
if(val){
primarySubStartIndex = 0;
primarySubSpecialityUrl = '/' + NMCApp.getVirtualDirectoryName() + '/PlatformUser/GetSpecialitiesandSubSpecilaities?primarySpeciality=' + val+//model.primarySpecialityUID() +'&secondarySpeciality=';
loadPrimarySubSpecilaities();
}
};
then call primarySpecilaityChanged function after you call ko.applyBindings.
var viewModel = new YourViewModel();
ko.applyBindings(viewModel);
viewModel.primarySpecilaityChanged();

jQuery File Upload in Rails 4.x Nested Form

I have a Horse model and a Photo model. I am using jQuery File Upload to resize (client side) images and save on Amazon s3 directly since I am using Heroku.
I have seen other questions similar that use carrierwave, paperclip, or that are very old. I am not sure why you would use carrierwave/paperclip, but I think based on what heroku says, I do not want to have images hitting the server potentially causing time-outs.
Heroku recommends using jQuery File Upload and shows js appending new file input with a value of the image's link (returned from amazon s3). I have this working when saving a photo separately. I now want to make it work in a nested form for Horse but js is not finding input (since it does not exist yet because it's nested I presume).
I am using Cocoon for nested forms (I am open to anything that will work better). I am not too familiar with javascript/jQuery but a far as I can tell, Cocoon 'hides' the nested element until I click to add it via the add_association.
haml view code:
= link_to_add_association 'add photo', f, :photos
html source before clicking 'add photo'
<div class='links'>
<a class="btn btn-default btn-sm add_fields" data-association-insertion-method="after" data-association="photo" data-associations="photos" data-association-insertion-template="<div class='nested-fields'>
<fieldset class="inputs"><ol><input type="file" name="horse[photos_attributes][new_photos][url]" id="horse_photos_attributes_new_photos_url" />
<input type="hidden" name="horse[photos_attributes][new_photos][_destroy]" id="horse_photos_attributes_new_photos__destroy" value="false" /><a class="remove_fields dynamic" href="#">remove photo</a>
</ol></fieldset>
</div>
" href="#">add photo</a>
How do I work with this input and how do I handle multiple file uploads as they are added correctly?
My current upload js:
$(function() {
if ($('#new_horse').length > 0) {
$.get( "/presign", function( s3params ) {
$('.direct-upload').find("input:file").each(function(i, elem) {
var fileInput = $(elem);
var form = $(fileInput.parents('form:first'));
var submitButton = form.find('input[type="submit"]');
var progressBar = $("<div class='bar'></div>");
var barContainer = $("<div class='progress'></div>").append(progressBar);
fileInput.fileupload({
fileInput: fileInput,
url: "http://" + s3params.url.host,
type: 'POST',
autoUpload: true,
formData: s3params.fields,
paramName: 'file', // S3 does not like nested name fields i.e. name="user[avatar_url]"
dataType: 'XML', // S3 returns XML if success_action_status is set to 201
disableImageResize: false,
imageQuality: 0.5,
disableImageResize: /Android(?!.*Chrome)|Opera/
.test(window.navigator && navigator.userAgent),
imageMaxWidth: 500,
imageMaxHeight: 1000,
imageOrientation: true, //auto rotates images
acceptFileTypes: /(\.|\/)(gif|jpe?g|png)$/i, //I added this to jquery.fileupload-validate: alert('Must Be JPG GIF or PNG Image')
replaceFileInput: false,
progressall: function (e, data) {
var progress = parseInt(data.loaded / data.total * 100, 10);
progressBar.css('width', progress + '%')
},
start: function (e) {
submitButton.prop('disabled', true);
fileInput.after(barContainer);
progressBar.
css('background', 'green').
css('display', 'block').
css('width', '0%').
text("Loading...");
},
done: function(e, data) {
submitButton.prop('disabled', false);
progressBar.text("Pre-uploading done... Please Save or Cancel");
// extract key and generate URL from response
var key = $(data.jqXHR.responseXML).find("Key").text();
var url = 'https://' + s3params.url.host +'/' + key;
// remove first input to prevent phantom upload delay
fileInput.remove();
// create new hidden input with image url
var input = $("<input />", { type:'hidden', name: fileInput.attr('name'), value: url })
var imgPreview = '<img src="' + url + '">';
form.append(input);
form.append(imgPreview);
},
fail: function(e, data) {
submitButton.prop('disabled', false);
progressBar.
css("background", "red").
text("Failed");
}
});
});
}, 'json');
}
});
I guess I should have looked at cocoon documentation first:
http://www.rubydoc.info/gems/cocoon#Callbacks__upon_insert_and_remove_of_items_
http://www.rubydoc.info/gems/cocoon/1.2.6
I modified my upload.js file to the following and it worked for multiple files in nested forms perfectly:
// added for file uploading
// https://devcenter.heroku.com/articles/direct-to-s3-image-uploads-in-rails
// Get our s3params from our endpoint
$(document).on('ready page:load', function () {
$('.direct-upload')
.on('cocoon:after-insert', function(e, photo) {
console.log('inside cocoon image function');
$.get( "/presign", function( s3params ) {
$('.direct-upload').find("input:file").each(function(i, elem) {
console.log('inside nested-fields photo input form');
var fileInput = $(elem);
var form = $(fileInput.parents('form:first'));
var submitButton = form.find('input[type="submit"]');
var progressBar = $("<div class='bar'></div>");
var barContainer = $("<div class='progress'></div>").append(progressBar);
fileInput.fileupload({
fileInput: fileInput,
url: "http://" + s3params.url.host,
type: 'POST',
autoUpload: true,
formData: s3params.fields,
paramName: 'file', // S3 does not like nested name fields i.e. name="user[avatar_url]"
dataType: 'XML', // S3 returns XML if success_action_status is set to 201
disableImageResize: false,
imageQuality: 0.5,
disableImageResize: /Android(?!.*Chrome)|Opera/
.test(window.navigator && navigator.userAgent),
imageMaxWidth: 500,
imageMaxHeight: 1000,
imageOrientation: true, //auto rotates images
acceptFileTypes: /(\.|\/)(gif|jpe?g|png)$/i, //I added this to jquery.fileupload-validate: alert('Must Be JPG GIF or PNG Image')
replaceFileInput: false,
previewMaxWidth: 100,
previewMaxHeight: 100,
previewCrop: true,
progressall: function (e, data) {
var progress = parseInt(data.loaded / data.total * 100, 10);
progressBar.css('width', progress + '%')
},
start: function (e) {
submitButton.prop('disabled', true);
fileInput.after(barContainer);
progressBar.
css('background', 'green').
css('display', 'block').
css('width', '0%').
text("Loading...");
},
done: function(e, data) {
submitButton.prop('disabled', false);
progressBar.text("Photo Uploaded");
// extract key and generate URL from response
var key = $(data.jqXHR.responseXML).find("Key").text();
var url = 'https://' + s3params.url.host +'/' + key;
// remove first input to prevent phantom upload delay
fileInput.remove();
// create new hidden input with image url
var input = $("<input />", { type:'hidden', name: fileInput.attr('name'), value: url })
var imgPreview = '<img src="' + url + '">';
form.append(input);
form.append(imgPreview);
},
fail: function(e, data) {
submitButton.prop('disabled', false);
progressBar.
css("background", "red").
text("Failed");
}
}, 'json'); //fileupload
}); //each file
}); //presign call
}); // function cocoon
}); // page ready
I guess Google and a well documented gem can replace knowledge of JS in the short term :-) I am sure it's not at tight as it could be so please offer any improvements.

Liferay JavaScript Function is not defined

I am new to liferay and I have been trying to do Ajax but my script does not load inside the browser. I also tested it by inserting a simple alert.
I've been getting the "function is not defined" error.
Below is my liferay aui script:
Liferay.provide(window,'refreshFunction',
function(param){
alert('param: ' + param);
A.one('#divToBeRefreshed').plug(A.LoadingMask);
var mask = A.one('#divToBeRefreshed').loadingmask;
mask.show();
var dTime = new Date();
var dynamicURL = '<%=resourceURL %>&t=' + dTime.getTime().toString();
A.io.request(dynamicURL, {
method: 'GET',
cache: false,
data : {
param: param
},
on: {
success: function(event, id, obj) {
var response = this.get('responseData');
mask.hide();
$('#divToBeRefreshed').html(response);
},
fail: function(event, id, obj) {
mask.hide();
}
}
});
},
['aui-base']
); </aui:script>
Is there something wrong in my script? what might be the problem? HELP!
Your script should be wrapped in
;(function(A, Liferay) {
<<your script>>
}
This will allow the use of A and Liferay. you can remove <aui:script>
in tag of popup add
onclick="window.parent.MyFunctionInPageParents()"

replacing select box dynamically inside of a div

I want replace the select box inside of the div
<div class="models">
<select disabled="disable">
<option>Model Name</option>
</select>
</div>
I'm trying to target the div and load the select box like this
jQuery('.models select').change(function() {
var model = jQuery('.models option:selected').text();
I'm not getting any action on change though
http://jsfiddle.net/HNgKt/
Simple change: bind your change event handler to the container div (which should be present when this executes) and get the text value from that:
jQuery('.models').on('change','select',function() {
var model = jQuery(':selected',this).text();
var modelValue = jQuery(':selected',this).val();
});
Note: your fiddle and markup has it diabled, of course it would need to be enabled first, something like:
jQuery('.models>select').prop('disabled',false);
EDIT: Using your fiddle, I mashed around, commented out your load - as it does not work there and the cleanstring, not present, and this works:
jQuery('.brands').change(function () {
alert('here');
var brand = jQuery('.brands option:selected').text();
// brand = cleanString(brand);
//jQuery('.models').load('/pf-models #' + brand);
jQuery('.models>select').append('<option >She is a classic</option>').prop('disabled', false);
});
alert(jQuery('.models>select').prop('disabled'));
jQuery('.models').on('change', 'select', function () {
var model = jQuery(":selected", this).text();
alert(model);
model = cleanString(model);
jQuery('#show-models').load('/pf-urls #' + model);
});
updated fiddle: http://jsfiddle.net/HNgKt/6/
EDIT Further detailed example, still based on the valid markup assumptions coming back from the load on the first part which I have substituted for a html replace since we have not access to that part:
jQuery('.brands').change(function () {
var brand = jQuery('.brands option:selected').text();
$('.models').html('<select class="models"><option >' + brand + ' She is a classic</option><option>clunker</option></select>');
});
jQuery('.models').on('change', 'select', function () {
var model = jQuery(":selected", this).text();
alert('model:' + model);
});
Fiddle for that: http://jsfiddle.net/HNgKt/7/
Alerts the model if you choose a brand, then a model.
Try following steps,
on change of brands list make an ajax call and make sure in result you recieve the new list options or you can dynamically prepare the options list in jquery also.
And on success of call repopulate new list with the received data.
jQuery('.brands').change(function() {
var brand = jQuery('.brands option:selected').text();
brand = JSON.stringify(cleanString(brand));
$.ajax({
type: "GET", //GET or POST or PUT or DELETE verb
url: ajaxUrl, // Location of the service
data: brand , //Data sent to server
contentType: "", // content type sent to server
dataType: "json", //Expected data format from server
processdata: true, //True or False
success: function (data) {//On Successful service call
var $newList = $(".models select'").empty();
$newList.append(data);
},
error: function(){} // When Service call fails
});
});
Try the following:
/* using delegate version of .on */
jQuery(document).on('change', '.brands', function() {
var brand = jQuery('.brands option:selected').text();
brand = cleanString(brand);
jQuery('.models').load('/pf-models #' + brand);
});
jQuery(document).on('change', '.models select', function() {
var model = jQuery('.models option:selected').text();
model = cleanString(model);
jQuery('#show-models').load('/pf-urls #' + model);
});
For dealing with "dynamic" elements, you want to use delegate to assign action. This basically reserves a method to be assigned to all elements who match the description.
See also:
http://api.jquery.com/delegate/
http://api.jquery.com/on/#direct-and-delegated-events

Categories

Resources