How to remove HTML table at form submitting - javascript

I have HTML table with dynamically generated contents. A td in the table contains a form. What I want is to remove the table from the page once this form is submitted because another page will be included at form submitting. I am using ajax and php. How can I amend my code below to remove the table once the form is submitted?
JAVASCRIPT
function chk(item_id){
$.ajax({
type:"post",
url:"edit_form.php",
data: {
id: item_id,
name: $('#name-'+item_id).val()
},
cache:false,
success: function(html){
$('#msg').html(html);
}
});
$('#forms').click(function(){
$('#table').hide();
});
return false;
}
HTML
<div id="msg"></div>
<div id="table">
<table align="center">
<tbody>
<tr>
<th>S/N</th>
<th>Subject</th>
<th>Edit</th>
</tr>
<tr>
<td><?php echo $i;?></td>
<td><?php echo $subject;?></td>
<td>
<form id="myform">
<input type="text" id="name-<?php echo $item_id;?>" hidden name="name" value="<?php echo $item_id;?>" >
<button type="submit" id="forms" onclick="return chk(<?php echo $item_id;?>)">Edit</button>
</form>
</td>
</tr>
</tbody>
</table>
</div>

$('#forms').click(function(){
$('#table').hide();
});
At the moment, when the form submits, the above code means you're creating an event handler to listen for the next time the button is clicked, which would then hide the table at that time.
To hide it as soon as the form is submitted, then simply remove the event handler part and just write
$('#table').hide();
by itself within the "chk" function.
N.B. If you don't want it to hide until after the ajax call is completed successfully, then move it inside the "success" function.

According to your question title:
You can simply add these lines in your ajax success: :
$("#table table").remove();
OR
You can set innerHTML of div to empty
$("#table").html("");
I hope this should work.

why do you need a <form> tag anyway? a more simple approach which doesn't involve jQuery
HTML
<input name="" />
<button id="submit">Submit</button>
JS
submit.onclick = function(){
element = document.querySelector('holderClass');
element.style.display = 'none'; // or any element
// ...ajax here
}
you might need document.querySelector()

//In success block you can remove the table by using $('#table').html("");
function chk(item_id){
$.ajax({
type:"post",
url:"edit_form.php",
data: {
id: item_id,
name: $('#name-'+item_id).val()
},
cache:false,
success: function(html){
$('#msg').html(html);
$('#table').html("");
}
});
return false;
}

Related

JavaScript, checked checkboxes from whole table [duplicate]

