How to bind data in table in asp using jquery? - javascript

** HI friends .I try to bind the data in table using jquery.But is not working and the value is not showing .I am a beginner in jquery.
Can you modify my code. And can you say which is more good and fast to bind values asp or jquery**
<script src="Data_Table.js"></script>
<script>
$(document).ready(function (){
bind(res);
});
function bind(res) {
url = "XXXX.aspx/XXXXXX";
var rows = JSON.parse(res.d);
if (res.d != "[]") {
var data = [];
$.each(rows, function (index, row) {
data.push([++index
, row.Id
, row.date
, row.shift
, row.Door
, row.Green
, row.Time
, row.Cycle
, row.Fault
]);
});
table = $("#XXX").DataTable({
destroy: true,
data: data,
deferRender: true,
paging: true,
});
} else {
alert("No Record Found");
}
}
</script>

Related

Query duplicates after each onClick

I have an add feature that runs an insert query (using PDO).
The first insert works accordingly. It's the second run, and every run after that causes the query to duplicate times 2.
I have no idea why this is happening.
The user makes a selection, which populates a datatable (example1). They can then select one of the records (or lanes) which populates another datatable (example2).
Here is the initial onClick event:
$('#example1').on('click', 'tr > .laneClick', function(e){
e.preventDefault();
const dataTable = $('#example1').DataTable();
const rowData = dataTable.row($(this).closest('tr')).data();
let partnerCode = rowData['partner_code'];
let partnerName = rowData['partner_name'];
let groupName = rowData['groupname'];
let lanecriteria = {
partnerCode: partnerCode,
partnerName: partnerName,
groupName: groupName
}
displayLaneRecords(lanecriteria);
});
Here is the function displayLaneRecords, which displays the second datatable called "example2" after the .laneClick onClick event:
function displayLaneRecords(lanecriteria){
if(lanecriteria == ""){
let data = '';
}
else{
let data = {
lanecriteria: {
partnerCode: lanecriteria.partnerCode,
vesselProfile: lanecriteria.vesselProfile,
salesRep: lanecriteria.salesRep
}
}
}
$.ajax({
url: 'api/getLaneData.php',
type: 'POST',
data: data,
dataType: 'html',
success: function(data, textStatus, jqXHR){
var jsonObject = JSON.parse(data);
var table = $('#example2').DataTable({
"data": jsonObject,
"columns": [
// data columns
],
"dom": 'Bfrtip',
"buttons": [
{
text: '<i class="fa fa-plus"></i> Add Lane',
className: 'addLane btn btn-primary btn-sm',
action: function (e, dt, node, config){
// opens the form for processing
$('#addLaneModal').modal('show');
}
}
]
});
},
error: function(jqHHR, textStatus, errorThrown){
console.log('fail: '+ errorThrown);
return false;
}
}); // end ajaxcall
// here is where the form process will occur
} // end displayLaneRecords();
As you will see, the form process will occur within the displayLaneRecords() function. I had to do this so when the process is complete, I can repopulate the datatable without refreshing.
Here is the form process:
$('#addLaneSubmit').on('click', function(e){
e.preventDefault();
let partnerCode = $('#addlanepartnercode').val();
let partnerName = $('#addlanepartnername').val();
let groupName = $('#addlanegroupname').val();
let addlanecriteria = {
partnerCode: partnerCode,
partnerName: partnerName,
groupName: groupName
}
$.post('api/editLane.php', {addlanecriteria:addlanecriteria}, function(data){
if(data.indexOf('Error') > 1){
$('.message').text(data);
$('#errorModal').modal('show');
return false();
}
else{
$('.message').text(data);
$('#messageModal').modal('show');
$('#messageModal').on('hidden.bs.modal', function(){
$("#addLaneModal").modal('hide');
displayLaneRecords(lanecriteria); // call displayLaneRecords to refresh the table
});
}
});
});
The actual PHP process called editLane.php looks like this:
<?php
if(isset($_POST['addlanecriteria'])){
$value = $_POST['addlanecriteria'];
$partnerCode = isset($value['partnerCode']) ? $value['partnerCode'] : '';
$partnerName = isset($value['partnerName']) ? $value['partnerName'] : '';
$groupName = isset($value['groupName']) ? $value['groupName'] : '';
try{
$dbc->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$insert = $dbc->prepare("INSERT INTO table (`partner_code`, `partner_name`, `group_name`) VALUES (:newpartnercode, :newpartnername, :newgroupname)");
$insert->execute([
'newpartnercode' => $partnerCode ,
'newpartnername' => $partnerName ,
'newgroupname' => $groupName
]);
if($insert){
echo "Success: New Lane has been added.";
}
}
catch(PDOException $e){
echo "Error: " . $e->getMessage();
}
}
?>
I tried to minimize as much code as I could.
All of the above works without any visible errors. When the form is submitted, a new record is inserted into the table, and the datatable refreshes without the page refreshing.
The problem occurs when the user adds another record - the query duplicates, and instead of inserting 1 record, 2 are inserted. If they add another record, the query will insert 4 records.
What can I try next?

jQuery Datatables with Dynamic Data

