Add button to table row td when fetching data ajax java - javascript

For my course purpose I want to create a dynamic data table using ajax. Here's my Javascript code:
$("#submitcateg").click(function(){
var categ = $("#addcategname").val();
$.ajax({
type: "POST",
url: "ProcatServlet",
data: {"categ":categ, "id":"addcateg"},
success: function(data){
if(data=="true"){
$("#addcategname").hide();
$("#submitcateg").hide();
$("#categtable").show(function(){
$.ajax({
type: "GET",
url: "ProcatServlet",
data: {"id":"getcateg"},
success: function(responseJson) {
if(responseJson!=null) {
$("#categtable").find("tr:gt(0)").remove();
var tablebody = document.getElementById("categtable").getElementsByTagName("tbody");
$.each(responseJson, function(key, value){
var button = document.createElement("input");
button.type="button";
button.id="edit";
button.value="edit";
var rowNew = $("<tr><td></td><td></td></tr>");
rowNew.children().eq(0).text(value);
rowNew.children().eq(1).append(button);
rowNew.appendTo(tablebody);
});
}
}
});
});
$("#addcategtrigger").show();
} else {
alert("failed");
}
}
});
});
Using this code, I can show the data and assigned it to the table perfectly, but when I'm trying to add a button to the next column on the row, the button didn't appear. Please help me where I'm doing it wrong.

Related

after adding data reloading my data table

why is this my data table not reloading?. In my situation, I have a data table named table_clinics that I declared global in my javascript, now I have other function to add a data within the data table, I want to prevent refresh that is why I want my data table to be reloaded after adding new data. Am I doing it wrong?.
Here is my code:
<script type="text/javascript">
var table_clinics;
$(document).ready(function() {
table_clinics = $('#dataTables-clinics').dataTable();
});
function show_clinics() {
$("#dataTables-clinics").dataTable().fnDestroy();
table_clinics = $('#dataTables-clinics').DataTable({
"ajax": {
"url": "<?php echo site_url('clinic_admin/myclinics')?>",
"type": "POST",
},
responsive: true,
bInfo: false,
});
}
</script>
now I have a function to add data from the data table and after success, i want to refresh my data table. Here is my function: i tried : table_clinics.ajax.reload(null,false); but it doesn't reload my data table. how can I do this?
function create_clinic() {
$('#btnCreateClinic').text('Saving...');
$('#btnCreateClinic').attr('disabled',true);
$.ajax({
url : siteurl+"clinic_admin/create_clinic",
type: "POST",
data: $('#frm_create_clinic').serialize(),
dataType: "JSON",
success: function(data)
{
if(data.status) {
table_clinics.ajax.reload(null,false);
alert('Added Sucessfuly');
}
else
{
for (var i = 0; i < data.inputerror.length; i++)
{
$('[name="'+data.inputerror[i]+'"]').parent().parent().addClass('has-error');
$('[name="'+data.inputerror[i]+'"]').next().text(data.error_string[i]);
}
}
$('#btnCreateClinic').text('Save'); //change button text
$('#btnCreateClinic').attr('disabled',false); //set button enable
},
error: function (jqXHR, textStatus, errorThrown)
{
alert('Error adding data' + jqXHR+ textStatus +errorThrown);
$('#btnCreateClinic').text('Save');
$('#btnCreateClinic').attr('disabled',false);
}
});
}
also tried this:
if(data.status) {
table_clinics = $("#dataTables-clinics").dataTable( { bRetrieve : true } );
table_clinics.fnDraw();
// Hide all tables
$('dataTables-clinics').hide();
// Show the refreshed
$('dataTables-clinics').show();
alert('Added Sucessfuly');
}
also i tried this one:
and i add https://cdn.datatables.net/plug-ins/1.10.15/api/fnReloadAjax.js.
if(data.status) {
table_clinics.fnReloadAjax('<?php echo site_url('"clinic_admin/myclinics"')?>');
table_clinics.fnReloadAjax();
alert('Added Sucessfuly');
}
Reload You datatable , Try this
$('#dynamic-table').DataTable().ajax.reload(); // id of table
You must call draw() on the datatable object.
var oTable = $('#yourDataTable').dataTable();
oTable.fnDraw();
See the example i have done. Click on Add New Data button in jsfiddle

How to make table updating content without refresh the whole page