I'm trying to get first cell (td) for each row and getting it but only for current page. If I navigate to next page then the checkbox checked on the previous page is not being sent.
<table class="table" id="example2">
<thead><tr>
<th>Roll no</th><th>Name</th></tr><thead>
<?php
$sel = "SELECT * FROM `st`";
$r = mysqli_query($dbc, $sel);
while ($fet = mysqli_fetch_array($r)) {
?>
<tr>
<td><?php echo $fet['trk'] ?></td>
<td><input type="text" value="<?php echo $fet['ma'] ?>" id="man" class="form-control"></td>
<td><input type="checkbox" id="check" name="myCheckbox" class="theClass"></td></tr>
<?php } ?>
</table>
<input type="submit" id="sub_marks" class="btn btn-info" value="Submit & Continue">
<script src="plugins/datatables/jquery.dataTables.min.js" type="text/javascript"></script>
<script src="plugins/datatables/dataTables.bootstrap.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(function () {
$('#example2').DataTable({
"paging": true,
"lengthChange": false,
"searching": false,
"ordering": true,
"info": true,
"autoWidth": false,
})
});
</script>
<script>
$('#sub_marks').click(function () {
var values = $("table #check:checked").map(function () {
return $(this).closest("tr").find("td:first").text();
}).get();
alert(values);
})
</script>
CAUSE
jQuery DataTables removes non-visible rows from DOM for performance reasons. When form is submitted, only data for visible checkboxes is sent to the server.
SOLUTION 1. Submit form
You need to turn elements <input type="checkbox"> that are checked and don't exist in DOM into <input type="hidden"> upon form submission.
var table = $('#example').DataTable({
// ... skipped ...
});
$('form').on('submit', function(e){
var $form = $(this);
// Iterate over all checkboxes in the table
table.$('input[type="checkbox"]').each(function(){
// If checkbox doesn't exist in DOM
if(!$.contains(document, this)){
// If checkbox is checked
if(this.checked){
// Create a hidden element
$form.append(
$('<input>')
.attr('type', 'hidden')
.attr('name', this.name)
.val(this.value)
);
}
}
});
});
SOLUTION 2: Send data via Ajax
var table = $('#example').DataTable({
// ... skipped ...
});
$('#btn-submit').on('click', function(e){
e.preventDefault();
var data = table.$('input[type="checkbox"]').serializeArray();
// Include extra data if necessary
// data.push({'name': 'extra_param', 'value': 'extra_value'});
$.ajax({
url: '/path/to/your/script.php',
data: data
}).done(function(response){
console.log('Response', response);
});
});
DEMO
See jQuery DataTables: How to submit all pages form data for more details and demonstration.
NOTES
Each checkbox should have a value attribute assigned with unique value.
Avoid using id attribute check for multiple elements, this attribute is supposed to be unique.
You don't need to explicitly enable paging, info, etc. options for jQuery DataTables, these are enabled by default.
Consider using htmlspecialchars() function to properly encode HTML entities. For example, <?php echo htmlspecialchars($fet['trk']); ?>.
You do not have to make hidden element on form just before submit simply destroy data table before submit and it will submit all checkbox on all pages like normal
$('form').on('submit', function (e) {
$('.datatable').DataTable().destroy();
});
<form action="Nomination" name="form">
<table width="100%" class="table table-striped table-bordered table-hover" id="dataTables- example">
<tbody>
<%while (rs1.next()){%>
<tr>
<td><input type="checkbox" name="aabb" value="<%=rs1.getString(1)%>" /></td>
</tr>
<%}%>
</tbody>
</table>
</form>
and add script with correct form id and table id
<script>
var table = $('#dataTables-example').DataTable({
// ... skipped ...
});
</script>
<script>
$('form').on('submit', function(e){
var $form = $(this);
table.$('input[type="checkbox"]').each(function(){
if(!$.contains(document, this)){
if(this.checked){
$form.append(
$('<input>')
.attr('type', 'hidden')
.attr('name', this.name)
.val(this.value)
);} } }); });
</script>
This is working code
Great code from Gyrocode.com, but if you have some other hidden values in your rows, you will have to create them too in the form.
I use :
var table = $('#example').DataTable({
// ... skipped ...
});
$("#buttonValidation").click(function(){
table.page.len(-1).draw();
});
It just displays on screen all the datatable without pagination before sending it in the form. Maybe if you want to hide the display, you can use css opacity :0 (but not display:none).

Retrieve a specific row value from table HTML and submit it to PHP

