Display ajax response in Table - javascript

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

Related

Pass values using JSON via Ajax Call

I am beginner on JSON. In my web application I am trying convert the table values into JSON and pass to another page using ajax call.
Below is my ajax query which I tried to convert the table values and pass to prescription.php page to save the records. There are two different separate java script variables which need to sent to the above page.
<script>
$(document).ready(function () {
$(document).on('click', '#submit', function () {
var getapt = $('#getapt').val();
var getpid = $('#getpid').val();
var ids={
'getapt': getapt,
'getpid': getpid,
}
var modess = $('#rows tr').map(function() {
let $tr = $(this);
return [{
"medname": $(this).find('.med_name').val(),
"morning": $(this).find('.morning').val(),
"noon": $(this).find('.noon').val(),
"night": $(this).find('.night').val(),
}]
console.log(modess);
});
var ids = JSON.stringify(ids);
var medical = JSON.stringify(modess);
$.ajax({
url: "adminquery/prescription.php", // Url to which the request is send
type: "POST", // Type of request to be send, called as method
data:{
index1: medical,
index2: ids
},
dataType:'json',
cache: false,
contentType: false,
processData: false,
async: false,
//contentType: "application/json; charset=utf-8",
})
});
});
</script>
Here is my prescription.php page
<?php
session_start();
require_once "../auth/dbconnection.php";
// if (isset(json_decode($_POST["data"])) {
$medical = json_decode($_POST["data"]);
if($stmt = mysqli_prepare($conn,"INSERT INTO prescription (apt_id,user_id,p_id, med_records,date) VALUES (?, ?, ?, ?, ?)")){
$user_id = $_SESSION['user_id'];
mysqli_stmt_bind_param($stmt, "sssss", $user_id);
echo "Records inserted successfully.";
} else{
echo "ERROR: Could not prepare query: $sql. " . mysqli_error($conn);
}
// }else{
// echo "now records";
// }
mysqli_stmt_close($stmt);
?>
Here is my HTML codes.
<form method="post" id="prescriptionn" enctype="multipart/form-data">
<div class="table-responsive">
<table class="table table-bordered mb-0" id="medical">
<thead>
<tr>
<th>Medicine Name</th>
<th>Morning</th>
<th>Noon</th>
<th>Night</th>
<th> <button type="button" name="add" id="add" class="btn btn-success btn-xs">
+ </button> </th>
</tr>
</thead>
<tbody id="rows">
</tbody>
</table>
<br><br>
<div align="center">
<input type="hidden" value="<?php echo $row['apt_id'] ?>" id="getapt"
name="getapt" class="btn btn-primary">
<input type="hidden" value="<?php echo $row['p_id'] ?>" id="getpid" name="getpid" class="btn btn-primary">
<input type="button" name="submit" id="submit" class="btn btn-primary" value="Enter Prescription">
</div>
</div>
</form>
But nothing happen when I submit the button. Please give me some suggestions to improve my code may highly appreciated.
Following Method show how to send HTML table data using jQuery Ajax and save in Database. Hope this will help.
function storeTblValuesSpecial(x)
{
var TableData = new Array();
$('#'+x+''+' tr').each(function(row, tr){
TableData[row]={
"columOne" :$(tr).find('td:eq(1)').text()
, "columTwo" : $(tr).find('td:eq(2)').text()
, "columThree" : $(tr).find('td:eq(3)').text()
}
});
TableData.shift(); // first row will be empty - so remove
return TableData;
}
function storeTblValuesAjax(y) {
var TableData;
TableData = JSON.stringify(storeTblValuesSpecial(y));
$.ajax({
type: "POST",
url: '../yourFile.php',
data: {
"pTableData" : TableData
},
success: function(msg){
alert('Success');
}
});
}
<table id="table1" class="table table-dark" border="1">
<thead>
<tr>
<th scope="col">columOne</th>
<th scope="col">columTwo</th>
<th scope="col">columThree</th>
</tr>
</thead>
<tbody>
<tr>
</tr>
</tbody>
</table>
<button type="button" class="btn-danger" id = "delete" onclick="storeTblValuesAjax('table1')" >Save Table</button>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
From PHP File once the Post Request Sent through Ajax Call
<?php
session_start();
// Unescape the string values in the JSON array
$tableData = stripcslashes($_POST['pTableData']);
// Decode the JSON array
$records = json_decode($tableData,TRUE);
$sizeOfArray = sizeof($records);
for($test = 1; $test < $sizeOfArray; $test++)
{
$columOne= str_replace(",","",$records[$test]['columOne']);
$columTwo= str_replace(",","",$records[$test]['columTwo']);
$columThree= str_replace(",","",$records[$test]['columThree']);
/* From Here a general SQL Insert query , pass $columOne , $columTwo , $columThree as the insert values, the loop will continue until the entire table is saved */
}

