I have here a javascript code. What I want is that I want to store the data result from this url:
'processjson.php?path=' + encodeURI('display/payTempEarn') + '&json=' + encodeURI(JSON.stringify(dataTempEarn)), to my variable 'tempIncDed', and display that data in my jqgrid.
My question here now is, why is that though when i alert the variable tempIncDed, it shows that it stores the correct data, but it does not display in my jqgrid?
Did I miss something in my code?
Below is my js code:
var tempIncDed = [];
$(document).ready( function() {
$("#tblIncDed").jqGrid({ data: tempIncDed,
datatype: "local",
colNames:['Code','Description', 'Taxable','Amount'],
colModel:[
{name:'ded_code',width: 85},
{name:'ded_desc'},
{name:'taxable',width: 95},
{name:'amount', formatter:'currency', align:'right',width: 85}
],
rowNum:20,
viewrecords: true,
rowList:[20,50,100],
ppager: '#tblIncDedPager',
viewrecords: true,
caption: "Details"
});
$( "#btnEarn" ).click(function() {
var empNo = $("#tblPayroll").jqGrid('getCell',($("#tblPayroll").jqGrid('getGridParam', 'selrow')),'emp_no');
var dataTempEarn = {
"SessionID": $.cookie("SessionID"),
"dataType": "data",
"per_id":$("#payPeriod").val(),
"emp_no":empNo
};
$.ajax({
type: 'GET',
url:'processjson.php?path=' + encodeURI('display/payTempEarn') + '&json=' + encodeURI(JSON.stringify(dataTempEarn)),
dataType: primeSettings.ajaxDataType,
success: function(data) {
if ('error' in data)
{
showMessage('ERROR: ' + data["error"]["msg"]);
}
else{
var resLen = data.result.length;
tempIncDed = JSON.stringify(data.result);
alert('this is the tempDed ' + tempIncDed);
$("#tblIncDed").jqGrid('setGridParam',{
datatype: 'local',
data:tempIncDed}
).trigger("reloadGrid");
}
}
});
$("#dialOtherIncDed").dialog( "open" );
$("#dialOtherIncDed").attr("name","earnings");
});
})
This is the tempDed sample data: [{"ded_id":"10000000845","ded_code":"100","ded_desc":"MEAL ALL","taxable":"N","amount":"10"},{"ded_id":"10000000849","ded_code":"101","ded_desc":"TRANSPORTATION","taxable":"N","amount":"40"},{"ded_id":"10000000851","ded_code":"103","ded_desc":"LAUNDRY","taxable":"N","mOther_amnt":"50.00"}]
Some of my html code:
<!--master grid-->
<div style="width:100%">
<table id="tblPayroll"></table>
<div id="tblPayrollPager"></div>
</div>
<!--dialog that contains the table for other earnings, deductions, loans-->
<div id="dialOtherIncDed" style="width:100%">
<table id="tblIncDed"></table>
<div id="tblIncDedPager"></div><br><br>
Total amount: <b><span id="totalAmnt"></span></b>
</div>
<!--dialog that contains the dialog edit earnings, deductions, loans-->
<div id="editIncDed"">
<table>
<tr>
<span id="incDed_name"></span>
<td>Amount:</td>
<td><input class="numeric" type="text" id="amount" value = ""/></td></tr>
</table>
</div>
<!--edit-->
<div id="dialogPayrollEdit" title="Payroll Entry">
<table>
<tr>
<td>Payroll Period:</td>
<td><b><span id="periodDateL" style="color:blue"></span></b></td>
<td>Type:</td><td><b><span id="rateType" style="color:blue"></span></b></td>
<td>Rate:</td><td><b><span id="payRate" style="color:blue"></span></b></td>
</tr>
<tr>
<td>Employee Name:</td>
<td><b><span id="empName" style="color:blue"></span></b></td>
</tr>
</table>
<hr/>
<fieldset><legend>Payroll Details</legend>
<p><center><b>EARNINGS</b></center></p>
<table>
<tr>
<td>
....
</td>
<td>
<table >
<tr...tr>
<tr>...</tr>
<tr>...</tr>
<tr><td>Other earnings</td><td><input class="numeric" style="width:60px" id="mOther_amnt" value = ""/></td><td><input type='button' value='...' id="btnEarn"></td></tr>
<tr><td><b>GROSS PAY</b></td><td></td><td><b><span style="width:60px;color:blue" id="grossPay"/></b></td></tr>
</table>
</td>
</tr>
</table>
<hr/>
<p><center><b>DEDUCTIONS</b></center></p>
<table width = "100%">
<tr>
<td>
....
</td>
<td>
<table >
<tr>
<td>Other deductions</td>
<td><input class="numeric" style="width:60px;color:black" id="mOther_ded" value = "" disabled/></td>
<td><input type='button' value='...' id="btnDed"/></td>
</tr>
<tr>
<td>Advances/Loans</td>
<td><input class="numeric" style="width:60px;color:black" id="mLoan_ded" value = "" disabled/></td>
<td><input type='button' value='...' id="btnLoan"></td>
</tr>
<tr></tr>
<tr></tr>
<tr><td><b>NET PAY</b></td><td></td><td><b><span class="numeric" style="width:60px;color:blue" id="netPay" value = "" disabled/></b></td><td></td></tr>
</table>
</td>
</tr>
</table>
<br>
</fieldset><br>
Suggest lowest NET PAY >>> <input type="text" id="lowNetPay" value = "" style="width:80px;color: black" value='0.00' disabled/>
</div><br><br>
<br><br>
<button id="btnPayrollEdit">Edit</button>
The btnLoan, btnDed, and btnEarn will be using the same grid. I also used the variable tempIncDed to save the returned data from ajax..
I've finally solved my own problem. Lets say for example I have this data stored in var tempInc,
[{"ded_id":"10000000845","ded_code":"100","ded_desc":"MEAL ALL","taxable":"N","amount":"10"},{"ded_id":"10000000849","ded_code":"101","ded_desc":"TRANSPORTATION","taxable":"N","amount":"40"},{"ded_id":"10000000851","ded_code":"103","ded_desc":"LAUNDRY","taxable":"N","mOther_amnt":"50.00"}]
This data was an output from ajax request, when the button btnEarn is click.
Here's my javascript code of btnEarn.
var tempInc = []; // global variable
$( "#btnEarn" ).click(function() {
$("#tblIncDed").clearGridData();
var empNo = $("#tblPayroll").jqGrid('getCell',($("#tblPayroll").jqGrid('getGridParam', 'selrow')),'emp_no');
var dataTempEarn = {
"SessionID": $.cookie("SessionID"),
"dataType": "data",
"per_id":$("#payPeriod").val(),
"emp_no":empNo
};
$.ajax({
type: 'GET',
url:'processjson.php?path=' + encodeURI('display/payTempEarn') + '&json=' + encodeURI(JSON.stringify(dataTempEarn)),
dataType: primeSettings.ajaxDataType,
success: function(data) {
var tempIncDed = [];
if ('error' in data)
{
showMessage('ERROR: ' + data["error"]["msg"]);
}
else{
$.each(data.result, function(rowIndex, rowDataValue) {
var fldName = rowDataValue;
tempInc[rowIndex] = fldName;
});
var resLen = data.result.length;
$("#totalAmnt").text(data.result[resLen -1].mTot_amnt);
$("#disTemp").text((JSON.stringify(tempInc)));
$("#tblIncDed").jqGrid('setGridParam',{
datatype: 'local',
data:tempInc}
).trigger("reloadGrid");
}
}
});
$("#dialOtherIncDed").dialog( "open" );
$("#dialOtherIncDed").attr("name","earnings");
});
Everytime I click that button, it will send ajax request to the server. The data returned (particularlly the object since i have an array of objects) will be saved in global variable, tempInc. After that, I have this code:
$("#tblIncDed").jqGrid('setGridParam',{
datatype: 'local',
data:tempInc}
).trigger("reloadGrid");
that will display the tempInc in my jqgrid. Hope this will help someone out there.
Related
enter image description hereenter image description hereHow to render a ajax response from db (map) in jsp screen
I am getting response in browser console but not sure how to render it in jsp on the browser screen like a table or any better suggestion
$('#submit_btn').click(function(){
var problemId = $('#search_data').val();
$.ajax({
type: "GET",
dataType : "json",
url : "http://localhost:8080/bugs/" + bugId,
success: function(data){
$("#response").html(data);
console.log('response data',data);
},
error : function(err){
console.log('error',err)
}
});
});
JSP
<body>
<div>
<div>
<h1>Lookup from Oracle database</h1>
Click on this <strong>link</strong> to visit home page.
</div>
<div>
<h2>${message}</h2>
<table>
<tr>
<td>Search Category:</td>
<td>
<select name="searchcategories">
<option value="-1">-Select Category-</option>
<option value="bug">bug</option>
<option value="attachment">attachment</option>
</select>
</td>
</tr>
<tr>
<td>Entity Id:</td>
<td><input type="text" name="bugId" id="search_data" class="form-control" placeholder="Search bug no..">
</td>
</tr>
<tr>
<td></td>
<td><button type="button" id="submit_btn" onclick="">Search</button>
</td>
</tr>
<tr>
<td>Bug Id:</td>
<td><input type="text" id="bugId" class="form-control">
</td>
</tr>
<tr>
<td>Prob State Name:</td>
<td><input type="text" id="probStateName" class="form-control">
</td>
</tr>
<tr>
<td>Priority Name:</td>
<td><input type="text" id="priorityName" class="form-control">
</td>
</tr>
</div>
</div>
</body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
});
$('#submit_btn').click(function(){
var bugId = $('#search_data').val();
$.ajax({
type: "GET",
dataType : "json",
url : "http://localhost:8080/bugs/" + bugId,
success: function(data){
$("#response").html(data);
console.log('response data',data);
var bugDetails = data;
renderDetails(data);
},
error : function(err){
console.log('error',err)
}
});
});
function renderDetails(data)
{
var id = document.getElementById("bugId");
var name = document.getElementById("probStateName");
var priority = document.getElementById("priorityName");
id.innerHTML = data.bugId;
name.innerHTML = data.probStateName;
priority.innerHTML = data.priorityName;
};
</script>
</html>
below is the response object that I see in console that has data fetched from backend. I want to render this ajax response below the search box
[Log] response data (oracle-lookup, line 65)
Object
data: {bugId: 298, stateCode: "2", …}
Object Prototype
You can populate data to any field from the following code. Probably best to also add a check to see whether the returned values are not empty.
<script type="text/javascript">
var bugDetails;
$(document).ready(function(){
$("#submit_btn").click(function(event){
event.preventDefault();
var bugId = document.getElementById("search_data").value;
$.ajax({
type: 'GET',
url: "http://localhost:8080/bugs/" + bugId,
dataType: 'json',
success: function(data, textStatus, jqXHR) {
bugDetails = data;
renderDetails(bugDetails);
alert(data);
alert(jqXHR.status);
alert(textStatus);
},
error: function(jqXHR, textStatus, errorThrown) {
alert(textStatus);
alert(jqXHR.status);
alert(errorThrown);
}
});
});
});
function renderDetails(bugs)
{
var id = document.getElementById("problemId");
var name = document.getElementById("probStateName");
var priority = document.getElementById("priorityName");
id.value = bugs.bugId;
name.value = bugs.probStateName;
priority.value = bugs.priorityName;
};
</script>
So now your code should be like this,
<body>
<div>
<div>
<h1>Lookup from Oracle database</h1>
Click on this <strong>link</strong> to visit home page.
</div>
<div>
<h2>${message}</h2>
<table>
<tr>
<td>Search Category:</td>
<td>
<select name="searchcategories">
<option value="-1">-Select Category-</option>
<option value="bug">bug</option>
<option value="attachment">attachment</option>
</select>
</td>
</tr>
<tr>
<td>Entity Id:</td>
<td><input type="text" name="bugId" id="search_data" class="form-control" placeholder="Search bug no..">
</td>
</tr>
<tr>
<td></td>
<td><button type="button" id="submit_btn">Search</button>
</td>
</tr>
<tr>
<td>Bug Id:</td>
<td><input type="text" id="problemId" class="form-control">
</td>
</tr>
<tr>
<td>Prob State Name:</td>
<td><input type="text" id="probStateName" class="form-control">
</td>
</tr>
<tr>
<td>Priority Name:</td>
<td><input type="text" id="priorityName" class="form-control">
</td>
</tr>
</div>
</div>
</body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript">
var bugDetails;
$(document).ready(function(){
$("#submit_btn").click(function(event){
event.preventDefault();
var bugId = document.getElementById("search_data").value;
$.ajax({
type: 'GET',
url: "http://localhost:8080/bugs/" + bugId,
dataType: 'json',
success: function(data, textStatus, jqXHR) {
bugDetails = data;
renderDetails(bugDetails);
alert(data);
alert(jqXHR.status);
alert(textStatus);
},
error: function(jqXHR, textStatus, errorThrown) {
alert(textStatus);
alert(jqXHR.status);
alert(errorThrown);
}
});
});
});
function renderDetails(bugs)
{
var id = document.getElementById("problemId");
var name = document.getElementById("probStateName");
var priority = document.getElementById("priorityName");
id.value = bugs.bugId;
name.value = bugs.probStateName;
priority.value = bugs.priorityName;
};
</script>
</html>
I have created Text Fields to fetch the data coming from AJAX call. Make sure you are using these ids.
<tr>
<td>Bug Id:</td>
<td><input type="text" id="problemId" class="form-control">
</td>
</tr>
<tr>
<td>Prob State Name:</td>
<td><input type="text" id="probStateName" class="form-control">
</td>
</tr>
<tr>
<td>Priority Name:</td>
<td><input type="text" id="priorityName" class="form-control">
</td>
</tr>
And when data comes from the AJAX call it will fetch to above fields using this method,
function renderDetails(bugs)
{
var id = document.getElementById("problemId");
var name = document.getElementById("probStateName");
var priority = document.getElementById("priorityName");
id.value = bugs.bugId;
name.value = bugs.probStateName;
priority.value = bugs.priorityName;
};
So what you need to care about is make sure text field ids are correct.
Good evening. The code below is intended to update a couple of table cells with a new quantity and new checked date. However, it only updates the first row in the table. Any help appreciated.
$(document).ready(function() {
$("form").on("submit", function(event) {
event.preventDefault();
var res = $(this).serialize();
var req = $.ajax({
url: '/stock/update',
type: 'POST',
data: res,
dataType: 'json',
success: function(response) {
//console.log(response);
$('#qty').text(response.qty_new);
$('#date').text(response.date);
}
});
});
});
Here is the HTML as requested:
<table>
<th>Part</th>
<th>Location</th>
<th>Quantity</th>
<th>Date Checked</th>
<th>New Quantity</th>
<th>Update</th>
% for row in stock:
<tr>
<td id='part'>{{row['part']}}</td>
<td id='location'>{{row['location']}}</td>
<td id='qty'>{{row['qty']}}</td>
<td id='date'>{{row['date']}}</td>
<form>
<input type='hidden' name='part' value="{{row['part']}}">
<input type='hidden' name='location' value="{{row['location']}}">
<td><input type='number' name='qty_new' style='width: 4em;'></td>
<td><button id='update_qty'>Save</button></td>
</form>
</tr>
% end
</table>
Firstly, the cells should have classes instead of IDs because there are duplicates.
<td class='part'>{{row['part']}}</td>
<td class='location'>{{row['location']}}</td>
<td class='qty'>{{row['qty']}}</td>
<td class='date'>{{row['date']}}</td>
<form>
<input type='hidden' name='part' value="{{row['part']}}">
<input type='hidden' name='location' value="{{row['location']}}">
<td><input type='number' name='qty_new' style='width: 4em;'></td>
<td><button class='update_qty'>Save</button></td>
</form>
Next, you'll need a way to select these based on the form that's being submitted.
$(document).ready(function() {
$("form").on("submit", function(event) {
event.preventDefault();
var $form = $(this);
var res = $form.serialize();
var req = $.ajax({
url: '/stock/update',
type: 'POST',
data: res,
dataType: 'json',
success: function(response) {
$form.siblings('.qty').text(response.qty_new);
$form.siblings('.date').text(response.date);
}
});
});
});
$(this) gets the jQuery-equivalent current scope of this, which is the form. Then the form's siblings are searched for the correct classes and the elements are modified.
I have a javascript file which is returning results to a HTML page via information entered in a SharePoint list. It works fine, but I've been asked to return another field of multiple text called 'Further Details'. However it's not showing up on the HTML page. I've checked the console and the information being entered in the Further Details field is being returned, it's just not showing on the HTML page. The rest (Current Status, Typical Usage etc) are showing fine.
The Do I need to add something to the var query URL? I've post the JavaScript and relevant HTML below:
function getDeviceKnownIssues() {
var txtfurtherinfo = "";
var txtTitleKnown = "<ol>";
var query = "**http://example.com/sites/it/ITInfrastructure/_vti_bin/listdata.svc//Knownissues?$filter=DeviceID eq " + window.DeviceId + ** "";
var call = $.ajax({
url: query,
type: "GET",
dataType: "json",
headers: {
Accept: "application/json;odata=verbose"
}
});
call.done(function(data, textStatus, jqXHR) {
console.log(JSON.stringify(data));
$.each(data.d.results, function(index, item) {
txtTitleKnown += "<li>" + item.Title + "</li>";
if (item.Info != undefined) {
txtfurtherinfo += item.Info + "\r\n";
}
});
txtTitleKnown = txtTitleKnown + "</ol>";
$('#knowntitle').append(txtTitleKnown);
$('#furtherinfo').append(txtfurtherinfo);
});
call.fail(function(jqXHR, textStatus, errorThrown) {
alert("Error retrieving data: " + jqXHR.responseText);
});
}
<tr>
<td class="tg-yw4l" colspan="3">
<h2>Known Issues</h2>
<div id="knowntitle"></div>
<input type=button onClick="location.href=**'http://example.com/sites/it/ITInfrastructure/_layouts/listform.aspx?PageType=8&ListId={5968ECC4-3049-4794-B6DC-130763C01043}&RootFolder=**'" value='Submit a known issue'>
</td>
<td class="tg-yw4l" colspan="3">
<h2>Accessories</h2>
<div id="deviceacc"></div>
</td>
</tr>
<tr>
<td class="tg-yw4l" colspan="3">
<h2>Typical Usage</h2>
<div id="deviceuse"></div>
</td>
<td class="tg-yw4l" colspan="3">
<h2>Current Status</h2>
<div id="imageContainer"></div>
</td>
</tr>
<td class="tg-yw4l" colspan="3">
<h2>Further Information</h2>
<div id="furtherinfo"></div>
</table>
It seems that you have basic html syntax error.
I would start from that.
You are not opening and closing your 'table row' <tr> and 'table data' <td> tags properly. Should be like this:
[...]
<tr>
<td class="tg-yw4l" colspan="3">
<h2>Further Information</h2>
<div id="furtherinfo"></div>
</td>
<td class="tg-yw4l" colspan="3">
</td>
</tr>
</table>
I used this tutorial http://www.dotnetcurry.com/aspnet/1006/edit-html-table-crud-knockoutjs-aspnet-webapi to create an editable table with KnockOutJS, without adding the ASP.NET stuff (only the KO part, server-side API is implemented in PHP).
The tutorial works but I added a new feature which doesn't. Instead of outputting a text field I modified the instructions of the author to add a button instead of it in the table. What I am trying to achieve is to read the contents of a file image, store it in a variable and append in POST payload so as to be stored in a blob field in a database table.
Can someone please suggest an alternative way to achieve this or guide me to correct the existing one ? I'm quite a newbie to KnockOutJS and furthermore in Javascript.
var self = this;
//S1:Boolean to check wheather the operation is for Edit and New Record
var IsNewRecord = false;
// filename to be converted into string for uploading
var ImgFile = "";
var handleFileSelect = function(evt) {
var files = evt.target.files;
var file = files[0];
//console.log("In handleFileSelect");
if (files && file) {
var reader = new FileReader();
reader.onload = function(readerEvt) {
ImgFile = readerEvt.target.result;
//console.log("Printing the base64 ...");
//console.log(readerEvt.target.result);
};
reader.readAsBinaryString(file);
}
};
function executeCreateListener() {
if (window.File && window.FileReader && window.FileList && window.Blob) {
//console.log("In if");
document.getElementById('filePicker').addEventListener('change', handleFileSelect, false); // this sh** resolves to null due to KO dynamic nature
} else {
alert('The File APIs are not fully supported in this browser.');
}
}
self.ProductsApallou = ko.observableArray([]);
loadProducts();
//S2:Method to Load all Products by making call to WEB API GET method
function loadProducts() {
alert("Loading Data");
$.ajax({
type: "GET",
url: "http://127.0.0.1/goandwin/store_products.json?retrieve:Store_of_Product=1+Store_Product_id=999+Name=999+Subname=999+Imgname=999+Price=999+Product_Discount=999+Slogan=999+Origin=999+Description=999+Product_Code=999+Category_level_1_id=999+Product_Photo=999",
dataType: "json",
}).done(function(data) {
self.ProductsApallou(data);
}).fail(function(err) {});
alert("Success");
};
//S3:The Product Object
function Product(soproduct, spid, pname, subname, imgname, price, product_disc, slogan, origin, descript, product_code, cbid, pphoto) {
return {
Store_of_Product: ko.observable(soproduct),
Store_Product_id: ko.observable(spid),
Name: ko.observable(pname),
Subname: ko.observable(subname),
Imgname: ko.observable(imgname),
Price: ko.observable(price),
Product_Discount: ko.observable(product_disc),
Slogan: ko.observable(slogan),
Origin: ko.observable(origin),
Description: ko.observable(descript),
Product_Code: ko.observable(product_code),
Category_level_1_id: ko.observable(cbid),
Product_Photo: ko.observable(pphoto)
}
};
//S4:The ViewModel where the Templates are initialized
var ProdViewModel = {
readonlyTemplate: ko.observable("readonlyTemplate"),
editTemplate: ko.observable()
};
//S5:Method to decide the Current Template (readonlyTemplate or editTemplate)
ProdViewModel.currentTemplate = function(tmpl) {
return tmpl === this.editTemplate() ? 'editTemplate' : this.readonlyTemplate();
}.bind(ProdViewModel);
//S6:Method to create a new Blank entry When the Add New Record button is clicked
ProdViewModel.addnewRecordApallou = function() {
self.ProductsApallou.push(new Product(1, "auto", "default", "default", "default", 0, 0, "default", "default", "default", "default", 1, "default"));
IsNewRecord = true;
};
//S7:Method to Save the Record (This is used for Edit and Add New Record)
ProdViewModel.saveProduct = function(d) {
var Prod = {};
//console.log(d);
Prod.Store_of_Product = d.Store_of_Product;
Prod.Store_Product_id = d.Store_Product_id;
Prod.Name = d.Name ? d.Name : null;
Prod.Subname = d.Subname ? d.Subname : null;
Prod.Imgname = d.Imgname ? d.Imgname : null;
Prod.Price = d.Price ? d.Price : 0.0;
Prod.Product_Discount = d.Product_Discount ? d.Product_Discount : 0;
Prod.Slogan = d.Slogan ? d.Slogan : null;
Prod.Origin = d.Origin ? d.Origin : null;
Prod.Description = d.Description ? d.Description : null;
Prod.Product_Code = d.Product_Code ? d.Product_Code : null;
Prod.Category_level_1_id = d.Category_level_1_id ? d.Category_level_1_id : 1;
//console.log("Printing imgfile ...");
//console.log(ImgFile);
// <---- HERE what I am trying to achieve, if possible
if (ImgFile) {
Prod.Product_Photo = ImgFile; //take the string produced after uploaded
} else {
Prod.Product_Photo = d.Product_Photo; //take the string as it was
}
// ---->
//Edit the Record
if (IsNewRecord === false) {
$.ajax({
type: "PUT",
url: "http://127.0.0.1/goandwin/store_products/" + Prod.Store_Product_id,
contentType: "application/x-www-form-urlencoded; charset=utf-8",
data: Prod
}).done(function(data) {
alert("Record Updated Successfully " + data.status);
ProdViewModel.reset();
}).fail(function(err) {
alert("Error Occured, Please Reload the Page and Try Again " + err.status);
ProdViewModel.reset();
});
}
//The New Record
if (IsNewRecord === true) {
var tmp = Prod;
delete tmp.Store_Product_id; //remove the PK which is auto
IsNewRecord = false;
$.ajax({
type: "POST",
url: "http://127.0.0.1/goandwin/store_products",
contentType: "application/x-www-form-urlencoded; charset=utf-8",
data: tmp
}).done(function(data) {
alert("Record Added Successfully " + data.status);
ProdViewModel.reset();
loadProducts();
}).fail(function(err) {
alert("Error Occured, Please Reload the Page and Try Again " + err.status);
ProdViewModel.reset();
});
}
}
//S8:Method to Delete the Record
ProdViewModel.deleteProduct = function(d) {
$.ajax({
type: "DELETE",
url: "http://127.0.0.1/goandwin/store_products/" + d.Store_Product_id
}).done(function(data) {
//console.log(d.Store_Product_id);
alert("Record Deleted Successfully " + data.status);
ProdViewModel.reset();
loadProducts();
}).fail(function(err) {
alert("Error Occured, Please Reload the Page and Try Again " + err.status);
ProdViewModel.reset();
});
}
//S9:Method to Reset the template
ProdViewModel.reset = function(t) {
this.editTemplate("readonlyTemplate");
};
ko.applyBindings(ProdViewModel);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<div class="tab-content">
<div id="Apallou" class="tab-pane fade in inactive">
<table class="table table-striped table-bordered table-hover" id="dataTables-exampleApallou">
<thead>
<tr>
<th>Store_of_Product</th>
<th>Store_Product_id</th>
<th>Name</th>
<th>Subname</th>
<th>Imgname</th>
<th>Price</th>
<th>Product_Discount</th>
<th>Slogan</th>
<th>Origin</th>
<th>Description</th>
<th>Product_Code</th>
<th>Category_level_1_id</th>
<th>Product_Photo</th>
<th></th>
<th></th>
</tr>
</thead>
<tbody data-bind="template: { name: currentTemplate, foreach: ProductsApallou }"></tbody>
</table><br><input type="button" value="Add New Record" data-bind="click: function () { ProdViewModel.addnewRecordApallou(); }" /><br></div>
</div>
</div>
</div>
</div>
</div>
<!-- /#wrapper -->
<script type="text/html" id="readonlyTemplate">
<tr>
<td><span data-bind="text: Store_of_Product"></span></td>
<td><span data-bind="text: Store_Product_id"></span></td>
<td><span data-bind="text: Name"></span></td>
<td><span data-bind="text: Subname"></span></td>
<td><span data-bind="text: Imgname"></span></td>
<td><span data-bind="text: Price"></span></td>
<td><span data-bind="text: Product_Discount"></span></td>
<td><span data-bind="text: Slogan"></span></td>
<td><span data-bind="text: Origin"></span></td>
<td><span data-bind="text: Description"></span></td>
<td><span data-bind="text: Product_Code"></span></td>
<td><span data-bind="text: Category_level_1_id"></span></td>
<td><img width="60px" height="70px" data-bind="attr:{src: Product_Photo}" /></td>
<td>
<input type='button' value='Edit' data-bind='click: function () { ProdViewModel.editTemplate($data);}'>
</td>
<td>
<input type='button' value='delete' data-bind='click: function () { ProdViewModel.deleteProduct($data); }'>
</td>
</tr>
</script>
<script type="text/html" id="editTemplate">
<tr>
<td><input type='text' data-bind='value: $data.Store_of_Product' /></td>
<td><input type='text' data-bind='value: $data.Store_Product_id' disabled='disabled' /></td>
<td><input type='text' data-bind='value: $data.Name' /></td>
<td><input type='text' data-bind='value: $data.Subname' /></td>
<td><input type='text' data-bind='value: $data.Imgname' /></td>
<td><input type='text' data-bind='value: $data.Price' /></td>
<td><input type='text' data-bind='value: $data.Product_Discount' /></td>
<td><input type='text' data-bind='value: $data.Slogan' /></td>
<td><input type='text' data-bind='value: $data.Origin' /></td>
<td><input type='text' data-bind='value: $data.Description' /></td>
<td><input type='text' data-bind='value: $data.Product_Code' /></td>
<td><input type='text' data-bind='value: $data.Category_level_1_id' /></td>
<td>
<div><label for="filePicker">Choose a file:</label><input type="file" id="filePicker"></div>
</td>
<td>
<input type="button" value="Save" data-bind="click: ProdViewModel.saveProduct" />
</td>
<td>
<input type="button" value="Cancel" data-bind="click: function () { ProdViewModel.reset(); }" />
</td>
</tr>
</script>
I know my explanation of what I'm trying to do is somehow vague, so feel free to ask questions to make things clear. My project lies here if someone wishes to check it out (dpesios, test).
My project having a problem that when table row button clicked it will appear on the html input typ="text" for user updation.Updation running successfully.What i need is,when user clicked update button the updated row must replace with new row + another button for again updation.
html
<h1>Time Management</h1>
<fieldset>
<h3>Update Test!</h3>
<form action="#" th:action="#{/admin/updateTest.html}"
th:object="${test}" id="formTest">
<table>
<tr>
<td>Test Name</td>
<td><input type="text" id="testName" required="required"
th:field="*{name}" disabled="disabled"/></td>
</tr>
<tr>
<td>Max No.of Questions</td>
<td><input type="text" id="questionNo" required="required"
th:field="*{maxNoQuestions}" onKeyUp="numericFilter(this);" /></td>
</tr>
<tr>
<td>Max Time</td>
<td><input data-format="hh:mm:ss" type="text" id="testTime"
required="required" th:field="*{maxTime}" />
</td>
</tr>
<tr>
<td><input type="button" value="Update" id="btnUpdate" /> <input
type="hidden" th:field="*{id}" id="hdnTestId" /></td>
<td><label id="statusMsg"
style="color: red; size: portrait; font-size: small;"></label></td>
</tr>
</table>
</form>
</fieldset>
<table id="tests"
style="cellpadding: 0px; cellspacing: 0px; border: 0px;">
<thead>
<tr>
<th width="5%">#</th>
<th align="left">Test Name</th>
<th align="left">Max No.of Questions</th>
<th align="left">Max Time</th>
<th align="left"></th>
</tr>
</thead>
<tbody>
</tbody>
</table>
below is my backbone script for updation.
script
var TimeManagementView = Backbone.View.extend({
sTable:null,
// target item.
el : $("#adminContentOuterPnl"),
render : function() {
var data = {};
// template
var compiledTemplate = _.template(timeManagementTemplate, data);
// append the item to the view's target
this.$el.html(compiledTemplate);
sTable = $('#tests').dataTable({
"aoColumns" : [ null, null, null, null, null ],
"sPaginationType" : "full_numbers"
});
//load data from db to table.
this.loadSavedTests();
},
// Event Handlers
events : {
"click #btnUpdate" : "updateTest"
},
loadSavedTests : function() {
$('#tests tbody tr').remove();
$('#tests tbody').append('<tr><td><h4>...Loading...</h4></td></tr>');
//Load the data in using jQuerys ajax call
$.ajax({
type : 'POST',
url : 'loadAllTests.html',
success: function(responseData) {
sTable.fnClearTable();
if(responseData.length > 0){
$.each(responseData, function(index,item) {
var rowCount = index+1;
sTable.fnAddData( [ rowCount,item['name'], item['maxNoQuestions'], item['maxTime'],'<input type="image" src="../resources/img/icons/edit.png" alt="Edit" onclick="editTest('+item['id']+',this); return false;" />' ]);
});
}
}
});
},
updateTest : function(){
$('#statusMsg').text("");
if($('#testName').val()==''){
$('#statusMsg').text("Test Name Can't Be Null");
return false;
}
if($('#questionNo').val()==''){
$('#statusMsg').text("Question No. Can't Be Null");
return false;
}
if($('#testTime').val()==''){
$('#statusMsg').text("Test Time Can't Be Null");
return false;
}
$('#statusMsg').text("Updating...");
$("#formTest").ajaxForm({
success : function(status) {
if (status == 1) {
// addRowToTests(status.object);
testRow.find("td").eq(0).text($('#testName').val());
testRow.find("td").eq(1).text($('#questionNo').val());
testRow.find("td").eq(2).text($('#testTime').val());
$('#testName').val('');
$('#questionNo').val('');
$('#testTime').val('');
$('#statusMsg').text("Data Updated!");
}
},
dataType : 'json'
}).submit();
}
});
return new TimeManagementView;
});
$("#formTest").ajaxForm({
success : function(status) {
console.log(status.statusCode);
if (status.statusCode == 0) {
testRow.find("td").eq(1).text('');
testRow.find("td").eq(2).text('');
testRow.find("td").eq(3).text('');
testRow.find("td").eq(4).text('');
testRow.find("td").eq(1).text($('#testName').val());
testRow.find("td").eq(2).text($('#questionNo').val());
testRow.find("td").eq(3).text($('#testTime').val());
testRow.find("td").eq(4).html('<input type="image" src="../resources/img/icons/edit.png" alt="Edit" onclick="editTest('+status.object.id+'); return false;" />');
$('#testName').val('');
$('#questionNo').val('');
$('#testTime').val('');
$('#statusMsg').text("Data Updated!");
}else{
$('#statusMsg').text("No Change");
}
},
dataType : 'json'
}).submit();