I fail to upload pictures using formdata. This is my previous code which was working fine(This is just part of a form):
<div class="fileinput fileinput-new" data-provides="fileinput" style="width: 100%;">
<div class="fileinput-preview" data-trigger="fileinput" style="margin: 10px 0px;"></div>
<div>
<span class="btn btn-default btn-file">
<input type="file" id="filePicture" name="filePicture">
</span>
</div>
</div>
And this is my Ajax call:
$(document).on("click", "#sledBuckSaveBtn", function() {
event.preventDefault();
event.stopPropagation();
var fd = new FormData(document.getElementById("saveSledBuckForm1"));
$.ajax({
type: "POST",
url: "/SledBuck/EditFromSledTestDetails", //url,
data: fd,
processData: false, // tell jQuery not to process the data
contentType: false,
success: function (result) {
var title = "Error", msgtype = "error";
if (result) {
title = "Success";
msgtype = "success";
}
document.location.reload();
}
});
});
But my requirement has changed, I need to use Krajee plugin to create an input type:
Here my new code:
<div class="col-md-9">
<input id="input-#Model.PictureIdList[i]" type="file" class="file" data-show-upload="false" data-show-caption="true" data-input-id="#Model.PictureIdList[i]">
</div>
what problem am I facing. I think the reason is I might need to do configuration for Krajee plugin but I'm not sure. Any suggestions?
I just found the answer. I lacked the name of the file input. Just do like this and the file will be regconized:
<input id="input-#Model.PictureIdList[i]" name= "fileInput" type="file" class="file" data-show-upload="false" data-show-caption="true" data-input-id="#Model.PictureIdList[i]">
Related
I am creating an 'assign button' which calls a modal. In this modal will search a username queried from a database table. This autocomplete should be listed in the modal box, in fact it is not. I am using Jquery UI for this.
The "No search result" text is behind the modal, as well the assignee is listed behind the modal.
I am detailing my code in this jsfiddle
This is my original code:
$("#user_name").autocomplete({
source: function(request, response) {
$.ajax({
url: "https://dummyjson.com/products",
// url: "<?= site_url('Inventory/readuser'); ?>",
method: "get",
dataType: "json",
data: {
term: request.term
},
success: function(data) {
console.log("response --> ", data);
response(data); //callback fn
}
}) //ajax
console.log("ok");
}, //source
select: function(event, ui) {
$('[name="username"]').val(ui.item.username);
$('[name="role"]').val(ui.item.role);
$('[name="location"]').val(ui.item.location);
}
}); //#user_name
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="col-sm-3">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.13.2/jquery-ui.min.js" integrity="sha512-57oZ/vW8ANMjR/KQ6Be9v/+/h6bq9/l3f0Oc7vn6qMqyhvPd1cvKBRWWpzu0QoneImqr2SkmO4MSqU+RpHom3Q==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap#5.2.3/dist/css/bootstrap.min.css" integrity="sha384-rbsA2VBKQhggwzxH7pPCaAqO46MgnOM80zW1RWuH61DGLwZJEdK2Kadq2F9CUG65" crossorigin="anonymous">
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.2.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-kenU1KFdBIe4zVF0s0G1M5b4hcpxyD9F7jL+jjXkk+Q2h455rYXK/7HAuoJl+0I4" crossorigin="anonymous"></script>
<i class="bx bxs-filter-alt text-white-50"></i>Assign
</div>
<div class="modal fade" id="updateUser" tabindex="-1" aria-labelledby="updateUser" aria-hidden="true">
<div class="modal-dialog modal-dialog-sm modal-dialog-centered">
<div class="modal-content">
<div class="modal-header">
<h1 class="modal-title fs-5" id="exampleModalLabel">Assign user ...</h1>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
<fieldset class="border rounded-3 p-2">
<legend class="float-none w-auto px-2 small">type a user name</legend>
<div class="frmSearch">
<input type="text" class="form-control form-control-sm" id="user_name" name="user_name" size="20" maxlength="3">
<div id="suggesstion-box"></div>
</div>
</fieldset>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary btn-save-filter" data-bs-dismiss="modal">Cancel</button>
<button type="button" class="btn btn-primary btn-save-filter" data-bs-dismiss="modal">OK</button>
</div>
</div>
</div>
</div>
but in fiddle I am using dummy json from
https://dummyjson.com/docs/products
Please advise how to put the listed value into the green box in the modal.
Please review the following:
https://jsfiddle.net/Twisty/orv2j67n/1/
JavaScript
$("#user_name").autocomplete({
appendTo: "#suggestion-box",
source: function(request, response) {
$.ajax({
url: "https://dummyjson.com/products",
method: "get",
dataType: "json",
data: {
term: request.term
},
success: function(data) {
var results = $.map(data.products, function(v, i) {
v = $.extend(v, {
label: v.brand,
value: v.brand
});
return v;
});
console.log(results);
response(results);
}
});
console.log("ok");
},
select: function(event, ui) {
$('[name="label"]').val(ui.item.title);
}
});
Two changes to be aware of:
appendTo: "#suggestion-box",
Which element the menu should be appended to. When the value is null, the parents of the input field will be checked for a class of ui-front. If an element with the ui-front class is found, the menu will be appended to that element. Regardless of the value, if no element is found, the menu will be appended to the body.
I also added a $.map() in the Success. This ensure that the proper elements exist when passing the data back to response().
var results = $.map(data.products, function(v, i) {
v = $.extend(v, {
label: v.brand,
value: v.brand
});
return v;
});
console.log(results);
response(results);
This is discussed here: https://api.jqueryui.com/autocomplete/#option-source
An array of objects with label and value properties: [ { label: "Choice1", value: "value1" }, ... ]
I'm using tornado to build a web server and now I'm creating a login module. Here is the code:
<body>
<form id="uploadForm">
<div class="form-group">
<label for="exampleInputEmail1">Email address</label>
<input name="name" type="email" class="form-control" id="exampleInputEmail1" placeholder="Email">
</div>
<div class="form-group">
<label for="exampleInputPassword1">Password</label>
<input name="password" type="password" class="form-control" id="exampleInputPassword1" placeholder="Password">
</div>
<button id="submit" type="button" class="btn btn-default">Submit</button>
</form>
</body>
<script src="../js/plugins/jquery-3.2.1.min.js?v=c9f5aeeca3"></script>
<script src="../js/common/bootstrap.min.js?v=5869c96cc8"></script>
<script>
$(function(){
$('#submit').on('click',function(){
$.ajax({
url: 'http://www.example.com/login',
method: 'POST',
data: $('#uploadForm').serialize(),
contentType: false,
processData: false,
cache: false,
success: function(data) {
console.log(data);
if( data === 'ERROR'){
alert('login failed')
}else{
location.href = data;
}
},
error: function (jqXHR) {
alert('ERROR');
}
});
});
});
</script>
And the backend part:
class LoginHandler(tornado.web.RequestHandler):
def post(self, path):
try:
print(self.request.body)
name = self.get_body_argument("name")
except Exception as e:
print(e)
When I do a test, I can see that print(self.request.body) gives me the result: b'name=test&password=tttt' but after that I get an exception:
HTTP 400: Bad Request (Missing argument name)
name=test is just in the http body but why it tells me missing argument name?
Tornado only supports "application/x-www-form-urlencoded" and "multipart/form-data" as content type. So when we send a post request to the server, we must send the request with the right contentType. For example,
$.ajax({
url: 'http://www.example.com/login',
method: 'POST',
data: $('#uploadForm').serialize(),
contentType: 'application/x-www-form-urlencoded',
processData: false,
...
Also, we can neglect the contentType in ajax as 'application/x-www-form-urlencoded' is set by default.
Trying to finally change over to the 4.0 version of select2 and running into a problem.
All of this works perfectly fine on 3.5. On button click I open a bootstrap modal and load a remote page into it. I have tested all everything on a normal page (not in a modal) and it works correctly. When loaded in a modal as below the modal opens and everything like it always had for 3.5, but select2 is returning an error. I believe the issue here is the select2 is being loaded from a remote page... thing is this same remote loading method always worked flawlessly with 3.5.
TypeError: $(...).select2(...).select2(...) is undefined
js:
// show edit modal
$('#datatable2').on('click', '.dtEdit', function () {
var data = {
'filter_id': $(this).parents('tr').attr('id').replace('dtrow_', '')
};
$('#modal-ajax').load(
'/modals/m_filtering_applications_filters.php',
data,
function() {
$(this).modal('show');
changeSettings();
hourSelection();
}
);
});
// change filter modal confirmation
var changeSettings = function() {
// get the default filter
var default_filter = $("#filter_default").val();
//app list
$("#vedit-filter").select2({
placeholder: {
id: default_filter, // or whatever the placeholder value is
text: default_filter // the text to display as the placeholder
},
allowClear: true,
multiple: false,
tags: true,
createTag: function (query) {
return {
id: query.term,
text: query.term,
tag: true
}
},
ajax: {
dataType: 'json',
delay: 500,
type: 'post',
url: '/process/get_application_list.php',
data: function (params) {
return {
term: params.term, // search term
page: params.page, //page number
page_limit: 25, // page size
};
},
results: function (data, page) {
var more = (page * 25) < data.total; // whether or not there are more results available
return {
results: data.results,
more: more
};
}
}
}).select2('val', [default_filter]).on('change', function() {
$(this).valid();
});
}
m_filtering_applications_filters.php :
Just the contents of the modal which is loaded in :
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true"></button>
<h3 class="modal-title">Change these settings?</h3>
</div>
<form id="application-filters-edit">
<div class="modal-body">
<div class="row">
<div class="col-md-12">
<div class="row">
<div class="col-md-12 margin-bottom-30 form-group">
<div class="input-modal-group">
<label for="vedit-filter" class="f-14"><b>Application to filter :</b></label>
<select id="vedit-filter" name="settings[filter]" class="form-control select2">
<option value="<?php echo htmlspecialchars($result['filter'], ENT_QUOTES, 'UTF-8'); ?>" selected=""><?php echo htmlspecialchars($result['filter'], ENT_QUOTES, 'UTF-8'); ?></option>
</select>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<input type="hidden" name="settings[users][]" value="<?php echo $result['user_id']; ?>"/>
<input id="filter_default" type="hidden" name="settings[original]" value="<?php echo htmlspecialchars($result['filter'], ENT_QUOTES, 'UTF-8'); ?>"/>
<button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
<?php
if (!$result)
{
//disable the button
echo '<button type="button" class="btn btn-primary disabled" data-dismiss="modal"><i class="fa fa-check-circle"></i> Save Settings</button>';
}
else
{
// show the button
echo '<button class="btn btn-primary" type="submit"><i class="fa fa-check-circle"></i> Save Settings</button>';
}
?>
</div>
</form>
</div>
</div>
UPDATE:
Okay, the error is coming from :
}).select2('val', [default_filter]).on('change', function() {
$(this).valid();
});
attached to the end... this is for using the jquery validation script (I did not include this in the jS here), and again, worked fine in 3.5. Can you not add on to the select2() anymore with 4.0 or something?
When removing this line the error goes away, but the display of the select2 is very small in width and I cannot gain focus on the search box to enter any values so it is still unusable within the modal.
UPDATE2:
Realized the events changed with 4.0 so this seems to work :
}).on("change", function (e) {
$(this).valid();
});
Still cannot enter anything into the search box though. Also, I notice if I click on anything other than the arrow in the input box to show the dropdown it acts as if the mouse is being held down - it highlights all the text/content within the modal.
Solution : All the issues I was having with the select2 in my bs3 modal were solved by adding the following in my js :
$.fn.modal.Constructor.prototype.enforceFocus = $.noop;
The highlighting of content/text is gone. The focus on the search box is gone. For now everything seems to work great. I do not have any information as to what this line actually does at the moment, but will be researching this to find out and will add it back here for future reference for anyone.
I self admitted newbie, but I have a view with some code I pasted to provide a file upload. The function works but if the code is in, the "Save" button for the View that was already there stops working. If I had to guess it has something to do with the "HTML.BeginForm" line being there twice.
Here is the top of the view,
#model BrooksSOR.Models.dataOffender
#{
ViewBag.Title = "Edit";
}
<h2>Edit</h2>
<div >
<h2>Upload Files in MVC</h2>
<img src="#Model.Photograph" width="250" height="250" />*
#using (Html.BeginForm("FileUpload", "SOR",
FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<input name="uploadFile" type="file" />
<input type="submit" value="Upload File"/>
<input type="hidden" name="parmPersonID" value="#Model.PersonID" />
}
</div>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
<fieldset>
<legend>dataOffender</legend>
<p>
<input type="submit" value="Save" />
<input id="Details" type="button" value="Details" />
</p>
</fieldset>
Remove the #html.BeginForm
The script you would need to send for a file and some other fields with it.
//Purpose: Form Submit: SAVE Client
document.getElementById('frmPage').onsubmit = function (e) {
debugger;
var file = document.getElementById('fileToUpload').files[0];
var filename;
if (file) {
filename = file.name;
}
else {
filename = "";
}
$('#Image').val(filename);
var formObj = $(this);
var formURL = '#Url.Action("SaveMethod", "ControllerName")';
var formData = new FormData(this);
$.ajax({
url: formURL,
type: 'POST',
data: formData,
mimeType: "multipart/form-data",
contentType: false,
cache: false,
processData: false,
success: function (data, textStatus, jqXHR) {
debugger;
alert("Client saved successfully");
},
error: function (jqXHR, textStatus, errorThrown) {
}
});
e.preventDefault(); //Prevent Default action.
}
This is the design:
<div>
<form id="frmPage" class="form-horizontal">
<div class="form-body">
<div class="form-group">
<label id="lblImage" class="col-md-3 control-label">Upload File</label>
<div class="col-md-4">
<input type="file" id="fileToUpload" name="file" />
</div>
</div>
<div class="modal-footer" style="margin-top: 0px">
<div class="pull-right">
<button type="submit" id="btnSave" class="btn blue Save">Save</button>
</div>
</div>
</form>
</div>
Here: The btnSave is submit type, so it will submit that particular form. and form named frmPage will do the jquery script we added.
I have worked with knockout a little bit. It is a good client side data binding js library. A template is bound and populated on the client side as follows:
<h3>Are you sure you want to delete this?</h3>
<fieldset>
<legend>Delete</legend>
<div class="display-label">
Student Id
</div>
<div class="display-field">
<input data-bind="value: StudentId" />
</div>
<div class="display-label">
First Name
</div>
<div class="display-field">
<input data-bind="value: FirstName" />
</div>
<div class="display-label">
Last Name
</div>
<div class="display-field">
<input data-bind="value: LastName" />
</div>
<div class="display-label">
Age
</div>
<div class="display-field">
<input data-bind="value: Age" />
</div>
</fieldset>
the above way we write html to bind data
this way populate template by js code
$(function () {
ko.applyBindings(StudentListVM);
StudentListVM.getStudents();
});
//View Model
var StudentListVM = {
Students: ko.observableArray([]),
getStudents: function () {
var self = this;
$.ajax({
type: "GET",
url: '/Student/FetchStudents',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
self.Students(data); //Put the response in ObservableArray
},
error: function (err) {
alert(err.status + " : " + err.statusText);
}
});
},
};
self.editStudent = function (student) {
window.location.href = '/Student/Edit/' + student.StudentId;
};
self.deleteStudent = function (student) {
window.location.href = '/Student/Delete/' + student.StudentId;
};
//Model
function Students(data) {
this.StudentId = ko.observable(data.StudentId);
this.FirstName = ko.observable(data.FirstName);
this.LastName = ko.observable(data.LastName);
}
The above code works and generates the UI on the client side.
I would like to know if there is any scaffolding option in MVC which generates the above html with binding expression and also generates the required js view model.
If this does not exist then I would appreciate suggestions on how to achieve it.
Take a look on Knockout mvc
You can write appropriate #helper method
Don't forget about T4
you can write your own extension for HtmlHelper