Clicking the submit button submit the form data multiple times - javascript

I have asynchronously loaded form. When I submit the form by clicking the submit button, it submits multiple times. I have gone through some of the SO answers but still the problem is there.
Form:
<form action="" method="POST" id="aproveForm" class="smart-form" novalidate="novalidate">
<fieldset>
<section class="col col-5" >
<select class="form-control" name="groupid" onchange="loadInvoice(this.value);">
<option value="1">Sales</option>
<option value="2">Merchandiser</option>
</select>
</section>
</fieldset>
</form>
JS
function loadInvoice(id){
nid= 'id='+id;
$.ajax({
type:'POST',
url:'loadform.php',
data:nid,
dataType:'html',
success:function(data) {
$('#payform').html(data);
}
});
}
in the <div id="payform">, I have loaded the form from loadform.php which is like below:
<form method="POST" id="mulpayment">
<table class="table table-bordered" style="width:80%;">
<tr>
<th><div align="center">Name of Customer</div></th>
<th><div align="center">New Payment</div></th>
<th><div align="center">Total Debit</div></th>
</tr>
<?php
alldebt=0;
foreach($linvoice as $row): ?>
<input type="hidden" id="gcustomer" name="gcustomer[]" value="<?php echo $row['customerid']; ?>">
<?php
echo "<tr>";
echo "<td><div align=left>".$row['name'].".</div></td>";
echo '<td><input type="text" id="gpay" name="gpay[]" min="0" required style="width:100%;"></td>';
echo '<td align="right"><i class="fa fa-inr"></i> '.$row['totaldebit'].'</td>';
echo "</tr>";
$alldebt += $row['totaldebit'];
endforeach;
?>
<tr>
<th colspan="3"><div align="right">Total</div></th>
<th><div align="right"><i class="fa fa-inr"></i> <?php echo number_format($alldebt,2); ?></div></th>
</tr>
<tr>
<td colspan="6">
<div align="right">
<input type="submit" id="savePayment" value="Save Payment" class="btn btn-success">
</div>
</td>
</tr>
</table>
</form>
When I submit the form, it submits multiple times,i.e., paymentupdate.php runs multiple times. I want to run paymentupdate.php one time only. How do I solve this problem? Please help.
$(document).on("submit", "#mulpayment", function(e){
e.preventDefault();
var gcustomer = $("input[id='gcustomer']").map(function(){return $(this).val();}).get();
var gpay = $("input[id='gpay']").map(function(){return $(this).val();}).get();
var gbalance = $("input[id='gbalance']").map(function(){return $(this).val();}).get();
var gid = $('#gid').val();
var paymentMade = 'gcustomer='+gcustomer+'&gpay='+gpay+'&gbalance='+gbalance+'&gid='+gid;
$.ajax({
type:'POST',
dataType:"json",
data:paymentMade,
url: 'paymentupdate.php',
success:function(data) {
if(data.success){
$('#mulpayment')[0].reset();
$('#payform').html(data.record);
}else{
alert(data.msg);
}
}
});
return false;
});

Try adding disable to your button after submitting your form. like for example
$(document).on("click", "#mulpayment", function(e){
e.preventDefault();
$(':input[type="submit"]').prop('disabled', true);
var gcustomer = $("input[id='gcustomer']").map(function(){return $(this).val();}).get();
var gpay = $("input[id='gpay']").map(function(){return $(this).val();}).get();
var gbalance = $("input[id='gbalance']").map(function(){return $(this).val();}).get();
var gid = $('#gid').val();
var paymentMade = 'gcustomer='+gcustomer+'&gpay='+gpay+'&gbalance='+gbalance+'&gid='+gid;
$.ajax({
type:'POST',
dataType:"json",
data:paymentMade,
url: 'paymentupdate.php',
success:function(data) {
if(data.success){
$('#mulpayment')[0].reset();
$('#payform').html(data.record);
$(':input[type="submit"]').prop('disabled', false);
}else{
alert(data.msg);
}
}
});
});
in this way, it can prevent from clicking multiple times. you can enable back the button once the ajax request succeeds.