How to reload view after AJAX POST

Being new to AJAX I have encountered this problem and have had no luck resolving it. I want my table to be refreshed after an ajax post to review an object, everything I've tried has been futile.
Assume the ajax response is a JSON result, to avoid posting my OnPost() code.
I send the Id of the product using ajax and then use that Id to remove the product
I then call the same method OnGet() uses to populate the tables which returns the updated list. In chrome debug tools I see the response successfully returns with the updated list. I just don't know how to get it across back to my list. Thanks in advance guys.
#Html.AntiForgeryToken()
<table id="shoppingBag" class="table">
<thead>
<tr>
<th scope="col">Item</th>
<th scope="col">Price</th>
<th scope="col">Quantity</th>
</tr>
</thead>
<tbody>
#foreach (var item in Model.ShoppingBagItems)
{
<tr>
<td>
#item.Product.Name
</td>
<td>
#item.Price.ToString("C")
</td>
<td>
<input value="#item.Quantity" size="1" maxlength="1" class="text-center" />
</td>
<td>
<button onclick="remove(#item.Product.Id.ToString())" class="close">
<span aria-hidden="true">×</span>
</button>
</td>
</tr>
}
</tbody>
</table>
<script>
function remove(id) {
$.ajax({
type: 'POST',
url: 'ShoppingBag?handler=Delete',
headers: {
"XSRF-TOKEN": $('input:hidden[name="__RequestVerificationToken"]').val()
},
contentType: 'application/json; charset=utf-8',
dataType: 'json',
data: ''+id+'',
sucess: function (response) {
append_json(response);
}
});
}
function append_json(data){
var table = document.getElementById('shoppingBag');
data.forEach(function(object) {
var tr = document.createElement('tr');
tr.innerHTML = '<td>' +
object.product.name +
'</td>' +
'<td>' +
object.price +
'</td>' +
'<td>' +
object.quantity +
'</td>';
table.appendChild(tr);
});
}
</script>
In Ajax success method after this append_json(response);add below code to refresh the table
$("#shoppingBag").load(window.location + " #shoppingBag");
change:
var table = document.getElementById('shoppingBag');
to:
var table = $('#shoppingBag tbody');
AND
change:
table.appendChild(tr);
to:
table.append(tr);
you are appending your data to main <table> if you inspect your table you can see the appended html.but you need to append data in body of table
for this you can use $("#shoppingBag tbody").append(tr);
or you can add id to <body> like <tbody id="myTestTableBody"> and use this in to your JavaScript
function append_json(data){
var table = document.getElementById('myTestTableBody');
data.forEach(function(object) {
var tr = document.createElement('tr');
tr.innerHTML = '<td>' +
object.product.name +
'</td>' +
'<td>' +
object.price +
'</td>' +
'<td>' +
object.quantity +
'</td>';
table.appendChild(tr);
});
}
I have added a sample code that how you can append data to existing table
var page=1;
function AddData() {
$.ajax({
url: "https://reqres.in/api/users?page="+page,
type: "GET",
success: function(response){
append_json(response.data);
}
});
page++;
}
function append_json(data){
data.forEach(function(object) {
var tr = document.createElement('tr');
tr.innerHTML = '<td>' +
object.first_name +
'</td>' +
'<td>' +
object.last_name +
'</td>' +
'<td>' +
'<img src ='+object.avatar +' width="50px" height="50px" />'+
'</td>';
$("#shoppingBag tbody").append(tr);
});
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="button" value="Add Data" onclick="AddData()">
<table id="shoppingBag" class="table">
<thead>
<tr>
<th scope="col">Item</th>
<th scope="col">Price</th>
<th scope="col">Quantity</th>
</tr>
</thead>
<tbody>
</tbody>
</table>

Django Send output with Ajax but Javascript doesn't work

I want to query the database and show the result don't refresh the page. So I use the Ajax! But when I append or paste the html code, the javascript isn't work. The style of my table is so ugly.
This is table html part that output will be here (ID=output) :
<div class='fresh-table' id="output">
<div class='toolbar'>
<button type='button' id='alertBtn' class='btn btn-info'>Add To Cart</button>
</div>
<table id='fresh-table' class='table'>
<thead>
<th data-field='state' data-checkbox='true'></th>
<th data-field='id' data-sortable='true'>id</th>
<th data-field='name' data-sortable='true'>candidate</th>
<th data-field='salary' data-sortable='true'>salary</th>
<th data-field='gpa' data-sortable='true'>gpa</th>
<th data-field='position'>position</th>
<th data-field='actions' class='td-actions text-right' data-formatter='operateFormatter' data-events='operateEvents'>Actions</th>
</thead>
<tbody>
{% for candidate in Candidate %}
<tr data-val='{{candidate.id_number}}'>
<td></td>
<td><a href='/filter/{{candidate.id_number}}/' style='color: #ff9800; font-weight: 400;'>{{candidate.id_number}}</a></td>
<td>{{ candidate.name_title }} {{candidate.firstname}} &nbsp&nbsp {{candidate.lastname}}</td>
<td>{{candidate.salary}}</td>
<td>{{candidate.nowEdu_gpa}}</td>
<td>{{candidate.position}}</td>
<td></td>
</tr>
{% endfor%}
</tbody>
</table>
</div>
This is Ajax in template:
$.ajax({
type: 'POST',
url: 'testajax/',
dataType: "json",
async: true,
data: {
filter_option: json_filter_option,
operator_position: json_operator_position,
filter_position: json_filter_position,
csrfmiddlewaretoken: "{{ csrf_token }}"
},
success: function(json) {
console.log(json.message)
html = "<div class='toolbar'> <button type='button' id='alertBtn' class='btn btn-info'>Add To Cart</button></div><table id='fresh-table' class='table'><thead><th data-field='state' data-checkbox='true'></th><th data-field='id' data-sortable='true'>เลขประจำตัวประชาชน</th><th data-field='name' data-sortable='true'>ชื่อผู้สมัคร</th><th data-field='salary' data-sortable='true'>เงินเดือนที่คาดหวัง</th><th data-field='gpa' data-sortable='true'>เกรดเฉลี่ยสะสม</th><th data-field='position'>ตำแหน่งที่สมัคร</th><th data-field='actions' class='td-actions text-right' data-formatter='operateFormatter' data-events='operateEvents'>Actions</th></thead><tbody>";
$.each(json.message, function(index, candidate) {
html += "<tr data-val='" + candidate[0] + "'><td></td><td><a href='/filter/" + candidate[0] + "/' style='color: #ff9800; font-weight: 400;'>" + candidate[0] + "</a></td><td>{{ candidate.name_title }} {{candidate.firstname}} &nbsp&nbsp {{candidate.lastname}}</td><td>{{candidate.salary}}</td><td>{{candidate.nowEdu_gpa}}</td><td>{{candidate.position}}</td><td></td></tr>";
});
html += "</tbody></table>";
$('#output').html(html);
}
})
Please help me. This project is so important for me.
The style of table that I use is from : https://www.creative-tim.com/product/fresh-bootstrap-table
This is my view.py
def test_ajax(request):
if request.method == 'POST':
print("Entryy")
filter_option = json.loads(request.POST.get('filter_option'))
operator_position = json.loads(request.POST.get('operator_position'))
filter_position = json.loads(request.POST.get('filter_position'))
print("filter_option",filter_option)
print("operator_position",operator_position)
print("filter_position",filter_position)
all_candidate = CandidateBasic.objects.all().values_list('id_number')
response_data = {}
try:
response_data['result'] = "Success"
response_data['message'] = list(all_candidate)
print(response_data)
except Exception as e:
response_data['result'] = "Fail"
response_data['message'] = "Fail!"
return HttpResponse(json.dumps(response_data), content_type="application/json")
This might just be a start, but in your AJAX $.each, you populate a lot of data but don't actually do anything with it. All you put into your page HTML is your html, which doesn't appear to have any view context in it. Maybe you want to consider using JsonResponse instead of HttpResponse

var query not returning required results

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>

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