I have a simple messaging system and I am retrieving the messages from the DB using jQuery/AJAX and appending to a table. I wanted pagination for the messages so I opted to use the DataTables plugin (https://datatables.net/).
I am having trouble using this with my dynamically generated data. I also have functions such as "delete message" which would then delete the message and then retrieve the messages again (refresh the table). I am getting the error "cannot re-initialise DataTable".
This is my code so far:
function getmessages(){
$.ajax({
type: "POST",
url: "modules/ajaxgetmessages.php",
dataType: 'json',
cache: false,
})
.success(function(response) {
if(!response.errors && response.result) {
$("#tbodymessagelist").html('');
$.each(response.result, function( index, value) {
var messagesubject = value[3];
var messagecontent = value[4];
var messagetime = value[5];
var sendername = value[2];
var readstatus = value[7];
var messageid = value[8];
if (readstatus==0){
messageheader += '<tr><td><input type="checkbox" class="inboxcheckbox input-chk"></td><td class="sendername"><b>'+sendername+'</b></td><td class="messagesubject"><b>'+messagesubject+'</b></td><td><b>'+messagetime+'</b></td><td class="messageid" style="display:none">'+messageid+'</td><td class="readstatus" style="display:none">'+readstatus+'</td><td class="messagecontent" style="display:none"><b>'+messagecontent+'</b></td></tr>';
} else {
messageheader += '<tr><td><input type="checkbox" class="inboxcheckbox input-chk"></td><td class="sendername">'+sendername+'</td><td class="messagesubject">'+messagesubject+'</td><td>'+messagetime+'</td><td class="messageid" style="display:none">'+messageid+'</td><td class="readstatus" style="display:none">'+readstatus+'</td><td class="messagecontent" style="display:none"><b>'+messagecontent+'</b></td></tr>';
}
});
$("#tbodymessagelist").html(messageheader);
$('#tblinbox').DataTable({
"paging": true,
"ordering": false,
"info": false
});
} else {
$.each(response.errors, function( index, value) {
$('input[name*='+index+']').addClass('error').after('<div class="errormessage">'+value+'</div>')
});
}
});
}
So how can I essentially, make changes to my table after message deletion or other functions and then "refresh" the table? It also shows Showing 0 to 0 of 0 entries in the footer even though there are entries there.
You must destroy datatable berfore create new instance;
`
$('#tblinbox').DataTable.destroy();
$('#tblinbox').empty();

how to get $this value in array in javascript

In message variable I am getting the multiple selected, how to store them in array, after this store in database?
<script type="text/javascript">
$(function () {
$('#lstFruits').multiselect({
includeSelectAllOption: true
});
$('#btnSelected').click(function () {
var selected = $("#lstFruits option:selected");
// document.write(selected);
//.var array = string.split(",").val(selected);
var message = "";
selected.each(function () {
message += $(this).val();
// here I am getting the selected ids like 2,4,5 and I
// want to submit all ids in the database.
// While, when I am submitting currently only the last
// id is being submitted.
var vale = [$(this).val()];
//document.write(vale);
$('#second').val(vale);
});
alert(message);
});
});
</script>
How to store all selected values in array and then submit in php page by query?
Try to save the values in array & name of the field whose id is second should be like second[]
<script type="text/javascript">
$(function () {
$('#lstFruits').multiselect({
includeSelectAllOption: true
});
$('#btnSelected').click(function () {
var selected = $("#lstFruits option:selected");
var message = [];
selected.each(function () {
message.push($(this).val());
});
$('#second').val(message);
alert(message);
});
});
</script>
For example, you can submit this to php by ajax. (With GET or POST query)
Another guide about ajax
Example
$.post('yourphpfile.php', {data: JSON.stringify(message)})
.done(function(data) { console.log('success'); })
.fail(function() { console.log('error');
// in youphpfile.php
$_POST['data'] ? yourFunctionToInsert($_POST['method']) : null;
btw, to insert in array in your js file, you can also do:
message[] = $(this).val(); //in the loop
$(function () {
$('#lstFruits').multiselect({
includeSelectAllOption: true
});
//create array variable
var selectedValues = new Array();
$('#btnSelected').click(function () {
var selected = $("#lstFruits option:selected");
selectedValues.push(selected);
//then by use=ing ajax you can send this array
$.ajax({
type: "POST",
data: {info:selectedValues},
url: "page.php",
success: function(msg){
$('.answer').html(msg);
}
});
});
});
You can make array then by useing .push method can store values in array, after that by ajax you can send over PHP page.

Unable to construct DataTable using data retrieved from Parse.com

In my project I'm using Parse.com as server and database, and DataTable plugin to create a table showing the data returned. There's no problem when I use a predefined json file, but when I try to construct a local json file using the data returned from Parse.com I get an error. It seems no matter what I do, the table creation process is run first and only afterwards the json object is created.
JSfiddle with the relevant code is here. Please note that due to the large amount of code I did not provide a working sample, but only the relevant part.
function getDataFromParse(){
console.log("test function run");
var loc_json={
"data":[]
};
//get data from parse
var parseTable = Parse.Object.extend("parseTable");
var tableObj = new parseTable();
var query = new Parse.Query(parseTable);
var count=0;
query.descending("createdAt");
query.find({
success: function(resultArr){
console.log("retreiving data from parse");
for(var i=0;i<resultArr.length;i++){
query.get(resultArr[i].id,{
success: function(tableObj){
var ret_phone = tableObj.get("phone");
var ret_first = tableObj.get("firstName");
var ret_last = tableObj.get("lastName");
var ret_status = tableObj.get("redemption_status");
var ret_vipCode = tableObj.get("vipCode");
loc_json.data.push([count,ret_first +" "+ret_last,ret_phone,tableObj.get("createdAt"),ret_vipCode]); //construction of local json
count++;
console.log("finished fetching data for "+ret_first+" "+ret_last);
},
error: function(object, error) {
console.log("could not do something "+error.message);
}
});
}
console.log("success function end");
},
error: function(error){
console.log(error.message);
}
});
console.log("trying to return json");
return loc_json;
}
var rows_selected = [];
console.log("table creation");
var table = $('#example').DataTable({
ajax: getDataFromParse(), // ajax: 'https://api.myjson.com/bins/4qr1g', THIS WORKS!!
columns: [
{},
{ data: 1},
{ data: 2 },
{ data: 3 }
],
'columnDefs': [{
'targets': 0,
'searchable':false,
'orderable':false,
'className': 'dt-body-center',
'render': function (data, type, full, meta){
return '<input type="checkbox">';
}
}],
'order': [1, 'asc'],
'rowCallback': function(row, data, dataIndex){
// Get row ID
$('input.editor-active', row).prop( 'checked', data[3] == 1 )
var rowId = data[0];
// If row ID is in the list of selected row IDs
if($.inArray(rowId, rows_selected) !== -1){
$(row).find('input[type="checkbox"]').prop('checked', true);
$(row).addClass('selected');
console.log("table trying to create itself");
}
}
});
SOLUTION
Remove ajax option from DataTables initialization options.
Call getDataFromParse() after initializing the DataTable
In the success handler for each query, replace this line:
loc_json.data.push([count, ret_first + " " + ret_last, ret_phone, tableObj.get("createdAt"), ret_vipCode]);
with the line below to add a new row to the table.
$('#example').DataTable()
.row.add([
count,
ret_first + " " + ret_last,
ret_phone,
tableObj.get("createdAt"),
ret_vipCode
])
.draw(false);
DEMO
See this jsFiddle for code and demonstration.
NOTES
The drawback of this solution is that a new row would be added once each query finishes successfully. Not sure if it is possible with Parse.com to handle event when all queries are completed.
Your example uses jQuery DataTables 1.9 but you're using option names and API from 1.10. You need to upgrade your jQuery DataTables library.
You're supplying data to jQuery DataTables using ajax option were in fact you should be using data option instead.
Remove code after // FOR TESTING ONLY as it was needed for demonstration only in jQuery DataTables - Row selection using checkboxes article and is not needed for production.

How to reload a div with jquery

I am new to jQuery.
I have to reload a div after sending some values to server using ajax.
My jQuery code is
selectionChanged: function () {
var $selectedRows = $('#PersonTableContainer').jtable('selectedRows');
$selectedRows.each(function () {
var record = $(this).data('record');
var columnname = record.columnname;
var datatype = record.datatype;
var columnlength = record.columnlength;
$.post('meta?action=dataload', {
columnname: columnname, datatype: datatype, columnlength: columnlength
});
});
after this code is executed I want to reload a div
<div id="loadedtablecontainer"></div>
this div will get the selected data of 1st jtable .. and display it in this jtable.
So by using this div id I have to call or reload this div soon after above jQuery function got executed
Something like
$.post('meta?action=dataload', {
columnname: columnname, datatype: datatype, columnlength: columnlength
});
$("#loadedtablecontainer");
So I am assuming the Ajax call returns the new content, so set the html() in the callback.
$.post('meta?action=dataload',
{
columnname : columnname,
datatype:datatype,
columnlength:columnlength
},
function (data) {
$( "#loadedtablecontainer" ).html(data);
}
);
You have a callback parameter which returns your result from post. Use that to manipulate the data and form the HTML. Then simply append it
$.post('meta?action=dataload', {
columnname : columnname, datatype:datatype,columnlength:columnlength
},
function (result) {
// make your manipulations here, (Ex: var manipulatedHTML )
$("#loadedtablecontainer" ).append(manipulatedHTML );
}
);
If its a json
function(result) {
//result is your json
var manipulatedHTML = '<div class="result">'+result.value"+'</div>';
}
$("#loadedtablecontainer" ).append(manipulatedHTML )
Use a for loop if its a json array
function loadCustomerCorpPopup(id) {
$("#eBody").mask("${loading}");
$.ajax({
url : '${url}/customer/ajax_customer_corporate_popup',
data : {
customerCorporateId : id,
},
dataType : 'text',
cache : false,
success : function(data) {
$('#popupId').html(data);
$('#popupId').modal('show');
$("#eBody").unmask("${loading}");
}
});
}
You can use this way $('#popupId').html(data);
data can a html code or url.

Categories