jQuery.ajax - Updating a table cell with new value - javascript

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.

Related

How to render the AJAX response in the JSP/HTML element (returned from db)

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.

Reading file contents and POSTing in combination with KO mechanism

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).

jQuery set value to delegated input fields

I have the HTML code as follows.
<table id="items">
<tr class="item-row">
<td class="item-name"><div class="delete-wpr"><a class="delete" href="javascript:;" title="Remove row">-</a></div></td>
<td><input type="text" id="slslno" class="slno"/></td>
<td><input type="text" class="cost"/></td>
<td><input type="text" class="qty"/></td>
<!-- <td><span class="price"></span></td>-->
<td class="price"></td>
<a class="add" id="addrow" href="javascript:;" title="Add a row">+</a> </tr>
</table>
It has a button named "Add a row" which adds more rows dynamically.
Then I have this bind, which calls an update function during blur of the slno field.
function bind()
{
$(".slno").blur(update_unitcost);
}
The function update_unitcost is as follows.
function update_unitcost()
{
var unitprice1=$(this).val();
unitprice={"unitpricereal":unitprice1};
$.ajax({
type: "POST",
url: "findcost.php",
data: unitprice,
success: function(unitp){
$( ".cost" ).val(unitp);
}
});
}
In the above function, I am able to get the values of with the this selector, but when it comes to setting the value in the following line,
$( ".cost" ).val(unitp);
It just resets every ".cost" classes to that particular number. How can I set values to individual delegated rows? I tried the following approach too, but it failed.
var row = $(this).parents('.item-row');
row.find('.cost').val(unitp);
Set a variable in your function to only target the specific .cost element you wish to update instead of all of them.
function update_unitcost()
{
var unitprice1=$(this).val();
var costItem = $(this).parent().parent().find('td input.cost');
unitprice={"unitpricereal":unitprice1};
$.ajax({
type: "POST",
url: "findcost.php",
data: unitprice,
success: function(unitp){
costItem.val(unitp);
}
});
}

Display ajax response in Table

display.html :
<div id="display_result" style="display: none"><table class="table">
<p style="float: right;" >Select All<input type="checkbox" class="allcb" data-child="chk" checked/> </p>
<thead>
<tr>
<th>Die No</th>
<th> Status </th>
<th> Location </th>
<th>Select</th>
</tr>
</thead>
<tbody>
</table>
<div id ="issue_button">
<input type="submit" id="submit" class="btn btn-success " value="Recieve" style="width: 150px;"></div>
</div>
Ajax:
var data = JSON.stringify($("#form").serializeArray());
// alert(data);
$.ajax({ // Send the credential values to another checker.php using Ajax in POST menthod
type: 'POST',
data: {
list: data
},
url: 'die_recieving_process.php',
success: function(data) ){
$('#display_result').html(data);
}
});
die_recieving_process.php
while($fetch = mysql_fetch_array($query))
{
if($fetch[1] == "Table Rack" )
{
echo '<tr class="success"><td>'.$fetch[0].'</td><td>'.$fetch[1].'</td><td>'.$fetch[3] . '</td> <td><input type=checkbox class="chk" id=check_box value= '.$fetch[2].' name= check_list[] </td> </tr>';
}
else
{
echo '<tr class="warning"><td>'.$fetch[0].'</td><td>'.$fetch[1].'</td><td>'.$fetch[3] . '</td> <td><input type=checkbox class="chk" id=check_box value= '.$fetch[2].' name= check_list[] checked </td> </tr>';
}
}
Hi friends in display.html I have to display the result processed in die_recieving_process.php . In ajax i've sent all the value to die_recieving_process.php and after fetching the result i've to display the result in display.html
First in you Javascript, you have 2 errors:
Your code overrides existing contents of div, which is the whole table...
And you have one unnecessary bracket in success function declaration
So change this:
success: function(data) ){
$('#display_result').html(data);
}
To this:
success: function(data) {//remove unnecessary bracket
$('#display_result tbody').html(data);//add data - to tbody, and not to the div
}
By the way, using $.post() you can write your javascript code shorter, like this:
var data = JSON.stringify($("#form").serializeArray());
$.post('die_recieving_process.php',{list:data},function(responseData){
$('#display_result tbody').html(responseData); //added to tbody which is inside #display_result
$('#display_result').show();
});
Second you need to close your tbody tag inside the table
Create html table with empty body tags and body id = tBody for example:
<table>
<caption>Smaple Data Table</caption>
<thead>
<tr>
<th>Field 1</th>
<th>Field 2</th>
</tr>
</thead>
<tbody id="tBody"></tbody>
</table>
Use the jquery ajax to load json data in the created table after load button is clicked assuming that my json file is storing userData like userName, age, city:
$('#btnLoadAll').click(function () {
$.ajax({
url: "url/data.json",
dataType: 'json',
success: function (resp) {
var trHTML = '';
$.each(resp, function (i, userData) {
trHTML +=
'<tr><td>'
+ userData.userName
+ '</td><td>'
+ userData.age
+ '</td><td>'
+ userData.city
+ '</td></tr>';
});
$('#tBody').append(trHTML);
},
error: function (err) {
let error = `Ajax error: ${err.status} - ${err.statusText}`;
console.log(error);
}
})
});
If you do not see result, try to remove style="display: none" in display.html

jqgrid can't display data from a variable

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.

Categories