Try change button type="submit" for type="button":
$(document).on("click", "#mulpayment", function(e){
var gcustomer = $("input[id='gcustomer']").map(function(){return $(this).val();}).get();
var gpay = $("input[id='gpay']").map(function(){return $(this).val();}).get();
var gbalance = $("input[id='gbalance']").map(function(){return $(this).val();}).get();
var gid = $('#gid').val();
var paymentMade = 'gcustomer='+gcustomer+'&gpay='+gpay+'&gbalance='+gbalance+'&gid='+gid;
$.ajax({
type:'POST',
dataType:"json",
data:paymentMade,
url: 'paymentupdate.php',
success:function(data) {
if(data.success){
$('#mulpayment')[0].reset();
$('#payform').html(data.record);
}else{
alert(data.msg);
}
}
});
});
And remove action and method attributes from the form tags, you dont need it if you use ajax:
<form id="aproveForm" class="smart-form" novalidate="novalidate">
<form id="mulpayment">

Related

Update Database Record with Ajax in Codeigniter

I am trying to update database records using ajax from the ajax response, getting success message but the actual database records are not updated at all. But it wonder how the ajax response should throw the success message while the query is not updating the database.
VIEW:
// AJAX code to update the database
// update marks when form is submitted
$('#updateMarks').on('submit',function(event) {
event.preventDefault();
var practical_mark = $("#mark_written").val();
var written_mark = $("#mark_practical").val();
var comment = $("#comment").val();
var mark_id = $("#mark_id").val();
$.ajax({
type: "POST",
url: "<?php echo site_url('admin/exam_marks_update'); ?>",
data: { practical_mark : practical_mark,
written_mark: written_mark,
comment : comment,
mark_id : mark_id
},
success: function(response)
{
alert("success");
},
error: function(){
alert("Error");
},
});
});
<?php foreach($marks as $row2): ?>
<form method="post" role="form" id="updateMarks">
<tr>
<td class="text-center"><?php echo $student['name']; ?></td>
<td>
<!-- create two col table for marks category -->
<table class="table table-bordered table-hover toggle-circle">
<thead>
<tr>
<th data-toggle="true" class="text-center"><?php echo get_phrase('written_exam'); ?></th>
<th data-toggle="true" class="text-center"><?php echo get_phrase('practical_exam'); echo get_phrase('_(out_of_100)'); ?></th>
</tr>
</thead>
<tbody>
<tr>
<td class="text-center"><input type="number" value="<?php echo $row2['written_mark_obtained'];?>" id="mark_written" name="mark_written" class="form-control" /></td>
<td class="text-center"><input type="number" value="<?php echo $row2['practical_mark_obtained'];?>" id="mark_practical" name="mark_practical" class="form-control"/></td>
</tr>
</tbody>
</table>
<!-- end create two col table for marks category -->
</td>
<td class="text-center"><textarea class="form_control" id="comment" name="comment" rows="4" > <?php echo $row2['comment'] ?> </textarea></td>
<td class="text-center">
<input type="hidden" id="mark_id" name="mark_id" value="<?php echo $row2['mark_id'];?>" />
<button type="submit" class="btn btn-block btn-success btn-md"><i class="icon pe-pen" aria-hidden="true"></i><?php echo get_phrase('update'); ?></button>
</td>
</tr>
</form>
<?php endforeach; ?>
Controller:
function exam_marks_update(){
$data['written_mark_obtained'] = $this->input->post('written_mark');
$data['practical_mark_obtained'] = $this->input->post('practical_mark');
$data['comment'] = $this->input->post('comment');
$this->crud_model->update_student_marks($data, $this->input->post('mark_id'));
}
MODEL
function update_student_marks($data, $mark_id){
$this->db->where('mark_id', $mark_id);
$this->db->update('mark', $data);
}
Jquery ajax success callback function is always called if the request to server succeeds. You need to return response data from server to verify when database operation was successful or not. I have edited your code , this might work for you.
MODEL
function update_student_marks($data, $mark_id){
.....
return $this->db->update('mark', $data);
}
Controller::
function exam_marks_update(){
.....
if($this->crud_model->update_student_marks($data, $this->input->post('mark_id'))){
echo json_encode(array('success' => true));
exit;
} else {
echo json_encode(array('success' => false));
exit;
}
}
View
$.ajax({
type: "POST",
url: "<?php echo site_url('admin/exam_marks_update'); ?>",
dataType :'json',
data: { practical_mark : practical_mark,
written_mark: written_mark,
comment : comment,
mark_id : mark_id
},
success: function(response)
{
if (response.success === true){
alert("success");
} else {
alert('failed');
}
},
error: function(){
alert("Error");
},
});
Your Controller retrieving inputs which doesn't exists... you need to pass your name, id as inputs and not the value which you echo... see as Controller:
function exam_marks_update(){
$data = array(
'written_mark_obtained' => $this->input->post('written_mark'),
'practical_mark_obtained' => $this->input->post('practical_mark'),
'comment' => $this->input->post('comment')
);
$this->db->where('mark_id', $this->input->post('mark_id'));
$this->db->update('mark', $data);
}
and change this:
var comment = $("#comment").val();
to
var comment = $("#comment").html();
As comment is textarea...