I'm populating a table from my database and it looks like this :
<form name = "Form" role="form" action ="php/teilnehmen.php" method="POST">
<fieldset>
<table width="100%" class="table table-striped table-bordered table-hover" id="dataTables-example">
<thead>
<tr>
<th>ID</th>
<th>Studienfach</th>
<th>Teilnehmer/in</th>
<th>Teilnehmen</th>
</tr>
</thead>
<tbody>
//<?php php code.....
$i =0;
$sizeofstudienfaecherseperate =
count($studienfaecherseperate);
for ($i; $i < $sizeofstudienfaecherseperate; $i++) {
?>
<tr class="odd gradeX">
<td ><?php echo($i+1);?></td>
<td class="studienfach"><?php echo($studienfaecherseperate[$i]);?>
<input type="hidden" name="PARAM_STUDIENFACH" id="PARAM_STUDIENFACH"
value="<?php echo($studienfaecherseperate[$i]);?>"> </input>
</td>
<td ><?php echo($teilnehmer[$i]);?></td>
<td width="10%">
<?php if ($teilnahmestatus[$i] =="0"){ ?>
<button type="submit" class="btn btn-success use-address"
name="teilnehmern"id="teilnehmen">Teilnehmen</button>
<?php }else{?>
<button type="submit" class="btn btn-danger use-address" name="teilnahme-beenden"
id="teilnahme-beenden">Teilnahme beenden</button>
<?php }?>
</td>
</tr>
<?php } ?>
</tbody>
</table>
</fieldset> <!-- /.table-responsive -->
the table is shown great, and my problem is when i try to submit my second column value "PARAM_STUDIENFACH" of a specific row to my php webservice. It always gives me back the last value. I know that because I'm using the same id in every row so it will be overwritten. I tried using JavaScript to return the value of the clicked row from other questions in the forum but it didn't work for me. I'm using a bootstrap table if that helps.
EDIT 1 :
Thanks to #Taplar answer I managed to find a solution to my problem. I used this JavaScript to retrieve the data and ajax to send a post request. This is the code I used :
$(".use-address").click(function() {
var item = $(this).closest("tr") // Finds the closest row <tr>
.find(".studienfach") // Gets a descendent with class="nr"
.text(); // Retrieves the text within <td>
$.ajax({
type: "POST",
dataType: "json",
url: "php/teilnehmen.php",
data: {PARAM_STUDIENFACH:item},
success: function(data){
alert(item);
},
error: function(e){
console.log(e.message);
}
});
});
my problem now is in the alert the "item" shows correctly but in my database it is saved as the following example :
item = a (shows in alert a)
item = a \n (it's saved like that in the database with spaces afeter \n)
i tried to trim the item before sending it but i got the same result
to get the item sent by ajax i'm using this line of code in :
$studienfach = null;
if(isset($_POST['PARAM_STUDIENFACH']))
$studienfach = $mysqli->real_escape_string($_POST['PARAM_STUDIENFACH']);
EDIT 2:
i managed to solve my second problem by doing this :
$pos= strpos($studienfach, "\\");
$studienfachtemp = substr($studienfach, 0,$pos);
trim($studienfachtemp);
if there is more elegent or correct way to do it ! please post it ! thank you all.
<elem1>
<elem2 class="getMe"></elem2>
<elem3></elem3>
</elem1>
Quick contextual lookup reference. Say you have a click event bound on all 'elem3' on your page. When you click it you want to get the associated 'elem2', not all of them. With the class you can contextually look this element up by doing...
//'this' being the elem3 that was clicked
$(this).closest('elem1').find('.getMe');
From the element you clicked, it will find the shared 'elem1' parent of both 'elem2' and 'elem3' and then find only the '.getMe' that belongs to that parent.
More reading material: http://learn.jquery.com/using-jquery-core/working-with-selections/

How to submit checkboxes from all pages with jQuery DataTables

I'm trying to get first cell (td) for each row and getting it but only for current page. If I navigate to next page then the checkbox checked on the previous page is not being sent.
<table class="table" id="example2">
<thead><tr>
<th>Roll no</th><th>Name</th></tr><thead>
<?php
$sel = "SELECT * FROM `st`";
$r = mysqli_query($dbc, $sel);
while ($fet = mysqli_fetch_array($r)) {
?>
<tr>
<td><?php echo $fet['trk'] ?></td>
<td><input type="text" value="<?php echo $fet['ma'] ?>" id="man" class="form-control"></td>
<td><input type="checkbox" id="check" name="myCheckbox" class="theClass"></td></tr>
<?php } ?>
</table>
<input type="submit" id="sub_marks" class="btn btn-info" value="Submit & Continue">
<script src="plugins/datatables/jquery.dataTables.min.js" type="text/javascript"></script>
<script src="plugins/datatables/dataTables.bootstrap.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(function () {
$('#example2').DataTable({
"paging": true,
"lengthChange": false,
"searching": false,
"ordering": true,
"info": true,
"autoWidth": false,
})
});
</script>
<script>
$('#sub_marks').click(function () {
var values = $("table #check:checked").map(function () {
return $(this).closest("tr").find("td:first").text();
}).get();
alert(values);
})
</script>
CAUSE
jQuery DataTables removes non-visible rows from DOM for performance reasons. When form is submitted, only data for visible checkboxes is sent to the server.
SOLUTION 1. Submit form
You need to turn elements <input type="checkbox"> that are checked and don't exist in DOM into <input type="hidden"> upon form submission.
var table = $('#example').DataTable({
// ... skipped ...
});
$('form').on('submit', function(e){
var $form = $(this);
// Iterate over all checkboxes in the table
table.$('input[type="checkbox"]').each(function(){
// If checkbox doesn't exist in DOM
if(!$.contains(document, this)){
// If checkbox is checked
if(this.checked){
// Create a hidden element
$form.append(
$('<input>')
.attr('type', 'hidden')
.attr('name', this.name)
.val(this.value)
);
}
}
});
});
SOLUTION 2: Send data via Ajax
var table = $('#example').DataTable({
// ... skipped ...
});
$('#btn-submit').on('click', function(e){
e.preventDefault();
var data = table.$('input[type="checkbox"]').serializeArray();
// Include extra data if necessary
// data.push({'name': 'extra_param', 'value': 'extra_value'});
$.ajax({
url: '/path/to/your/script.php',
data: data
}).done(function(response){
console.log('Response', response);
});
});
DEMO
See jQuery DataTables: How to submit all pages form data for more details and demonstration.
NOTES
Each checkbox should have a value attribute assigned with unique value.
Avoid using id attribute check for multiple elements, this attribute is supposed to be unique.
You don't need to explicitly enable paging, info, etc. options for jQuery DataTables, these are enabled by default.
Consider using htmlspecialchars() function to properly encode HTML entities. For example, <?php echo htmlspecialchars($fet['trk']); ?>.
You do not have to make hidden element on form just before submit simply destroy data table before submit and it will submit all checkbox on all pages like normal
$('form').on('submit', function (e) {
$('.datatable').DataTable().destroy();
});
<form action="Nomination" name="form">
<table width="100%" class="table table-striped table-bordered table-hover" id="dataTables- example">
<tbody>
<%while (rs1.next()){%>
<tr>
<td><input type="checkbox" name="aabb" value="<%=rs1.getString(1)%>" /></td>
</tr>
<%}%>
</tbody>
</table>
</form>
and add script with correct form id and table id
<script>
var table = $('#dataTables-example').DataTable({
// ... skipped ...
});
</script>
<script>
$('form').on('submit', function(e){
var $form = $(this);
table.$('input[type="checkbox"]').each(function(){
if(!$.contains(document, this)){
if(this.checked){
$form.append(
$('<input>')
.attr('type', 'hidden')
.attr('name', this.name)
.val(this.value)
);} } }); });
</script>
This is working code
Great code from Gyrocode.com, but if you have some other hidden values in your rows, you will have to create them too in the form.
I use :
var table = $('#example').DataTable({
// ... skipped ...
});
$("#buttonValidation").click(function(){
table.page.len(-1).draw();
});
It just displays on screen all the datatable without pagination before sending it in the form. Maybe if you want to hide the display, you can use css opacity :0 (but not display:none).