i've made a project using php ajax i use it for input data and displaying data into a table. the code work fine but when displaying data the table content didnt update the latest input in there i need to refresh page to update them.
anyone know how to make it update without refresh the whole page?
this my ajax function for input and displaying
INPUT
$(document).on('click','#ok',function(e) {
if ($('#netto').val() == '') {
alert('Kolom Netto Tolong Di Isi');
} else {
var data = $("#form_input").serialize();
$.ajax({
data: data,
type: "post",
url: "../php/bkk/bkk_i.php",
success: function(data){
alert("Data: " + data);
}
});
}
clearInput();
});
$("#form_input").submit( function() {
return false;
});
function clearInput() {
$("#form_input :input").each( function() {
$('#nopol').val('');
$('#netto').val('');
});
}
Display
$(document).ready(function(){
$.ajax({
type: "Post",
url: "../php/bkk/bkk_isel.php",
success: function(data){
var list = JSON.parse(data);
for(var i = 0; i < list.length; i++){
$('#mat').val((list[i]['material']));
$('#lok').val((list[i]['lokasi']));
$('#kpl').val((list[i]['kapal']));
$('#po_numb').val((list[i]['po']));
$('#dok').val((list[i]['doc_mat']));
var tr = "<tr>";
tr += "<td>"+list[i]['no']+"</td>";
tr += "<td>"+list[i]['tanggal']+"</td>";
tr += "<td>"+list[i]['no_pol']+"</td>";
tr += "<td>"+list[i]['netto']+"</td>";
tr += "</tr>";
$("#table_s tbody").append(tr);
}
return false;
}
});
});

Hiding the first table when the second table is loaded

