I have upload file excel function that run normally in Websphere server 8.5 with JAX-RS 1.1. But when I update to Websphere 9.0 using JAX_RS 2.0, I cannot use #FormParam to upload file, I tried using #MultiPart to replace but it can read .csv file right only, with .xls and .xlsx file it create wrong temp file, so HSSFWorkbook of Apache Poi cannot read inputstream of file normally.
This is my code:
Controller:
#POST
#Path("class/import")
#Consumes(MediaType.MULTIPART_FORM_DATA)
#Produces(MediaType.APPLICATION_JSON)
#RolesAllowed(Role.TRAINING_ADMIN)
public Response importClass(#FormParam("file") File file) {
InputStream is = new FileInputStream(file);
HSSFWorkbook workbook = new HSSFWorkbook(is);
if (checkTokenAndRole(new int[] {1, 11}).getStatus() != Response.Status.OK.getStatusCode()) {
return LoginError(checkToken().getStatus());
} else {
String token = request.getHeader(HttpHeaders.AUTHORIZATION);
String fileExtension = request.getHeader("FileExtension");
return ClassService.getInstance().importClass(file, fileExtension,
token);
}
}
HTML and Js file:
<form data-bind="submit: cancel">
<div class="modal-dialog dialog-class">
<div class="modal-content dialog-class">
<div class="modal-header layout-dialog-header">
<div class="layout-float-left dialog-close-icon">
<span class="glyphicon doc-icon-close-nav" data-bind="click: cancel"></span>
</div>
<div>
<h5 data-bind="text: title" data-i18n="modules.class.uploadSchedule"></h5>
</div>
</div>
<div class=" docs-margin-top-s">
<div>
<div class="form-group marginBot35">
<div class="class-browse">
<div class="col-md-12">
<div>
<label class="label-md search-class-header" for="">
<span class="search-class-header" data-i18n="modules.class.uploadClasslist" data-bind="text: listClass"></span>
</label>
</div>
<div id="" class="col-md-8 control-upload no-padding-left">
<input readonly="true" tabindex="3" class="col-md-12" id='uploadFile' type="text" name="" style="min-height: 40px" data-bind="value: name, attr: {'title': name()}"/>
</div>
<div clas="col-md-4">
<label for="input-file-upload" tabindex="3" class="pull-right btn btn-secondary-aia btn-cancel font-size20" data-dismiss="modal"
data-i18n="buttons.buttonBrowse" >Browse
</label>
</div>
</div>
<div class="class-center-align">
<label class="label-md search-class-header " for="">
<span class="search-class-header" data-i18n="modules.class.downloadThe">Download the</span>
<!-- <a class="class-highlight" tabindex="3" data-i18n="modules.class.trainingSchedule" data-bind="attr: {href: template}, text: textTemplate" download>Training Schedule Template</a> -->
<a class="class-highlight" tabindex="3" data-i18n="modules.class.trainingSchedule" data-bind="click: $root.download, text: textTemplate" >Training Schedule Template</a>
</label>
</div>
</div>
</div>
</div>
</div>
<div class="col-md-12 footer-class" style="padding-bottom:40px">
<button tabindex="3" type="button" class="btn btn-secondary-aia btn-cancel font-size20" data-dismiss="modal" data-i18n="buttons.buttonCancel" data-bind="click: cancel"></button>
<button tabindex="3" type="submit" class="btn btn-primary-aia btn-save font-size20 " style=" cursor: pointer; word-spacing: normal !important" data-bind="click: upload, disable: !readyUpload(),text: buttonUpload" data-dismiss="modal" data-i18n="buttons.buttonUploadSchedule"></button>
</div>
</div>
</div>
</form>
<form id="form-input-file-upload" action="" method="post" enctype="multipart/form-data" style="display:none">
<input id="input-file-upload" type="file" style="" name="file" size="45" accept=".xls,.xlsx" style="display:none" data-bind="attr: {accept: acceptedFiles},event: {change: addFile}" >
</form>
define([
'durandal/app',
'durandal/events',
'plugins/dialog',
'plugins/http',
'knockout',
'jquery',
'config',
'services/utils',
'i18next',
'services/document'
], function (app, Events, dialog, http, ko, $, Config, Utils, i18next, DocumentService) {
'use strict';
return function UploadBulkSchedule(mode) {
var self = this;
Events.includeIn(self);
if(mode === 1){
self.title = ko.observable( i18next.t("modules.bulkAttendee.title") ? i18next.t("modules.bulkAttendee.title") : "");
self.listClass = ko.observable( i18next.t("modules.bulkAttendee.listClass") ? i18next.t("modules.bulkAttendee.listClass") : "");
self.textTemplate = ko.observable( i18next.t("modules.bulkAttendee.template") ? i18next.t("modules.bulkAttendee.template") : "");
self.buttonUpload = ko.observable( i18next.t("modules.bulkAttendee.buttonUpload") ? i18next.t("modules.bulkAttendee.buttonUpload") : "");
}else{
self.title = ko.observable( i18next.t("modules.class.uploadSchedule") ? i18next.t("modules.class.uploadSchedule") : "");
self.listClass = ko.observable( i18next.t("modules.class.uploadClasslist") ? i18next.t("modules.class.uploadClasslist") : "");
self.textTemplate = ko.observable( i18next.t("modules.class.trainingSchedule") ? i18next.t("modules.class.trainingSchedule") : "");
self.buttonUpload = ko.observable( i18next.t("buttons.buttonUploadSchedule") ? i18next.t("buttons.buttonUploadSchedule") : "");
}
self.name = ko.observable();
var acceptedFileArr = [
'application/vnd.ms-excel',
'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
'application/csv',
'.xls','.xlsx', '.csv'];
var acceptedExtension = ['xls', 'xlsx', 'csv'];
self.mode = mode;
self.acceptedFiles = ko.observable(acceptedFileArr.join(','));
self.readyUpload = ko.computed(function(){
return self.name() ? true : false;
});
var maxSize = 5242880;
self.template = (self.mode === 1) ? Config.getBackendBaseUrl('/temp/excel/AttendanceImportTemplate/AttendeeListTemplate.xls') :Config.getBackendBaseUrl('/temp/excel/ClassImportTemplate/ClassImportTemplate.zip');
self.templateCSV = Config.getBackendBaseUrl('/temp/excel/ClassImportTemplate/ClassImportTemplate.csv');
var filesArray = [];
self.cancel = function(){
dialog.close(self);
};
self.active = function(){
};
self.upload = function(data, e){
e.preventDefault();
app.showLoading();
var inputTag = $('#form-input-file-upload :input')[0];
var fileName = $(inputTag).val().replace(/^.*[\\\/]/, '');
var extension = fileName.split('.').pop();
var headers = {
FileExtension: extension,
FileName: encodeURIComponent(fileName),
'Authorization': app.user().get('token'),
'isCourseImage': 0
};
if (self.mode === 1) {
self.trigger('uploadSuccess', [ $('#form-input-file-upload :input')[0] ]);
} else {
Utils
.uploadFile(
'class/import',
new FormData(
$('#form-input-file-upload')[0]),
headers)
.then(
function() {
app.hideLoading();
},
function(response) {
var title = i18next
.t('modules.class.errorTitle');
var options = [{
text : i18next
.t('buttons.buttonOk'),
value: Config.Events.DialogMessage.OK
}];
if(response.status === 200){
app.hideLoading();
} else if(response.status === 500){
var errorMessage = Utils
.getErrorMessage(response);
var errorCode = '';
var developerMessage = '';
try{
errorCode = JSON
.parse(response.responseText).errorCode;
developerMessage = JSON
.parse(response.responseText).message;
} catch(e){
}
if (errorCode === 1007
&& developerMessage) {
var messageContent = '<br></br><b>'
+ i18next
.t(
'message.error.importClassSuccess')
.format(
developerMessage)
+ '</b><br></br>';
title = i18next
.t('message.error.importSuccess');
app
.showMessageConfirmTitle(
messageContent,
title,
options,
false,
{
class : 'success-class'
})
.then(
function() {
self
.trigger('uploadSuccess');
dialog
.close(self);
});
} else if(errorMessage){
app.showMessageError(
errorMessage,
title, options,
false, null);
}
} else if(response.status === 0) {
var errorMessage = i18next
.t('message.error.notSaveClassList');
app.showMessageError(
errorMessage, title,
options, false, null);
}
app.hideLoading();
});
}
};
self.browse = function(){
filesArray = [];
document.getElementById("uploadFile").click();
};
self.addFile = function(data, event){
var inputFile = document.getElementById("input-file-upload");
var path = inputFile.value.toString();
var uploadFile = event.currentTarget;
var file = uploadFile.files[0];
var fsize = file.size;
var name, extension;
name = path.replace(/^.*[\\\/]/, '');
extension = name.split('.').pop();
if( fsize > maxSize){
self.name('');
$('#input-file-upload').replaceWith($('#input-file-upload').clone(true));
showUploadMessageWithData(file);
$('#input-file-upload')[0].value = '';
} else if(acceptedExtension.indexOf(extension.toLowerCase()) < 0){
self.name('');
$('#input-file-upload').replaceWith($('#input-file-upload').clone(true));
var messageContent = '<br/><b>'+i18next.t('modules.class.wrongFileExtension')+' </b><br/>';
var options = [{
text: i18next.t('buttons.buttonClose'),
value: Config.Constants.MessageBox.DialogResult.BUTTON_INDEX_0
}];
var title = i18next.t('modules.class.errorTitle');
app.showMessageError(messageContent, title, options, false, null);
$('#input-file-upload')[0].value = '';
} else {
self.name(name);
}
};
function showUploadMessageWithData (file) {
var messageContent = '<p style="white-space: pre-wrap">'+i18next.t('modules.course.editPage.fileName')+': ' + file.name + '</p>';
messageContent += '</br><p><b>'+i18next.t('modules.course.editPage.warnUploadFile')+' </b></p>'; messageContent += '<p><b>'+i18next.t('modules.course.editPage.requireUploadFile')+ ' </b></p>';
var options = [{
text: i18next.t('buttons.buttonOk'),
value: Config.Constants.MessageBox.DialogResult.BUTTON_INDEX_0
}];
var title = i18next.t('modules.class.errorTitle');
return app.showMessageError(messageContent, title, options, false, {class: 'confirm-class'}).then(function () {
});
}
//download Material
self.download = function(fileDownload){
app.showLoading();
DocumentService.downloadTemplate(fileDownload.template).then(function (response) {
app.hideLoading();
var extension = fileDownload.template.split('.').pop();
var ctType = '';
switch(extension) {
case 'jpg':
case 'jpeg':
ctType = 'image/jpeg';
break;
case 'png':
ctType = 'image/png';
break;
case 'doc':
ctType = 'application/msword';
break;
case 'docx':
ctType = 'application/vnd.openxmlformats-officedocument.wordprocessingml.document';
break;
case 'xls':
ctType = 'application/vnd.ms-excel';
break;
case 'xlsx':
ctType = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
break;
case 'ppt':
ctType = 'application/vnd.ms-powerpoint';
break;
case 'pptx':
ctType = 'application/vnd.openxmlformats-officedocument.presentationml.presentation';
break;
case 'pdf':
ctType = 'application/pdf';
break;
default:
break;
}
var byteArray = new Uint8Array(response.data);
var a = window.document.createElement('a');
a.setAttribute("id", "tmpHref");
a.href = window.URL.createObjectURL(new Blob([byteArray], { type: ctType }));
a.download = fileDownload.template.split("/")[fileDownload.template.split("/").length - 1];
// Append anchor to body.
document.body.appendChild(a);
a.click();
// Remove anchor from body
document.body.removeChild(a);
}, function (response) {
app.hideLoading();
Utils.downloadMaterial(response);
});
};
};
});
Anyone can help me give a solution?
Thanks.
I had the solution. I change use IMultipartBody instead using #FormParam,changing ImultipartBody to byte array and use it instead a file.
Related
I have this form
<div class="row">
<h1 class="page-header">
Create
</h1>
<form ng-submit="create()", enctype="multipart/form-data">
<div class="form-group">
<label>Name:</label>
<input type="text" ng-model="subforum.name" class="form-control" />
</div>
<div class="form-group">
<label>Desc:</label>
<input type="text" ng-model="subforum.desc" class="form-control" />
</div>
<input type="file" ngf-select ng-model="subforum.icon" name="subforum.icon"
accept="image/*" ngf-max-size="2MB" required
ngf-model-invalid="errorFile">
<img ng-show="myForm.file.$valid" ngf-thumbnail="subforum.icon" class="thumb"> <button ng-click="subforum.icon= null" ng-show="subforum.icon">Remove</button>
<button class="btn btn-success" type="submit">Create</button>
</form>
``
In my JS
.config(function($stateProvider) {
$stateProvider.state('create', {
url:'/subforum/create',
views: {
'main': {
templateUrl:'subforum/create.tpl.html',
controller: 'CreateCtrl'
}
},
data : { pageTitle : "Create Subforum" }
})
and
.factory('subforumService', function($resource) {
var service = {};
service.create = function (subforum, success, failure) {
var SubForum= $resource ("/web-prog/rest/subforums");
SubForum.save({}, subforum, success, failure) ;
};
.controller("CreateCtrl", function($scope, $state, subforumService) {
$scope.create = function() {
$scope.subforum.author = JSON.parse(localStorage.getItem ("logedUser"));
subforumService.create($scope.subforum,
function(returnedData) {
$state.go("home");
},
function() {
alert("Error creating");
});
};
I know thats not best practice to save user in LocalStorage but for now its like that.
On backend i have controller and in that controller i have methode:
#RequestMapping(method = RequestMethod.POST)
public ResponseEntity<SubForumResource> createPodforum(#RequestBody SubForumResource sentPodforum) {
}
and SubForumResource is
public class PodforumResource extends ResourceSupport {
private String name;
private String desc;
private byte[] icon;}
with geters and seters and everything i need.
So when i have form without image it works without problems. But i need icon too. Im new to angularjs but need it for this project. When i try to use FormData() i dont know how to use $resource. So if someone can help me i would be thankful. This is my first prject i need to work front end so im lost.
You can refer below code for angularjs :
this.addEmployee = function (requestData, file) {
var data = new FormData();
data.append('file', file[0]);
data.append('requestData', new Blob([JSON.stringify(requestData)], {
type: "application/json"
}));
var config = {
transformRequest: angular.identity,
transformResponse: angular.identity,
headers: {
'Content-Type': undefined
}
}
var url = "http://localhost:8080/addEmployee";
var promise1 = $http.post(url, data, config);
var promise2 = promise1.then(function (response) {
return response.data;
},
function errorCallback(response) {
alert(response.data.errorMessage);
});
return promise2;
}
And for controller :
#RequestMapping(value = "/addEmployee", method = RequestMethod.POST, consumes = {"multipart/form-data" })
#CrossOrigin
public CustomResponse addEmployee(#RequestPart("file") MultipartFile file, #RequestPart("requestData") Employee emp) {
}
i am trying the example todo app,i download that example in ionic and i tried that it is working, and i trued to add another filed inside newTask.html and add in local database as same as previous value,but it is not working can you please help me how can i add another filed in the local database and get results in list html file....
NewTask.html
------------
<div class="modal" ng-controller="newTaskCtrl">
<ion-header-bar class="bar-stable">
<h1 class="title">Add New Task</h1>
<button class="button button-clear button-positive" ng-click="closeNewTask()">Cancel</button>
</ion-header-bar>
<ion-content>
<form ng-submit="createTask(task)">
<div class="list">
<!--label class="item item-input">
<input type="text" placeholder="Title What do you need to do?" ng-model="task.title">
</label-->
<label class="item item-input item-stacked-label">
<span class="input-label">Title</span>
<input type="text" placeholder="What do you need to do?" ng-model="task.title">
<span class="input-label">Lasr Name</span>
<input type="text" placeholder="Firstname?" ng-model="task.firstname">
</label>
<!--div class="row">
<label class="col">
<input type="" ng-model="time">
</label>
<label class="col">
<input type="text" placeholder="End?" >
</label>
</div-->
</div>
<div class="padding">
<button type="submit" class="button button-block button-positive">Create Task</button>
</div>
</form>
</ion-content>
</div>
NewTaskCtrl.js
-------------------
todoApp.controller('newTaskCtrl', function($scope, $ionicModal, $ionicPopup, SQLService) {
// Called when the form is submitted
$scope.createTask = function(task) {
SQLService.set(task.title,task.firstname);
$scope.loadTask();
$scope.taskModal.hide();
task.title = "";
task.firstname = "";
};
SQLService.js
------------------
todoApp.factory("SQLService", function ($q) {
var db;
var task='';
var deltask;
function createDB() {
try {
db = window.openDatabase("todoDB", "1.0", "ToDoApp", 10*1024*1024);
db.transaction(function(tx){
tx.executeSql("CREATE TABLE IF NOT EXISTS tasks (id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, title VARCHAR(100), firstname VARCHAR(100) )",[]);
});
} catch (err) {
alert("Error processing SQL: " + err);
}
console.log('database created');
}
function setTasks(title,firstname){
return promisedQuery("INSERT INTO tasks(title,firstname) VALUES ('" + title + "','" + firstname + "')", defaultResultHandler, defaultErrorHandler);
}
function getTasks(){
return promisedQuery('SELECT * FROM tasks', defaultResultHandler, defaultErrorHandler);
}
function defaultResultHandler(deferred) {
return function(tx, results) {
var len = results.rows.length;
var output_results = [];
for (var i=0; i<len; i++){
var t = {'id':results.rows.item(i).id,'title':results.rows.item(i).title,'firstname':results.rows.item(i).firstname};
output_results.push(t);
}
deferred.resolve(output_results);
}
}
function defaultErrorHandler(deferred) {
return function(tx, results) {
var len = 0;
var output_results = '';
deferred.resolve(output_results);
}
}
function promisedQuery(query, successCB, errorCB) {
var deferred = $q.defer();
db.transaction(function(tx){
tx.executeSql(query, [], successCB(deferred), errorCB(deferred));
}, errorCB);
return deferred.promise;
}
return {
setup: function() {
return createDB();
},
set: function(title,firstname) {
return setTasks(title,firstname);
},
all: function() {
return getTasks();
}
}
});
PLease see the SQL Service and help me,is it correct what i add the filed name in "setTasks function.."
Ok, so you had tried the example that you had downloaded, now you have added another field in NewTask.html. But the new field that you added is not getting added to the table right??
Did you try to change the version of the DB opened??
db = window.openDatabase("todoDB", "1.0", "ToDoApp", 10*1024*1024);
to
db = window.openDatabase("todoDB", "2.0", "ToDoApp", 10*1024*1024);
Hi I'm trying to upload a image file to the server.I have used jCrop to crop the image before uploading and used canvas to get the cropped image coordinates.I have included controller and jsp files .But I'm not able to send formdata using ajax.
AppController.java
#RequestMapping(value = "/upload", method = RequestMethod.POST)
public String handleFormUpload(#RequestParam("file") MultipartFile file, ModelMap model) throws IOException{
if (!file.isEmpty()) {
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
String name = auth.getName(); //get logged in username
BufferedImage src = ImageIO.read(new ByteArrayInputStream(file.getBytes()));
File destination = new File("/home/me/Desktop/"+name+".png");
model.addAttribute("username", name);
// something like C:/Users/tom/Documents/nameBasedOnSomeId.png
ImageIO.write(src, "png", destination);
//Save the id you have used to create the file name in the DB. You can retrieve the image in future with the ID.
}else {
System.out.println("file is empty");
}
return "prefs";
}
prefs.jsp
<script type="text/javascript">
$(function(){
$('.majorpoints').click(function(){
$(this).find('.hiders').slideToggle();
});
$("#imgInp").change(function(){
var c = $('.cropArea').Jcrop({
onSelect: updateCoords,
bgOpacity: .4,
setSelect: [ 100, 100, 50, 50 ],
aspectRatio: 16 / 9
});
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#blah').attr('src', e.target.result);
}
reader.readAsDataURL(input.files[0]);
}
}
readURL(this);
});
$('#btnCrop').click(function () {
var x1 = $('#x').val();
var y1 = $('#y').val();
var width = $('#w').val();
var height = $('#h').val();
var canvas = $("#canvas")[0];
alert(x1+""+y1+""+""+width+""+height);
var context = canvas.getContext('2d');
var img = new Image();
img.onload = function () {
canvas.height = height;
canvas.width = width;
context.drawImage(img, x1, y1, width, height, 0, 0, width, height);
$("#imgInp").val(canvas.toDataURL("image/jpeg"));
};
var data = new FormData();
data.append('file', dataURItoBlob(canvas.toDataURL("image/jpeg")));
$.ajax({
url: 'upload',
data: data,
contentType: false,
processData: false,
type: 'POST',
success: function(data){
alert(data);
}
});
img.src = $('#blah').attr('src');
});
});
function dataURItoBlob(dataURI) {
// convert base64/URLEncoded data component to raw binary data held in a string
var byteString;
if (dataURI.split(',')[0].indexOf('base64') >= 0)
byteString = atob(dataURI.split(',')[1]);
else
byteString = unescape(dataURI.split(',')[1]);
// separate out the mime component
var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0];
// write the bytes of the string to a typed array
var ia = new Uint8Array(byteString.length);
for (var i = 0; i < byteString.length; i++) {
ia[i] = byteString.charCodeAt(i);
}
return new Blob([ia], {type:mimeString});
}
function updateCoords(c)
{
console.log(c);
$('#x').val(c.x);
$('#y').val(c.y);
$('#w').val(c.w);
$('#h').val(c.h);
$('#btnCrop').show();
};
</script>
<div id="myModal" class="modal fade" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Modal Header</h4>
</div>
<div class="modal-body">
<form method="POST" action="upload" enctype="multipart/form-data">
Please select a file to upload :
<input type="file" name="file" class="file" id="imgInp" />
<div class="cropArea">
<img id="blah" src="#" alt="your image" />
</div>
<input type="hidden" id="x" name="x" />
<input type="hidden" id="y" name="y" />
<input type="hidden" id="w" name="w" />
<input type="hidden" id="h" name="h" />
<canvas id="canvas" height="5" width="5"></canvas>
</form>
<input type="button" id="btnCrop" value="Crop" style="display: none" />
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
You are missing this param
enctype: 'multipart/form-data'
$.ajax({
url: 'upload',
data: data,
contentType: false,
processData: false,
enctype: 'multipart/form-data',
type: 'POST',
success: function(data){
alert(data);
}
});
You should have this
var data = new FormData();
data.append('file', jQuery('#imgInp')[0].files[0]);
instead of
jQuery.each(jQuery('#imgInp')[0].files, function(i,file) {
data.append('file-'+i, file);
});
Later Edit 2:
in your function dataURItoBlob(dataURI) add callback like this:
function dataURItoBlob(dataURI, callback) {
...
callback();
}
then in
$('#btnCrop').click(function () { ...
data.append('file', dataURItoBlob(canvas.toDataURL("image/jpeg", function(){
$.ajax({
url: 'upload',
data: data,
contentType: false,
processData: false,
type: 'POST',
success: function(data){
alert(data);
}
});
})));
this way, you are sure that you make the ajax call after dataURItoBlob is executed.
So i have created div with static data from controller and model.Now when i click on ADD button a new item should be added to list and div should automatically be dispalyed to page. Hope i am clear :)
Please guide me how do i achieve it?? Thanks
It should work before but I guess you changed the html , Okay Try This one
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script>
var i=y=0;
var newarr = new Array();
var divContent = '';
#foreach (var job in Model)
{
divContent = '<div class="panel panel-default" id="panel2"><div class="panel-heading-new"><h4 class="panel-title" id="newpanel1"><a data-toggle="collapse" data-target="#collapseTwo" href="#collapseTwo">';
divContent += '#Html.DisplayFor(modelItem => job.Header, new { job.Id })';
divContent += '</a></h4></div><div id="collapseTwo" class="panel-collapse collapse in"><div class="panel-body"><p class="lead justified">';
divContent += 'Qualifications and Skills:';
divContent += '</p><ul class="fa-ul">';
divContent += '<li><i class="fa-li fa fa-hand-o-right pad-icon"></i><span class="lead justified">#Html.DisplayFor(modelItem => job.Content, new { job.Id })</span></li>';
divContent += '</ul><br /></div></div></div>';
newarr[i] = $(divContent);
i = i +1;
}
$(document).ready(function(){
$("a#add").click(function(){
if (y<i) {
var content = newarr[y];
$('#maincontainer').append(content);
y++;
} else {
alert('No other Job!');
}
return false;
});
});
</script>
ADD
<div class="container">
<div class="col-lg-12" id="maincontainer">
</div>
</div>
<script>
</script>
#model IEnumerable<Nexcentus.UI.Models.JobOpening>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script>
var i=0;
var y=0;
var newarr = new Array();
</script>
<script>
#foreach (var job in Model)
{
newarr[i] = $( "<li><i class=\"fa-li fa fa-hand-o-right pad-icon\"></i><span class=\"lead justified\">#Html.DisplayFor(modelItem => job.Content, new { job.Id })</span></li>");
i = i +1;
}
</script>
<div class="container">
ADD
<div class="col-lg-12">
#foreach (var job in Model)
{
<div class="panel panel-default" id="panel2">
<div class="panel-heading-new">
<h4 class="panel-title-new" id="newpanel1">
<a data-toggle="collapse" data-target="#collapseTwo" href="#collapseTwo">
#Html.DisplayFor(modelItem => job.Header, new { job.Id })
</a>
</h4>
</div>
<div id="collapseTwo" class="panel-collapse collapse in">
<div class="panel-body">
<p class="lead justified">
Qualifications and Skills:
</p>
<ul class="fa-ul">
<li><i class="fa-li fa fa-hand-o-right pad-icon"></i><span class="lead justified">#Html.DisplayFor(modelItem => job.Content, new { job.Id })</span></li>
</ul>
<br />
</div>
</div>
</div>
<script>
$("a#add").click(function(){
if (y<i) {
var content = newarr[y];
$('ul.fa-ul').append(content);
y = y+1;
}
return false;
});
</script>
Try this one
<in search.php>
<?php require_once("../includes/session.php"); ?>
<?php require_once("../includes/connection.php") ?>
<?php require_once("../includes/functions.php") ?>
<?php
$searchq = $_POST['searchq'];
$tablehead="<tr><th>Product Name</th><th>Category</th><th>Price</th><th>Discount</th><th>Edit</th></tr>";
$tabledata = "";
if(empty($searchq)) {
echo "";
} else {
//If there is text in the search field, this code is executed every time the input changes.
echo "<div id='results'-->"; //this div is used to contain the results. Mostly used for styling.
//This query searches the name field for whatever the input is.
$sql = "SELECT * FROM `tblstudent` WHERE `student_id` LIKE '%$searchq%' or `name` LIKE '%$searchq%' or `email` LIKE '%$searchq%'";
$result = mysql_query($sql);
while($row = mysql_fetch_assoc($result)) {
$id = $row['id'];
$student_id=htmlentities($row['student_id']);
$hashed_password=htmlentities($row['hashed_password']);
$name=htmlentities($row['name']);
$email=htmlentities($row['email']);
"this is the part that i add on but not work, error-free"
$tabledata.="<tr id='$id' class='edit_tr'><td class='edit_td' >
<span id='one_$id' class='text'>$student_id</span>
<input type='text' value='$student_id' class='editbox' id='one_input_$id' />
</td>
<td class='edit_td' >
<span id='two_$id' class='text'>$hashed_password</span>
<input type='text' value='$hashed_password' class='editbox' id='two_input_$id'/>
</td>
<td class='edit_td' >
<span id='three_$id' class='text'>$name $</span>
<input type='text' value='$name' class='editbox' id='three_input_$id'/>
</td>
<td class='edit_td' >
<span id='four_$id' class='text'>$email $</span>
<input type='text' value='$email' class='editbox' id='four_input_$id'/>
</td>
<td><a href='#' class='delete' id='$id'> X </a></td>
</tr>";
}
$finaldata = "<table width='100%'>". $tablehead . $tabledata . "</table>"; // Content for Data
}
echo "</div>";
?>
this is the js query plug in.
<EditDeletePage.js>
$(document).ready(function()
{
$(".delete").live('click',function()
{
var id = $(this).attr('id');
var b=$(this).parent().parent();
var dataString = 'id='+ id;
if(confirm("Sure you want to delete this update? There is NO undo!"))
{
$.ajax({
type: "POST",
url: "delete_ajax.php",
data: dataString,
cache: false,
success: function(e)
{
b.hide();
e.stopImmediatePropagation();
}
});
return false;
}
});
$(".edit_tr").live('click',function()
{
var ID=$(this).attr('id');
$("#one_"+ID).hide();
$("#two_"+ID).hide();
$("#three_"+ID).hide();
$("#four_"+ID).hide();
$("#one_input_"+ID).show();
$("#two_input_"+ID).show();
$("#three_input_"+ID).show();
$("#four_input_"+ID).show();
}).live('change',function(e)
{
var ID=$(this).attr('id');
var one_val=$("#one_input_"+ID).val();
var two_val=$("#two_input_"+ID).val();
var three_val=$("#three_input_"+ID).val();
var four_val=$("#four_input_"+ID).val();
var dataString = 'id='+ ID +'&name='+one_val+'&category='+two_val+'&price='+three_val+'&discount='+four_val;
if(one_val.length>0&& two_val.length>0 && three_val.length>0 && four_val.length>0)
{
$.ajax({
type: "POST",
url: "live_edit_ajax.php",
data: dataString,
cache: false,
success: function(e)
{
$("#one_"+ID).html(one_val);
$("#two_"+ID).html(two_val);
$("#three_"+ID).html(three_val);
$("#four_"+ID).html(four_val);
e.stopImmediatePropagation();
}
});
}
else
{
alert('Enter something.');
}
});
// Edit input box click action
$(".editbox").live("mouseup",function(e)
{
e.stopImmediatePropagation();
});
// Outside click action
$(document).mouseup(function()
{
$(".editbox").hide();
$(".text").show();
});
//Pagination
function loading_show(){
$('#loading').html("<img src='images/loading.gif'/>").fadeIn('fast');
}
function loading_hide(){
$('#loading').fadeOut('fast');
}
function loadData(page){
loading_show();
$.ajax
({
type: "POST",
url: "load_data.php",
data: "page="+page,
success: function(msg)
{
$("#container").ajaxComplete(function(event, request, settings)
{
loading_hide();
$("#container").html(msg);
});
}
});
}
loadData(1); // For first time page load default results
$('#container .pagination li.active').live('click',function(){
var page = $(this).attr('p');
loadData(page);
});
$('#go_btn').live('click',function(){
var page = parseInt($('.goto').val());
var no_of_pages = parseInt($('.total').attr('a'));
if(page != 0 && page <= no_of_pages){
loadData(page);
}else{
alert('Enter a PAGE between 1 and '+no_of_pages);
$('.goto').val("").focus();
return false;
}
});
});
I edit from the http://palavas.biz/forum/viewtopic.php?f=51&t=4143&sid=9241f1f287fc672cc32f91a06b93f4c3#.UjqVx9Jmim4 but not work... i try to change the function that already have a table display to a search function only display out. but unfortunately I can't display out the data which list inside the table when type words in the search keyword textbox.