How to upload image in jQuery jTable - jquery-jtable

I successfully created an upload field in create mode in jQuery jTable as follows:
upload: {
title: 'Upload Image',
input: function (data) {
return '<input type="file" name="file">';
'<input type="submit" value="Submit" id="submitBtn" />';
},
},
I am able to successfully display the browse button and select files. I am unable to submit the form:
Error: newcourse.php' not found or unable to stat.
with the same file name in which the code is.
I am at a dead end. Where will the file be uploaded to? In the same directory?
How to do it in jTable ? Can it be done using ajax ? If so, how to proceed? jTable documentation is very poor.

I finally found a soluton to upload files on jTable
Now with the version of jtable 2.4.0 (the most recent at the moment writing this post)
on your file.js add the following methods:
// Read a page's GET URL variables and return them as an associative array.
function getVars(url)
{
var formData = new FormData();
var split;
$.each(url.split("&"), function(key, value) {
split = value.split("=");
formData.append(split[0], decodeURIComponent(split[1].replace(/\+/g, " ")));
});
return formData;
}
// Variable to store your files
var files;
$( document ).delegate('#input-image','change', prepareUpload);
// Grab the files and set them to our variable
function prepareUpload(event)
{
files = event.target.files;
}
//The actions for your table:
$('#table-container').jtable({
actions: {
listAction: 'backoffice/catalogs/display',
deleteAction: 'backoffice/catalogs/delete',
createAction: function (postData) {
var formData = getVars(postData);
if($('#input-image').val() !== ""){
formData.append("userfile", $('#input-image').get(0).files[0]);
}
return $.Deferred(function ($dfd) {
$.ajax({
url: 'backoffice/catalogs/update',
type: 'POST',
dataType: 'json',
data: formData,
processData: false, // Don't process the files
contentType: false, // Set content type to false as jQuery will tell the server its a query string request
success: function (data) {
$dfd.resolve(data);
$('#table-container').jtable('load');
},
error: function () {
$dfd.reject();
}
});
});
},
updateAction: function (postData) {
var formData = getVars(postData);
if($('#input-image').val() !== ""){
formData.append("userfile", $('#input-image').get(0).files[0]);
}
return $.Deferred(function ($dfd) {
$.ajax({
url: 'backoffice/catalogs/update',
type: 'POST',
dataType: 'json',
data: formData,
processData: false, // Don't process the files
contentType: false, // Set content type to false as jQuery will tell the server its a query string request
success: function (data) {
$dfd.resolve(data);
$('#table-container').jtable('load');
},
error: function () {
$dfd.reject();
}
});
});
},
// Now for the fields:
fields: {
id_catalog: {
key: true,
create: false,
edit: false,
list: false
},
thumb_url: {
title: 'Image',
type: 'file',
create: false,
edit: true,
list: true,
display: function(data){
return '<img src="' + data.record.thumb_url + '" width="150" height="207" class="preview">';
},
input: function(data){
return '<img src="' + data.record.thumb_url + '" width="150" height="207" class="preview">';
},
width: "150",
listClass: "class-row-center"
},
image: {
title: 'Select File',
list: false,
create: true,
input: function(data) {
html = '<input type ="file" id="input-image" name="userfile" accept="image/*" />';
return html;
}
}
}
});
Now, you are able to process the files on your server side.
That's all folks.

Hello shels
I lost a lot of time to searching of a solution of this issue. I read a many articles and found that this solution working for me fine:
actions: {
 listAction: 'modules_data.php?action=list',
deleteAction: 'modules_data.php?action=delete',
updateAction: 'modules_data.php?action=update',
createAction: 'modules_data.php?action=create'
},
...
image_file: {
title: 'Album cover',
list: true,
create: true,
edit: true,
input: function(data) {
return '<form target="iframeTarget" class="formUploadFile" action="file_upload.php" method="post" enctype="multipart/form-data"> <input type="file" onchange="this.form.submit()" name="myFile"/> </form> <iframe class="upload-iframe" style="display: none;" src="#" name="iframeTarget"></iframe>';
}
},
image: {
title: 'Album cover',
list: true,
create: true,
edit: true,
input: function(data) {
html = '<input type ="hidden" id="image" name="image" />';
return html;
}
},
....
How to capture submit response in a form created dynamically?
So you can capture submit event using:
...
formSubmitting: function(event, data) {
filename = $('input[type=file]').val().split('\\').pop();
($("#" + data.form.attr("id")).find('input[name="image"]').val(filename));
},
And save data to the server side script.
I think, it's a good solution and hope will be helpful.
Best Regards
Kameliya

console.log not working for FormData. Use instead
for (var data of formData) {
console.log(data);
}

Related

Why is displayStart (Datatable 1.10) not working for me?

I am using Datable (1.10.3) and whatever value I set in the diplayStart field, the start parameter of the server request always goes as 0.
Here is my code:
this.table = $('#table').DataTable({
displayStart: 100,
order: [[0, 'desc']],
processing: true,
serverSide: true,
searching: true,
pageLength: 50,
searchDelay: 1000,
language: {
lengthMenu: 'Show _MENU_ records per page'
},
dom: '<"top"il>rt<"bottom"p><"clear">',
ajax: {
url: <url>,
type: 'POST',
headers: {
authorization: <token>
},
data: function (d) {
//setting request data
},
dataSrc: (json) =>{
return json.data;
},
error: function (xhr, error, thrown) {
if (xhr.status + '' === '401') {
location.href = '/';
}
}
},
columns: this.getColumns(),
drawCallback: function () {
//some operations
}
});
It seems to work fine if I initialise the table like the older version, like this:
this.table = $('#table').dataTable({...
But this initialisation breaks other preexisting function calls (like search and row) in the code.
Can anyone suggest where I am going wrong and how can I fix this?
I am not sure if displayStart works with server side.
I realize this is not an ideal solution if you dont find any other you can override the pipeline method forcing it to use whatever you want:
$.fn.dataTable.pipeline = function ( opts ) {
return function ( request, drawCallback, settings ) {
request.start = 20;
return $.ajax( {
"type": opts.method,
"url": opts.url,
"data": request,
"dataType": "json",
"success": drawCallback
} );
}
};
Taken the example from: https://datatables.net/examples/server_side/pipeline.html

Displaying Block and floor and Room on single page using asp.net mvc

I am a beginner in asp.net MVC
I have tblBlock,tblFloor,tblRoom table in my database. I want to display all these in a single page like when I click Block number it should show the list of the floor and when I click on floor number it should show the number of rooms. how to do this within a single page in asp.net MVC.
This my view code
function GetFloors() {
$("#tblFloor tbody tr").remove();
console.log("Hello Javascript");
$.ajax({
type: "GET",
//url: "/RoomBooking/GetFloors",
url: '#Url.Action("GetFloors","RoomBooking")',
dataType: "json",
//cache: false,
async: "false",
contenttype:"charset=utf-8",
success: function (data) {
$.each(data, function (i, item) {
var rows = ""
+ ""
+ ' tblFloor ' + item.Floor_No + ""
+ "";
$('#tblFloor tbody').append(rows);
});
},
});
//Prevent default behavior
return false;
}
This is my controller
[HttpGet]
public JsonResult GetFloors()
{
List<tblFloor> floors = new List<tblFloor>();
floors = BlockRepsitory.GetFloors(1).ToList();
return Json(floors, JsonRequestBehavior.AllowGet);
}
Finally, I got a solution to this problem below is code for that solution:
<script>
$(document).ready(function () {
loadData();
});
function loadData() {
$.ajax({
url: "/PeopleBooking/Blocklist",
type: "GET",
contentType: "application/json;charset=utf-8",
dataType: "json",
success: function (result) {
var html = '';
$.each(result, function (key, item) {
html += '<div class="col-md-3 col-lg-3 col-xl-2 "><section class="panel panel-featured-left panel-featured-primary "><div class="panel-body zoom"><div class="widget-summary"><div class="widget-summary-col widget-summary-col-icon"><div class="summary-icon bg-white"><img src="/assets/images/RoomImg/block.png" width = "150" height = "150" class="img-circle img-responsive"/></div></div><div class="widget-summary-col"><div class="summary"><h4 class="title">' + item.Block_name + '</h4><div class="info"><strong class="amount">' + item.Block_No + '</strong></div></div></div></div></div></div></section></div>';
});
$('#yes').html(html);
},
error: function (errormessage) {
alert(errormessage.responseText);
}
});
}
</script>

Cannot Get Typeahead.js Working with MVC 5 Over Remote

I have no idea what I'm doing wrong, but I cannot get typeahead working in my MVC 5 application. I installed everything via NuGet and my view includes #Scripts.Render("~/bundles/typeahead"), which is rendering properly when viewing the source of the view. So the issue isn't that the dependencies are missing.
I am not seeing any drop down appear when I start typing, and using Fiddler I do not see any calls being made out to the remote that I setup that pulls the data.
Here's the line in my view that typeahead is being attached:
#Html.TextBoxFor(m => m.MainInfo.CompanyName,
new { #class = "form-control typeahead", id = "comp-name", autocomplete="off" })
Here's the portion of my script that configures typeahead and bloodhound:
$(document).ready(function() {
var clients = new Bloodhound({
datumTokenizer: function (datum) {
return Bloodhound.tokenizers.whitespace(datum.value);
},
queryTokenizer: Bloodhound.tokenizers.whitespace,
remote: {
url: "/info/client?like=%QUERY",
wildcard: '%QUERY',
filter: function (clients) {
return $.map(clients, function (client) {
return {
value: client.Name,
clientId: client.Identifier
};
});
}
}
});
clients.initialize();
$('#comp-name').typeahead(null,
{
display: 'value',
minLength: 1,
source: clients.ttAdapter(),
templates: {
empty: "Looks like a new client...",
suggestion: Handlebars.compile("<p><b>{{value}}</b> - {{clientId}}</p>")
}
});
});
Is there something that I've configured wrong in my javascript? I've used a few tutorials as well as their own documentation, but I cannot figure out what I'm doing wrong here. It almost feels like it's not properly initialized, but there are no errors being thrown.
NOTE: Just as an FYI I'm using Bootstrap 3 as well in case that changes anything.
EDIT: Here's my #section Scripts:
#Scripts.Render("~/bundles/jqueryval")
#Scripts.Render("~/bundles/typeahead")
<script src="#Url.Content("~/Scripts/handlebars.min.js")"></script>
<script src="#Url.Content("~/Scripts/ProjectSetupFormScripts.js")"></script> <-- this is where typeahead is set up
This did the trick for me:
JS
#section Scripts {
<script type="text/javascript">
$(function () {
SetupTipeahead();
});
function SetupTipeahead() {
var engine = new Bloodhound({
remote: {
url: '/Employees/AllEmployees',
ajax: {
type: 'GET'
}
},
datumTokenizer: function (d) {
return Bloodhound.tokenizers.whitespace(d.FullName);
},
queryTokenizer: Bloodhound.tokenizers.whitespace
});
engine.initialize();
$('#FullName').typeahead(null, {
displayKey: 'FullName',
source: engine.ttAdapter(),
templates: {
empty: [
'<div class="empty-message">',
'No match',
'</div>'
].join('\n'),
suggestion: function (data) {
return '<p class="">' + data.FullName + '</p><p class="">' + data.ManNumber + '</p>';
}
}
});
}
</script>
EmployeesController has the following JsonResult
public JsonResult AllEmployees()
{
return Json(db.Employees.ToList(),JsonRequestBehavior.AllowGet);
}
Hello try to wrap your script in #section scripts {} this will place the script at the bottom just before the </body> tag and make sure you are not calling the function before your bundles load.
#section scripts {
<script>
$(document).ready(function() {
var clients = new Bloodhound({
datumTokenizer: function (datum) {
return Bloodhound.tokenizers.whitespace(datum.value);
},
queryTokenizer: Bloodhound.tokenizers.whitespace,
remote: {
url: "/info/client?like=%QUERY",
wildcard: '%QUERY',
filter: function (clients) {
return $.map(clients, function (client) {
return {
value: client.Name,
clientId: client.Identifier
};
});
}
}
});
clients.initialize();
$('#comp-name').typeahead(null,
{
display: 'value',
minLength: 1,
source: clients.ttAdapter(),
templates: {
empty: "Looks like a new client...",
suggestion: Handlebars.compile("<p><b>{{value}}</b> - {{clientId}}</p>")
}
});
});
</script>
}

Jade returning error with Unexpected token {

I keep getting an error around line 18-19 (in this case the dayClick line) saying:
Unexpected token {
at Function (native)
at assertExpression (C:\websites\timeoffcalendar\node_modules\jade\lib\lexer.js:30:33)
at Object.Lexer.conditional (C:\websites\timeoffcalendar\node_modules\jade\lib\lexer.js:509:11)
at Object.Lexer.next (C:\websites\timeoffcalendar\node_modules\jade\lib\lexer.js:914:15)
at Object.Lexer.lookahead (C:\websites\timeoffcalendar\node_modules\jade\lib\lexer.js:113:46)
at Parser.lookahead (C:\websites\timeoffcalendar\node_modules\jade\lib\parser.js:102:23)
at Parser.peek (C:\websites\timeoffcalendar\node_modules\jade\lib\parser.js:79:17)
at Parser.block (C:\websites\timeoffcalendar\node_modules\jade\lib\parser.js:704:30)
at Parser.tag (C:\websites\timeoffcalendar\node_modules\jade\lib\parser.js:817:24)
at Parser.parseTag (C:\websites\timeoffcalendar\node_modules\jade\lib\parser.js:738:17)
at Parser.parseExpr (C:\websites\timeoffcalendar\node_modules\jade\lib\parser.js:211:21)
at Parser.block (C:\websites\timeoffcalendar\node_modules\jade\lib\parser.js:708:25)
at Parser.tag (C:\websites\timeoffcalendar\node_modules\jade\lib\parser.js:817:24)
at Parser.parseTag (C:\websites\timeoffcalendar\node_modules\jade\lib\parser.js:738:17)
at Parser.parseExpr (C:\websites\timeoffcalendar\node_modules\jade\lib\parser.js:211:21)
at Parser.block (C:\websites\timeoffcalendar\node_modules\jade\lib\parser.js:708:25)
block content
script.
$(document).ready(function() {
// page is now ready, initialize the calendar...
$('#calendar').fullCalendar({
eventSources: [
{url: '/getevents'},
{url: "/javascripts/Holidays.json"},
],
header: {
left: 'prev,next today',
center: 'title',
right: 'month,agendaWeek,agendaDay'
},
editable: true,
dayClick: function(date, jsEvent, view) {
$('#calendar').fullCalendar('changeView', 'agendaDay');
$('#calendar').fullCalendar('gotoDate', date);
},
eventClick: function(event, jsEvent, view) {
$('#editModalTitle').html(event.title);
if(Cookies.get("fullAdmin") != "undefined"){
var sdate = event.start.format().split("T")[0];
var stime = event.start.format().split("T")[1];
var edate = event.end.format().split("T")[0];
var etime = event.end.format().split("T")[1];
$("#startday").val(sdate);
$("#starttime").val(stime);
$("#endday").val(edate);
$("#endtime").val(etime);
} else {
$('#startDate').html("Start date: "+event.start.format());
$('#endDate').html(" End Date: "+event.end.format());
}
$('#dayoffid').val(event.id);
$('#fullCalModal').modal();
return false;
}
});
if(Cookies.get("date") != "undefined"){
$('#calendar').fullCalendar('gotoDate', Cookies.get("date"));
Cookies.remove("date");
}
$('#allday').change(function() {
if(document.getElementById('allday').checked == true) {
$('#starttime').val("09:00:00");
$('#endtime').val("17:00:00");
}
});
$('#startday').change(function () {
$('#endday').val($('#startday').val());
});
$('#saveevent').click(function(){
$.ajax({
type: "POST",
url: "/calendar/"+$('#startday').val()+"/"+$('#starttime').val()+"/"+$('#endday').val()+"/"+$('#endtime').val()+"/"+$('#typeoptions').val()+"/"+$('#useroptions').val()
}).success(function(msg){
window.location.reload();
});
});
$('#updateEvent').click(function(){
$.ajax({
type: "PUT",
url: "/calendar/"+$('#startday').val()+"/"+$('#starttime').val()+"/"+$('#endday').val()+"/"+$('#endtime').val()+"/"+$('#typeoptions').val()+"/"+$('#useroptions').val()
}).success(function(msg){
window.location.reload();
});
});
$('#addEvent').click(function(){
$('#createModalTitle').html("Book a day off!");
$('#inputCalModal').modal();
return false;
});
$('#removeEvent').click(function() {
if(confirm("Are you sure you want to delete the event?")) {
$.ajax({
type: "DELETE",
url: "/calendar/"+$('#dayoffid').val()
}).success(function(msg){
window.location.reload();
});
}
});
});
I don't think there is a problem with your jade template, i tried it out on this site with this code..
doctype html
html(lang="en")
head
title= pageTitle
body
block content
script.
$(document).ready(function() {
// page is now ready, initialize the calendar...
//And the rest of your script
});
and it produced valid html with no errors

Error "Object does not support property or method 'selectize'" on selectize initialization

i'm triyng to use this code
$(this.node).find("select").selectize({
valueField: "value",
labelField: "label",
searchField: ["label"],
maxOptions: 10,
create: false,
render: {
option: function (item, escape) {
return "<div>" + escape(item.label) + "</div>";
}
},
load: function (query, callback) {
if (!query.length) return callback();
$.ajax({
url: "../ajaxPage.aspx?functionName=GET_03&fieldValue=" + encodeURIComponent(query),
type: "POST",
dataType: "json",
data: {
maxresults: 10
},
error: function () {
callback();
},
success: function (res) {
console.log(res);
callback(res);
}
});
}
});
$(this.node).find("select") is a simple select:
<select name="tagName" id="tagId"></select>
I include this js in my page:
microplugin.min.js
sifter.min.js
selectize.js
selectize.default.css
but when i use .selectize i get this error at runtime:
"Object does not support this property or method selectize"
Any idea about this error?
yes... i'm using jQuery.
I load dependencies in this order:
microplugin.min.js
sifter.min.js
selectize.js
selectize.default.css
do you think is this the wrong order?
You may have to include the css before all the js files.
selectize.default.css
microplugin.min.js
sifter.min.js
selectize.js

Resources