Ajax response not updating in php while loop

I am having a slight problem figuring out why this ajax response isn't updating properly. I have a php while loop which lists gallerys in text format, i am using . It is getting details from the php page but only for one result so essentially when you hover over the name a qtip tooltip box pops up so you can edit the name of the gallery. The problem is it only lists one result for all results in the loop.
PHP & HTML
<?php
$MemberGalleriesQuery = $bapcity->query("SELECT * FROM CroMemberRetailGalleries WHERE UserID='".$_SESSION['user_id']."' ORDER BY GalleryID DESC");
$MemberGalleriesCount = $MemberGalleriesQuery->num_rows;
if ( $MemberGalleriesCount )
{
$BaseHeight = 150;
$GalleriesBoxHeight = $BaseHeight + ( 20 * $MemberGalleriesCount );
echo '
<div id="ManageGalleries" style="height: '.$GalleriesBoxHeight.'px" align="center">
<div id="ManageGalleriesHeader">Manage Galleries</font></div><br><br>
<font color="#000000"><b>Click Gallery To Edit</b></font><br><br>
';
while($GalleryData = $MemberGalleriesQuery->fetch_assoc())
{
echo '>> <b><a class="EditGallery" href="Crowork.Backend/Crowork.EditGallery.php?action=EditGallery&gallerykey='.$GalleryData['GalleryID'].'">'.$GalleryData['GalleryName'].'</a></b> <<<br>';
}
echo '<br><br></div>';
}
$MemberGalleriesQuery->free();
?>
JAVASCRIPT:
//Edit Form When Hovering Over Gallery Name
$('.EditGallery').each(function() {
var link = $('.EditGallery').attr('href'); //Gets link url
$.ajax({ //Make the ajax request
url: link,
cache: false
}).done(function( html ) { //On complete run tooltip code
//Display tooltip code goes here, returned text is variable html
$('.EditGallery').qtip({
content: {
text: html
},
hide: {
fixed: true,
delay: 300
},
style: 'wiki'
});
$('.EditGallery').qtip('click', true);
$(".EditGallery").page();
});
});
CONTENTS OF Crowork.Backend/Crowork.EditGallery.php
if ( isset( $cleanGet['action'] ) && $cleanGet['action'] == 'EditGallery' ){
$MemberGalleriesQuery = $bapcity->query("SELECT * FROM CroMemberRetailGalleries WHERE GalleryID='".$cleanGet['gallerykey']."' AND UserID='".$SessionUserID."' ORDER BY GalleryID DESC");
$MemberGalleriesCount = $MemberGalleriesQuery->num_rows;
if ( $MemberGalleriesCount )
{
$GalleryData = $MemberGalleriesQuery->fetch_assoc();
}?>
<form action="Crowork.Backend/Crowork.EditGallery.php?action=DoEditGallery&gallerykey=<?php echo $GalleryData['GalleryID']?>" method="post">
<input type="hidden" name="GalleryName" value="<?php echo $GalleryData['GalleryName']?>">
<input type="hidden" name="GalleryID" value="<?php echo $GalleryData['GalleryID']?>">
<input type="submit" name="DeleteGallery" value="Delete Gallery">
</form>
<form action="Crowork.Backend/Crowork.EditGallery.php?action=DoEditGallery&gallerykey=<?php echo $GalleryData['GalleryID']?>" method="post">
<table border="0" width="100%">
<tr>
<td colspan="2" align="center"><font size="-1"><b>NOTE:</b> Letters & Numbers Only</font></td>
</tr>
<tr>
<td>Name:</td>
<td><input type="text" name="GalleryName" size="30" value="<?php echo $GalleryData['GalleryName']?>"></td>
</tr>
<tr>
<td align="right" colspan="2">
<input type="hidden" name="OriginalGalleryName" value="<?php echo $GalleryData['GalleryName']?>">
<input type="hidden" name="GalleryID" value="<?php echo $GalleryData['GalleryID'] ?>">
<input type="submit" name="EditGallery" value="Edit Gallery">
</td>
</tr>
</table>
</form>
<?php }?>
PREVIEW:
http://www.bigjohn863.com/mini-upload-form/uploads/ajaxproblem.png
See how all three are the same results.
Try:
$('.EditGallery').each(function()
{
$(this).qtip({
content: {
text: "Loading...",
ajax: {
url:$(this).attr('href'),
type: "GET",
success: function(data, status) {
this.set('content.text', data);
}
}
},
hide: {
fixed: true,
delay: 300
},
style: 'wiki'
});
$(this).qtip('click', true);
});
http://jsfiddle.net/st0j8nLy/
//Edit Form When Hovering Over Gallery Name
$('.EditGallery').each(function() {
var link = $('.EditGallery').attr('href'); //Gets link url
....
everytime you are calling $('.EditGallery'). $('.EditGallery'). is an array, you need to change all references to $('.EditGallery') that is within the loop to $(this):
var link = $(this).attr('href'); //Gets link url
You Might be need to create dynamic id so you can call proper ajax.
please modify your ajax call as below
$gid=$GalleryData['GalleryID'];
echo '>> <b><a onclick="editgalary($gid)" id="EditGallery_$gid" href="Crowork.Backend/Crowork.EditGallery.php?action=EditGallery&gallerykey='.$GalleryData['GalleryID'].'">'.$GalleryData['GalleryName'].'</a></b> <<<br>';
replace this code in while loop.
function editgalary(galaryid){
var link = $('#EditGallery_'+galaryid).attr('href');
//ajax code as it is.
}
try and let me konw

Why will my Ajax call fire twice?

I am trying to delete a record from a data-table by creating a delete button for each record. My issue with the code that the first time I click on the delete button it refreshes the page and deletes the record, the second time I click the button Ajax fires up twice and I don't get the bootstrap modal, can't delete the record. Any suggestion how to fix the Ajax firing up twice.
index.php
<body>
<div id="test1234">
<table id="example" class="table table-striped table-bordered" cellspacing="0" width="100%">
<thead>
<tr>
<th>fname</th>
<th>lname</th>
<th>email</th>
<th>username</th>
<th>Delete</th>
</tr>
</thead>
<tbody>
<?php
// connect to mongodb
$m = new MongoClient();
$db = $m->local;
$collection = $db->user;
$results = $collection->find();
foreach($results as $res){
$fname = $res['fname'];
$lname = $res['lname'];
$email = $res['email'];
$username = $res['username'];
?>
<tr>
<td><?php echo $fname; ?></td>
<td><?php echo $lname; ?></td>
<td><?php echo $email; ?></td>
<td><?php echo $username; ?></td>
<td><i class="fa fa-trash-o"></i></td>
</tr>
<?php
}
?>
</tbody>
</table>
</div>
</body>
</html>
<script>
$(document).ready(function(){
$('#example').DataTable();
$(document).on('click','.idname', function(){
var data = $(this).serialize();
var aa = $(this).attr('id');
alert('open modal: '+aa);
$.ajax({
type: 'POST',
url: 'modal.php',
async:false,
data: ({name:aa}),
cache: false,
success: function(data){
$('#results').html(data);
}
})
return false;
});
});
</script>
<div id="results"></div>
modal.php
<?php
$email = $_POST['name'];
?>
<div id="myModal" class="modal fade" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title"><?php echo $email; ?></h4>
</div>
<div class="modal-body">
<p>Some text in the modal.</p>
</div>
<div class="modal-footer">
<form action="deleteUser.php" id="formsubmit1" method="POST">
<input type='hidden' id="email" name="email" value=<?php echo $email ?> >
<input type="submit" id="submit" value="Submit" >
</form>
<button type="button" class="btn btn-default" data-dismiss="modal">No</button>
</div>
</div>
</div>
</div>
<script>
$(document).ready(function() {
$('#myModal').modal('show');
});
</script>
<script>
$(document).ready(function(){
$('#formsubmit1').on('submit',function(){
alert('opened');
//e.preventDefault();
var data = $(this).serialize();
$.ajax({
type: 'POST',
url: 'deleteUser.php',
data: data,
cache: false,
success: function(data){
$('#results3333').html(data);
//alert('res2');
}
})
return false;
});
$('#formsubmit1').on('submit', function(){
//alert('close');
$('#myModal').hide();
$('.modal-backdrop').hide();
});
//refresh page
$('#formsubmit1').on('submit', function(){
alert('refresh');
//e.preventDefault();
var data = $(this).serialize();
$.ajax({
type: 'POST',
url: 'index.php',
data: data,
cache: false,
success: function(data){
$('#test1234').html(data);
alert('ref2');
}
})
return false;
});
});
</script>
userDelete.php
<?php
$email = $_POST['email'];
$m = new MongoClient();
$db = $m->local;
$collection = $db->user;
$results = $collection->remove(array('email' => $email));
?>
As #Michelem has mentioned there are multiple functions attached as submit-handlers to your form with id formsubmit1 inside modal.php.
$('#formsubmit1').on('submit',function(){
alert('opened');
//e.preventDefault();
var data = $(this).serialize();
//////////////////HERE////////////////////////
$.ajax({
type: 'POST',
url: 'deleteUser.php',
data: data,
cache: false,
success: function(data){
$('#results3333').html(data);
//alert('res2');
}
})
return false;
});
$('#formsubmit1').on('submit', function(){
//alert('close');
$('#myModal').hide();
$('.modal-backdrop').hide();
});
//refresh page
$('#formsubmit1').on('submit', function(){
alert('refresh');
//e.preventDefault();
var data = $(this).serialize();
//////////////////HERE////////////////////////
$.ajax({
type: 'POST',
url: 'index.php',
data: data,
cache: false,
success: function(data){
$('#test1234').html(data);
alert('ref2');
}
})
return false;
});

Stop form from refreshing the page on submit

Alright, so I have a basic form on my page:
<form action='' id='formId' method='POST'>
<table>
<tr>
<td>
<input type='text' name='Chat' autocomplete='off'>
</td>
<td>
<input type='submit' name='Go'>
</td>
</tr>
</table>
</form>
and the javascript is:
<script type='text/javascript'>
$( "#formId" ).submit(function( event ) {
event.preventDefault();
<?php
$Chat = mysql_real_escape_string(strip_tags($_POST['Chat']));
$Go = mysql_real_escape_string($_POST['Go']);
if ($Go) {
if ($Chat) {
mysql_query("INSERT INTO `Chat` (`Chat`)
VALUES('$Chat')");
}
}
?>
});
</script>
I just need it to stop from refreshing when someone submits. I've read a few different posts on here with the same problem, but none seemed to work for me.
$('#formId').submit(function () {
/do your stuff
return false;
});
Returning false will prevent page reloading.
You need to separate the php code to your script. PHP is executed server side, js/jquery is executed client side. Try this code if it will help you.
<?php
if(isset($_POST['Go'])){
$Chat = mysql_real_escape_string(strip_tags($_POST['Chat']));
$Go = mysql_real_escape_string($_POST['Go']);
if ($Go) {
if ($Chat) {
mysql_query("INSERT INTO `Chat` (`Chat`)
VALUES('$Chat')");
}
}
}
?>
<form action='' id='formId' method='POST'>
<table>
<tr>
<td>
<input type='text' name='Chat' autocomplete='off'>
</td>
<td>
<input type='submit' name='Go'>
</td>
</tr>
</table>
</form>
<script type='text/javascript'>
$( "#formId" ).submit(function( event ) {
event.preventDefault();
});
</script>
REVISED: 06/15/2015 10:16AM GMT+8
You need use AJAX to send data. First, Add an id to the text field then create a php file for getting the data from the URL and insert the chat to DB. Try this code:
<form action='' id='formId' method='POST'>
<table>
<tr>
<td>
<input type='text' id='chat' name='Chat' autocomplete='off'>
</td>
<td>
<input type='submit' name='Go'>
</td>
</tr>
</table>
</form>
<script src="//code.jquery.com/jquery-1.11.3.min.js"></script>
<script type='text/javascript'>
$( "#formId" ).submit(function( event ) {
event.preventDefault();
$.ajax({
type: "POST",
url: "insert_chat.php?",
data: "Chat="+$('input#chat').val(),
dataType: "json",
success: function(data){
}
});
});
</script>
insert_chat.php
<?php
$Chat = mysql_real_escape_string(strip_tags($_GET['Chat']));
$Go = mysql_real_escape_string($_GET['Go']);
if ($Go) {
if ($Chat) {
mysql_query("INSERT INTO `Chat` (`Chat`)
VALUES('$Chat')");
}
}
?>

How to replaceWith an edited row to its original display in a table using jquery

Say I have a table:
<table class="table table-bordered table-hover" id="myTableJD">
<thead>
<tr>
<th>JOB DESCRIPTION</th>
<th>CONTROL</th>
</tr>
</thead>
<tbody>
<?php
foreach ($JobDescription as $rowJD1)
{
echo '<tr id="itemk_'.$rowJD1["id"].'">';
echo '<td class="customerIDCell">'.$rowJD1["JobDescription"].'</td>';
echo '<td>Edit | Delete</td>';
echo '</tr>'; //i changed this part to </tr> and close the last </td> to avoid confusion
}
?>
</tbody>
</table>
And here's my javascript using jquery jquery-1.8.2.min.js
//##### Add record when Add Record Button is clicked #########
$("#FormSubmitJD").click(function (e) {
e.preventDefault();
if($("#contentTextJD").val()==="") //simple validation
{
alert("Please enter some text!");
return false;
}
var myData = "jd="+ $("#contentTextJD").val(); //post variables
jQuery.ajax({
type: "POST", // HTTP method POST or GET
url: "<?php echo BASE_URL."programs/SaveJobDescription.php"; ?>", //Where to make Ajax calls
dataType:"text", // Data type, HTML, json etc.
data:myData, //post variables
success:function(response){
$('#IDJOBDESCRIPTION').modal('hide');
<?php
$getLastID = $emp->getLastID($_SESSION['UEmpID']) + 1;
$itemk_id = "itemk_".$getLastID;
$delk_id = "delk-".$getLastID;
$editk_id = "editk-".$getLastID;
?>
$('#myTableJD').append('<tr id="<?php echo $itemk_id; ?>"><td>'+$("#contentTextJD").val()+'</td><td>Delete</td></tr>');
$("#contentTextJD").val(''); //empty text field after successful submission
},
error:function (xhr, ajaxOptions, thrownError){
alert(thrownError); //throw any errors
}
});
});
//##### edit record when edit Button is clicked #########
$("body").on("click", ".edit_buttonk", function(e) {
e.preventDefault();
var clickedID = this.id.split("-"); //Split string (Split works as PHP explode)
var DbNumberID = clickedID[1]; //and get number from array
<?php
$getJD = $emp->getJD($_SESSION['UEmpID']);
$jdValue = $getJD;
?>
var tr = $(this).parent().parent();
alert(tr);
var new_row = '<tr id="itemk_'+DbNumberID+'"><td style="margin-bottom:-10px;padding-bottom:0px;"><input id="jd-'+DbNumberID+'" type="text" value="<?php echo $jdValue; ?>" class="span12"/> </td><td>Save</td></tr>';
alert(new_row);
tr.replaceWith(new_row);
});
//##### save record when save Button is clicked #########
$("body").on("click", ".save_buttonk", function(e) {
e.preventDefault();
var clickedID = this.id.split("-"); //Split string (Split works as PHP explode)
var DbNumberID = clickedID[1]; //and get number from array
var myData = 'id='+DbNumberID+'&jd='+$("#jd-"+DbNumberID).val(); //build a post data structure
alert(myData);
jQuery.ajax({
type: "POST", // HTTP method POST or GET
url: "<?php echo BASE_URL."programs/EditJobDescription.php"; ?>", //Where to make Ajax calls
data:myData, //post variables
success:function(response){
//on success, hide element user wants to delete.
<?php
$getJD = $emp->getJD($_SESSION['UEmpID']);
$jdValue = $getJD;
?>
var tr = $(this).parent().parent();
var new_row = '<tr id="<?php echo $itemk_id; ?>"><td><?php echo $jdValue; ?></td><td>Delete</td></tr>';
tr.replaceWith(new_row);
$('#<?php echo $itemk_id; ?>').empty();
$('#<?php echo $itemk_id; ?>').append(new_row);
$('#<?php echo $itemk_id; ?>').replaceWith(new_row);
},
error:function (xhr, ajaxOptions, thrownError){
//On error, we alert user
alert(thrownError);
}
});
});
//##### Delete record when delete Button is clicked #########
$("body").on("click", ".del_buttonk", function(e) {
e.preventDefault();
var clickedID = this.id.split("-"); //Split string (Split works as PHP explode)
var DbNumberID = clickedID[1]; //and get number from array
var myData = 'id='+ DbNumberID; //build a post data structure
alert(myData);
jQuery.ajax({
type: "POST", // HTTP method POST or GET
url: "<?php echo BASE_URL."programs/DeleteJobDescription.php"; ?>", //Where to make Ajax calls
data:myData, //post variables
success:function(response){
//on success, hide element user wants to delete.
$('#itemk_'+DbNumberID).fadeOut("slow");
},
error:function (xhr, ajaxOptions, thrownError){
//On error, we alert user
alert(thrownError);
}
});
});
Everything works except after replacing the specific row of a table by clicking the Edit link, and when i click for saving the edited field nothing happen. I want to display the original display of the table but edited.
Anybody got any ideas?
//Data added on table when click on submit.
var edit_row = null;
$("#submit").on("click", function () {
var fname = $("#fname").val();
var lname = $("#lname").val();
var number = $("#number").val();
var row = "<tr><td class='first'>" +
fname +
"</td><td class='last'>" +
lname +
"</td><td class='mobile'>" +
number +
'</td><td> <a class="fas fa-trash-alt dlt text-danger" style="cursor:pointer"></a></td></tr>';
if (edit_row) {
$("#myTable tbody").find($(edit_row)).replaceWith(row);
edit_row = null;
}
else if ((fname != "" && lname != "" && number != "")) {
$("#myTable tbody").append(row);
}
// After submit all values are null using below codes.
$("#fname").val('');
$("#lname").val('');
$("#number").val('');
});
// Data delete in table when click on delete button.
$(document).on('click', '.dlt', function () {
$(this).parents('tr').remove();
return false;
});
// Data again fill in form when click on edit.
$(document).on('click', '.edit', function () {
edit_row = $(this).closest('tr');
$("#fname").val($(this).closest('tr').find('.first').text());
$("#lname").val($(this).closest('tr').find('.last').text());
$("#number").val($(this).closest('tr').find('.mobile').text());
});
// Thank you.
<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="icon" type="image"
href="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQoqksPBDeWpznZfj0_XtgkNO5npIUwP7n7n0GCXos3PGoEGHLwapvcf_qlnbXWf-bd-Us&usqp=CAU">
<!-- Bootstrap CSS -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.1.3/dist/css/bootstrap.min.css" rel="stylesheet"
integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta2/css/all.min.css">
<style>
.form-label {
margin: 0%;
}
</style>
<title>Edit and Delete</title>
</head>
<body>
<!-- form -->
<div class="container mt-5 d-flex justify-content-center">
<form class="row" id="myForm">
<div class="col-8">
<label for="fname" class="form-label">First Name</label>
<input type="text" class="form-control" id="fname" placeholder="First Name">
</div>
<div class="col-8 mt-3">
<label for="lname" class="form-label">Last Name</label>
<input type="text" class="form-control" id="lname" placeholder="Last Name">
</div>
<div class="col-8 mt-3">
<label for="number" class="form-label">Mobile Number</label>
<input type="tel" class="form-control" maxlength="10" minlength="10" id="number"
placeholder="Mobile Number">
</div>
<div class="col-12 mt-3">
<button type="button" id="submit" class="btn btn-primary">Submit</button>
</div>
</form>
</div>
<!-- Table -->
<table class="table container mt-5" id="myTable">
<thead>
<tr>
<th scope="col">First Name</th>
<th scope="col">Last Name</th>
<th scope="col">Mobile Number</th>
<th scope="col">Action</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
<footer style="float: right;display: block;position: fixed;bottom: 20px;right: 20px;">Made by <a style="text-decoration: none;color: black;font-weight: 600;" href="https://www.instagram.com/_ridham_golakiya/">Ridham Golakiya</a></footer>
<!-- Scripts -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.1.3/dist/js/bootstrap.bundle.min.js"
integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p"
crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta2/js/all.min.js"></script>
<script src="edit&delete.js"></script>
</body>
</html>

Categories

Resources