I am trying to drill down to detail rows when a user clicks on a cell in table R.So when a cell is clicked Table L is loaded and Table R has to be hidden . I tried to use $('#RegionTable').hide but it hides the table when it is loaded .but i want it to be hidden only on second click
`<script type="text/javascript">
$(document).ready(function($) {
$('#lsearch').click(function(){
makeAjaxRequest();
});
$('form').submit(function(e){
e.preventDefault();
makeAjaxRequest();
return false;
});
function makeAjaxRequest() {
$.ajax({
url: 'php/l_search.php?op=1',
data: {name: $('#l').val()},
type: 'get',
success: function(response) {
$('table#R tbody').html(response);
}
});
}
});
$(document).on('click','#loc_code',function() {
var url = $(this).text();
url = 'php/l_search.php?op=2&l_code='+url ;
$.ajax({
url: url,
type: 'get',
success: function(response) {
$('table#L tbody').html(response);
}
});
return false;
$('#R').toggle("slide", { direction: "right" }, 1000);
});
</script> `
Instead of:
.on('click')
do:
$('#loc_code').dblclick(function(){
https://api.jquery.com/dblclick/
actually I used $("#R").hide(); and it works

Updating rows that are added dynamically using ajax

I hope I can explain my issue clearly.
I am running a function to get values from a database using ajax, and adding each result as a row in a table. This is so the user can delete or edit any row they want. I'm adding IDs dynamically to the columns and also the edit and delete buttons which are generated. So it looks like this:
My code:
function getstationdata(){
var taildata1 = $('#tailnumber2').val();
var uid = $('#uid').val();
$.ajax({
// give your form the method POST
type: "POST",
// give your action attribute the value ajaxadd.php
url: "ajaxgetstationdata.php",
data: {tailnumber:taildata1, uid:uid},
dataType: 'json',
cache: false,
})
.success(function(response) {
// remove all errors
$('input').removeClass('error').next('.errormessage').html('');
// if there are no errors and there is a result
if(!response.errors && response.result) {
var trHTML = '';
$.each(response.result, function( index, value) {
trHTML += '<tr><td><input type="text" value="' + value[2] + '"></td><td><input type="text" class="weightinputclass"value="' + value[3] + '"></td><td><input type="text" class="arminputclass"value="' + value[4] + '"></td><td><input type="text" class="momentinputclass" value="' + value[5] + '"></td><td><button id="updatecgbtn" onclick="updatecg()"class="editbuttonclass">Edit</button></td><td><button id="deletecgbtn" class="deletebuttonclass"">Delete</button></td></tr>';
});
$('#mbtbody').html('');
$('#mbtbody').html(trHTML);
var ID = 0;
$('.weightinputclass').each(function() {
ID++;
$(this).attr('id', 'weightinputboxID'+ID);
});
var ID = 0;
$('.arminputclass').each(function() {
ID++;
$(this).attr('id', 'arminputboxID'+ID);
});
var ID = 0;
$('.momentinputclass').each(function() {
ID++;
$(this).attr('id', 'momentinputboxID'+ID);
});
var ID = 0;
$('.editbuttonclass').each(function() {
ID++;
$(this).attr('id', 'editbutton'+ID);
});
var ID = 0;
$('.deletebuttonclass').each(function() {
ID++;
$(this).attr('id', 'deletebutton'+ID);
});
} else {
// append the error to the form
$.each(response.errors, function( index, value) {
// add error classes
$('input[name*='+index+']').addClass('error').after('<div class="errormessage">'+value+'</div>')
});
}
});
}
The code I have when adding the info is in a form and it looks like this:
$('#addstations').on('submit', function(e){
e.preventDefault();
$.ajax({
type: $(this).attr('method'),
url: $(this).attr('action'),
data: $(this).serialize(),
dataType: 'json',
cache: false,
})
.success(function(response) {
$('input').removeClass('error').next('.errormessage').html('');
if(!response.errors && response.result) {
$.each(response.result, function( index, value) {
chartdata4=(tailnumber3.value)
});
} else {
// append the error to the form
$.each(response.errors, function( index, value) {
// add error classes
$('input[name*='+index+']').addClass('error').after('<div class="errormessage">'+value+'</div>')
});
}
});
});
I searched a bit on the internet and found out that I can't add a form inside my table for each row which would have been easy to do and I can reuse my code which I use when adding new info.
So, can someone please point me in the right direction?
Here is the direction you could go
$('#formTable').on('click',"button" function(e){
var $row = $(this).closest("tr"), $form = $("#addstations");
var data = {
passenger:$row.find("passengerClass").val(),
weight :$row.find("weightClass").val()
} // no comma on the last item
data["type"]=this.className=="deletebuttonclass"?"delete":"edit";
$.ajax({
type: $form.attr('method'),
url: $form.attr('action'),
dataType: 'json',
cache: false,
})
...
I assume that the problem is that you want to add a form as a child of a table / tbody element to wrap your row. You cannot do that and the browser will most likely strip the form tags, leaving you with nothing to serialize.
There are different solutions for that, for example:
Build the data object manually in javascript when a button on a row is clicked;
Use a non-form grid solution for your layout.
Add each row in its own table and have the form wrap that table
The third solution is a bit of a hack, I would use the first or the second myself.

How to pass extra parameter in jquery post request from outside click event?

Hi i have jquery request like below ,
$('#filterForm').submit(function(e){
e.preventDefault();
var dataString = $('#filterForm').serialize();
var class2011 = document.getElementById("2011").className;
//var validate = validateFilter();
alert(dataString);
if(class2011=='yearOn')
{
dataString+='&year=2011';
document.getElementById("2011").className='yearOff';
}
else
{
document.getElementById("2011").className='yearOn';
}
alert (dataString);
$.ajax({
type: "POST",
url: "myServlet",
data: dataString,
success: function(data) {
/*var a = data;
alert(data);*/
}
});
and my Form is like ,
<form method="post" name="filterForm" id="filterForm">
<!-- some input elements -->
</form>
Well, I am triggering jquery submit on submit event of a form ,(it's working fine)
I want pass one extra parameter inside form which is not in above form content but it's outside in page
it's like below
[Check this image link for code preview][1]
So how can i trigger above event , on click of , element with class yearOn ( check above html snippet ) and class yearOff , with additional parameter of year set to either 2011 or 2010
$(document).ready(function () {
$('#filterForm').submit(function (e) {
e.preventDefault();
var dataString = $('#filterForm').serialize();
if ($("#2011").hasClass('yearOn')) {
dataString += '&year=2011';
$("#2011").removeClass('yearOn').addClass('yearOff');
}
else {
$("#2011").removeClass('yearOff').addClass('yearOn');
}
$.ajax({
url: "/myServlet",
type: "POST",
data: dataString,
success: function (data) {
/*var a = data;
alert(data);*/
}
});
});
});
1.) If you are using jQuery already, you can use the $.post() function provided by jquery. It will make your life easier in most cases.
2.) I have always had a successful post with extra parameters this way:
Build you extra parameters here
commands={
year:'2011'
};
Combine it with your form serialize
var dataString=$.param(commands)+'&'+$("#filterForm").serialize();
Perform your post here
$.post("myServlet",data,
function(data) {
/*var a = data;
alert(data);*/
}
);
OR use $.ajax if you really love it
$.ajax({
type: "POST",
url: "myServlet",
data: dataString,
success: function(data) {
/*var a = data;
alert(data);*/
}
In the end, here is the full code the way you are doing it now
$('#filterForm').submit(function(e){
e.preventDefault();
var class2011 = document.getElementById("2011").className;
//var validate = validateFilter();
alert(dataString);
if(class2011=='yearOn') {
dataString+='&year=2011';
document.getElementById("2011").className='yearOff';
} else {
document.getElementById("2011").className='yearOn';
}
commands={
year:'2011'
};
var dataString=$.param(commands)+'&'+$("#filterForm").serialize();
alert (dataString);
$.ajax({
type: "POST",
url: "myServlet",
data: dataString,
success: function(data) {
/*var a = data;
alert(data);*/
}
});

Categories