How identify a secondary Id of a html element with multiple IDs

In my project, one of the jsp pages have this html structure:
<table id="hor-minimalist-a" class="campos">
<thead>
<tr>
<th>Campo</th>
<th>#</th>
</tr>
</thead>
<tfoot>
<tr>
<td> <input type="text" name="nome_campo"> </td>
<td> <button type="button" id="incluir_campo" class="btn btn-link">Incluir</button> </td>
</tr>
<tr>
<td> <div id="result_incluir_campo"></div> </td>
<td> <div id="result_excluir_campo"></div> </td>
</tr>
</tfoot>
<c:forEach var="item_key" items="${campos}">
<tr id="linha_campo_${item_key}">
<td> <input type="text" value="${item_key}"> </td>
<td> <button type="button" id="excluir_campo_${item_key}" class="btn btn-link">Excluir</button> </td>
</tr>
</c:forEach>
</table>
Note the line:
<button type="button" id="excluir_campo_${item_key}" class="btn btn-link">Excluir</button>
I have one jquery function associated to it:
<c:forEach var="item_key" items="${campos}">
<script>
$("#excluir_campo_${item_key}").on("click", function () {
$.ajax({
type: "GET",
url: "<c:out value="${pageContext.request.contextPath}/key/remove_campo"/>",
cache: false,
data: {nome: "${item_key}"}
}).done(function(data){
if(data == "yes") {
$("#linha_campo_${item_key}").remove();
}
else if(data == "not"){
$("#result_excluir_campo").empty().append("erro");
}
else {
$("#result_excluir_campo").empty().append("sem acesso");
}
});
});
</script>
</c:forEach>
I was using jstl, but i am facing some problems with this solution, since my list can be updated dynamicly.
Take in consideration I change the Id from this element:
<button type="button" id="excluir_campo_${item_key}" class="btn btn-link">Excluir</button>
to this two (separating the two "terms" of current Id):
excluir_campo ${item_key}
is there any way to detect the secong id with a jquery function similar to that:
$("#excluir_campo").on("click", function () {
var second_id = ???;
$.ajax({
type: "GET",
url: "<c:out value="${pageContext.request.contextPath}/key/remove_campo"/>",
cache: false,
data: {nome: "<second_id>"}
}).done(function(data){
if(data == "yes") {
$("#linha_campo_<second_id>").remove();
}
else if(data == "not"){
$("#result_excluir_campo").empty().append("erro");
}
else {
$("#result_excluir_campo").empty().append("sem acesso");
}
});
});
Or there is another way to accomplish the same result of the code above?
First of all, never generate scripts in rendered html using any kind of loops. What if you have 1000 items? 1000 times your code, very inefficient. You can use write a generic function and render that caller. This way, you save thousands of lines!
Secondly, NEVER use generated id's and id based functions, never ever! you can just use a generic class for that functionality, you do not need id selector. You just need an extra attribute like "key":
<div class="my-functionality" data-key="15" />
<div class="my-functionality" data-key="16" />
<div class="my-functionality" data-key="17" />
<div class="my-functionality" data-key="18" />
And you can just use either generated scripts in loops or jquery's each selector to bind events to your elements: you can wrap your click event like:
$('.my-functionality').each(function(index, elem){
$(elem).click(function(){
//do you stuff here!
var key = $(elem).data('key'); //this will read data-key attribute
});
});

Html form is not working with Php, Ajax request

Hello following is my html form which I want to validate with Ajax. So that Browser do not load the page. If user enter First Name, It's should show the first name above the html form. But It doesn't showing...
Html form:
<form id="validation"/>
<table width="500" border="0" cellspacing="10" cellpadding="0">
<tr>
<td>First Name</td>
<td><input type="text" name="fname" value="<?php if(isset($_POST['fname'])) echo $_POST['fname']; ?>" class="tr" placeholder="First Name"/></td>
</tr>
<tr>
<td></td>
<td><input type="reset" name="reset" value="Clear" class="submit"/> <input type="submit" name="Submit" id="submit" value="Registration" class="submit"/></td>
</tr>
</table>
</form>
<script>
$('#validation').submit(function(event) {
event.preventDefault();
$.ajax({
type: 'POST',
url: 'regProcess.php',
data: $(this).serialize(),
dataType: 'json',
success: function (data) {
}
});
});
</script>
Php code:
<?php
if(isset($_POST['Submit']) && $_POST['Submit'] == "Registration"){
$fname = $_POST['fname'];
echo $fname;
}
?>
Near the bottom of your code, you have this:
success: function (data) {
}
That's your problem. You're not doing anything with the returned "data" - you need to use javascript or jquery to insert it into the DOM somewhere.
EDIT: UPDATE
To use jquery to insert the data into the dom, do something like this:
success: function (data) {
$("#id of the element where you want the data").innerHTML+=data
}
That will append the "data" retrieved from the AJAX into the element with the specific ID. You can use any CSS selector inside the $("HERE") I believe.

Categories

Resources