Unable to remove a table row after ajax success - javascript

In my html-php table:
<tr id="idrow">
<td><?php echo $user_id; ?></td>
<td ><?php echo $user_name; ?></td>
<td>
<input type="button" class="btn btn-danger btn-xs delete " value="Cancella sin id" onclick="deleteFunction(<?php echo $user_id; ?>)"/>
</td>
</tr>
there is a button to erase sql row by a ajax call, using the id field.
My problem is on update table after success:
my js code is:
function deleteFunction(valor) {
var $tr = $('#datatable-id').closest('tr');
var id = valor;
var parametros = {
"id" : id
};
console.log(parametros);
$.ajax({
type: "POST",
url: "deleteTabla.php",
data: parametros,
success: function(result){
//$("#idrow").remove();
$tr.remove();
},
error: function () {
console.log('ajax error');
}
});
}
Using $("#idrow").remove(), the first row is removed, not the button related one.
I suppose the trick is on var $tr = $('#datatable-id').closest('tr');, the reference to tr label?
Any help is appreciated.

If I understand correctly, every row has the same id (idrow). This is your first mistake. Ids have to be unique throughout the whole page. Create the rows with a unique Id and pass it to the function:
<tr id="idrow_<?php echo $user_id; ?>">
...
<td>
<input type="button" onclick="deleteFunction('<?php echo $user_id; ?>')"/>
</td>
</tr>
In your function, just do this:
function deleteFunction(valor) {
...
$('#idrow_'+valor).remove();
...
}

The closest tr to the #datatable-id will always be the first row.
If you want to delete a particular row try assigning an id.
<tr id="<?php echo $user_id;?>">
....
</tr>
Then in the function:
function deleteFunction(valor) {
var $tr = $('#' + valor);
// delete after request is success
$tr.remove()
}

Try this
<tr id="idrow_<?= $user_id ?>">
And on success:
$("#idrow_" + valor).remove();

Change your selector at the beginning of the function to this: var $try = $("#idrow")

Related

Ajax request data could not show into the input field

I have created a loop which contains a dropdown list and input field.
What I need is:
When I select a value from dropdown list of Fruit Genres, the Unit Price field will display value come from database. I did all of these, but could not display value to the Unit Price field.
Here is my code:
View page:
<div class="table-responsive">
<table class="table table-hover" id="item-tbl">
<thead>
<tr>
<th class="text-center">Fruit Type</th>
<th class="text-center">Fruit Genres</th>
<th class="text-center">Qty</th>
<th class="text-center">Unit Price</th>
<th class="text-center">Sub Total</th>
</tr>
</thead>
<tbody>
<?php for($i=1; $i<=3; $i++){ ?>
<tr style="">
<td><?php echo $this->Form->input('fruit_type_id', ['options'=>$fruit_types, 'empty'=>'Select Fruit Type', 'label'=>false, 'name'=>'detail_orders['.$i.'][fruit_type_id]']); ?></td>
<td><?php echo $this->Form->input('fruit_genre_id', ['options'=>$fruit_genres, 'empty'=>'Select Fruit Genre', 'label'=>false, 'name'=>'detail_orders['.$i.'][fruit_genre_id]', 'class'=>'fruit_genre']); ?></td>
<td><?php echo $this->Form->input('quantity', ['type'=>'text', 'label'=>false, 'name'=>'detail_orders['.$i.'][quantity]', 'class'=>'quantity', 'id'=>'quantity_'.$i]); ?></td>
<td><?php echo $this->Form->input('price', ['type'=>'text', 'label'=>false, 'name'=>'detail_orders['.$i.'][price]', 'class'=>'price', 'id'=>'price_'.$i]); ?></td>
<td><?php echo $this->Form->input('sub_total', ['type'=>'text', 'label'=>false, 'name'=>'detail_orders['.$i.'][price]', 'class'=>'sub_total']); ?></td>
</tr>
<?php } ?>
</tbody>
</table>
Javascript:
<script type="text/javascript">
$(document).ready(function() {
$(".fruit_genre").on('change' , function() {
var fruitGenreId = +$(this).val();
var priceId = $(this).closest('tr').find('.price').attr('id');
// alert(priceId);
$.ajax({
type: "GET",
url: baseURL+"orders/getFruitById/"+fruitGenreId+".json",
beforeSend: false,
success : function(returnData) {
if(returnData.response.code == '200'){
console.log(returnData.response.data.unit_price);
// $(this).closest('tr').find('.price').val(returnData.response.data.unit_price);
$(priceId).val(returnData.response.data.unit_price);
};
}
})
}).trigger('change');
});
OrdersController.php
public function getFruitById($id){
$this->viewBuilder()->layout('ajax');
$this->loadModel('FruitGenres');
$item = $this->FruitGenres->get($id);
if (!empty($item)) {
$response['code'] = 200;
$response['message'] = 'DATA_FOUND';
$response['data'] = $item;
}else{
$response['code'] = 404;
$response['message'] = 'DATA_NOT_FOUND';
$response['data'] = array();
}
$this->set('response', $response);
$this->set('_serialize', ['response']);
}
I have got the expected data to the javascript console. but could not pass the data to the input field.
I have tried:
$(this).closest('tr').find('.price').val(returnData.response.data.unit_price);
instead of
$(priceId).val(returnData.response.data.unit_price);
into the ajax success function, but it did not worked.
if I add a static id like the following:
$('#price_1').val(returnData.response.data.unit_price);
then it works.
Can anyone please help me? I am stuck on it.
I am using cakephp 3 for my project.
priceId is a value like price_1 without #. To make it a selector by id - prepend it with #:
$("#" + priceId).val(returnData.response.data.unit_price);
You can even simplify your code:
// you get id of the found element so as to find this element again
// you can store founded element instead of it's id
var priceDiv = $(this).closest('tr').find('.price');
// in success callback:
priceDiv.val(returnData.response.data.unit_price);
You can select the element directly instead of getting its ID and select with another jQuery call.
Another thing to note - this in the submit callback refer to the callback function itself, not the element.
$(document).ready(function() {
$(".fruit_genre").on('change' , function() {
var fruitGenreId = +$(this).val();
var $price = $(this).closest('tr').find('input.price'); // Get the element
$.ajax({
type: "GET",
url: baseURL+"orders/getFruitById/"+fruitGenreId+".json",
beforeSend: false,
success : function(returnData) {
if(returnData.response.code == '200'){
console.log(returnData.response.data.unit_price);
// Use $price directly as a jQuery object
$price.val(returnData.response.data.unit_price);
};
}
})
}).trigger('change');
});

how to change the text of a button in a Jquery on click event handler inside an ajax success function

I usually figure things out for myself but this one is giving me a really difficult time. I need to change the text value of a button in a table that is created by php from a database, after it gets clicked on.
<td id="order_num"><?php echo $order -> order_num; ?></td>
<td><?php echo $order -> data; ?></td>
<td><?php echo $order -> data; ?></td>
<td><?php echo $order -> data; ?></td>
<td><?php echo $order -> data; ?></td>
<td><?php echo $order -> data; ?></td>
<td><?php echo $order -> data; ?></td>
<td><?php echo $order -> data; ?></td>
<!-- **** this is the button. ******** -->
<td><button type="submit" class="accept_order" id ="row_<?php echo $order -> order_num; ?>"
data-row_id = "row_<?php echo $order -> order_num; ?>" data-current_user = "<?php echo $user_id; ?>"
data-order_num = "<?php echo $order -> order_num; ?>">Accept</button>
here is the big mess of an ajax call
$(document).ready(function () {
$('.shop').on('click', 'button', function(e){
var button = $(this).find('button'); //trying to put the value of the current button in a variable to pass to the ajax function.
var current_user = $(this).closest('.shop').find('.accept_order').data('current_user');
console.log(current_user);
var row_id = $(this).closest('.shop').find('.accept_order').data('row_id');
var accepted_order = $(this).closest('.shop').find('.accept_order').data('order_num');
console.log(accepted_order);
e.preventDefault();
$.ajax('url', {
type: "POST",
data: { order_id: accepted_order, user_id: current_user },
success: function(msg){
console.log(msg);
console.log(this);
//change the text of the button to something like "accepted"
***************this is where I have problems ***********************
$(this).html('accepted'); or
$(this).closest('.shop').find('button').html(msg); or
button.text(msg);
},
error: function(){
$(this).closest('.shop').find('.accept_order').html("failure");
}
});
});
});
</script>
I did use $('button').html(msg);
but that changes all of the buttons. It seems like I lose scope to the object when inside the success function. Any ideas or help will be greatly appreciated. Thanks in advance.
I believe I found your problem source but I'm not sure. And The problem came from this keyword because this in the ajax function direct to the ajax object not the button node object. So you can use bind function in the success and error functions to make this directs to the button. here is the modification:
and another thing the url in ajax function is a variable not a string as you wrote above.
$.ajax(url, {
type: "POST",
data: { order_id: accepted_order, user_id: current_user },
success: function(msg){
console.log(msg);
console.log(this);
//change the text of the button to something like "accepted"
***************this is where I have problems ***********************
$(this).html('accepted'); or
$(this).closest('.shop').find('button').html(msg); or
button.text(msg);
}.bind(this),
error: function(){
$(this).closest('.shop').find('.accept_order').html("failure");
}.bind(this)
});
I'm not sure from the solution because there is no demo for what you asked about.
I hope it works.
Maybe you can use the class to select the button
$.ajax('url', {
type: "POST",
data: { order_id: accepted_order, user_id: current_user },
success: function(msg){
console.log(msg);
console.log(this);
//change the text of the button to something like "accepted"
***************this is where I have problems ***********************
$("button.accept_order").html(msg);
},
error: function(){
$(this).closest('.shop').find('.accept_order').html("failure");
}
});
or better..
var button = $(this);
and inside your ajax call just use:
button.html(msg);

I am not getting response from ajax request

I am getting no response from ajax request . i am posting a ajax call to processor.php file and the processor.php file is processing the file and sending the processed file back to javascript i am gerring my result in my console log but it is not showing in the html.
My javascript code is :
function add_to_cart(item_name,item_price){
$('.user-info').slideUp('1200');
$('.cart-status').slideDown('1200');
var dataString = "item_name=" + item_name + "&item_price=" + item_price + "&page=add_to_cart";
$.ajax({
type: "POST",
url: "php/processor/processor.php",
data:dataString,
beforeSend:function(){
$(".cart-show-product").html('<h3>Your Cart Status</h3><img src="images/loading.gif" align="absmiddle" alt="Loading...." class="center" /><br><p class="center">Please Wait...</p>');
},
success: function(response){
console.log(response);
$(".cart-show-products").html(response);
}
});
}
and my php is :
if(isset($_POST['item_name']) && !empty($_POST['item_name']) && isset($_POST['item_price']) && !empty($_POST['item_price']))
{
$sql = mysqli_query($conn,
'SELECT * FROM
products_added
where
username = "'.mysqli_real_escape_string($conn, $_SERVER['REMOTE_ADDR']).'"
and
item_added="'.mysqli_real_escape_string($conn, $_POST['item_name']).'"'
);
if(mysqli_num_rows($sql) < 1)
{
mysqli_query($conn,
"INSERT INTO products_added values(
'',
'".mysqli_real_escape_string($conn, $_SERVER['REMOTE_ADDR'])."',
'".mysqli_real_escape_string($conn, $_POST['item_name'])."',
'".mysqli_real_escape_string($conn, $_POST['item_price'])."',
'".mysqli_real_escape_string($conn, '1')."',
'".mysqli_real_escape_string($conn, $_POST['item_price'])."'
'".mysqli_real_escape_string($conn, date("d-m-Y"))."')"
);
?>
<table class="cart-show-products">
<thead>
<tr>
<td>Sl.No</td>
<td>Item</td>
<td>Qty</td>
<td>Price</td>
<td>Action</td>
</tr>
</thead>
<tbody>
<?php
$sl_no = 1;
$sql = mysqli_query(
$conn,
'SELECT sum(amount) as grandtotal
FROM products_added
WHERE username = "'.mysqli_real_escape_string($conn, $_SERVER['REMOTE_ADDR']).'"
ORDER BY id'
);
$row = mysqli_fetch_array($sql);
$grandtotal = strip_tags($row['grandtotal']);
$sql = mysqli_query(
$conn,
'SELECT
id,
item_added,
price,
quantity
FROM products_added
WHERE username = "'.mysqli_real_escape_string($conn, $_SERVER['REMOTE_ADDR']).'"
ORDER BY id'
);
$row = mysqli_fetch_array($sql);
$item_id = strip_tags($row['item_id']);
$item_name = strip_tags($row['item_added']);
$item_price = strip_tags($row['price']);
$quantity = strip_tags($row['price']);
?>
<tr class="items_wrap items_wrap<?php echo $item_id; ?>">
<td><?php echo $sl_no++; ?></td>
<td><?php echo $item_name ?></td>
<td><?php echo $quantity ?></td>
<td><?php echo $item_price ?></td>
<td><i class="fa fa-times"></i></td>
</tr>
</tbody>
</table>
<?php
}
If you're getting a response in the console, then the issue must be with your HTML. I think part of the problem is you've created a section on the HTML page wiht a class that is the same as the table the AJAX call is bringing into the page. I would suggest changing the HTML element to us an ID instead. Something like
<div id="products-table"></div>
And then change your JavaScript to
function add_to_cart(item_name,item_price){
$('.user-info').slideUp('1200');
$('.cart-status').slideDown('1200');
var dataString = "item_name=" + item_name + "&item_price=" + item_price + "&page=add_to_cart";
$.ajax({
type: "POST",
url: "php/processor/processor.php",
data:dataString,
beforeSend:function(){
$("#products-table").html('<h3>Your Cart Status</h3><img src="images/loading.gif" align="absmiddle" alt="Loading...." class="center" /><br><p class="center">Please Wait...</p>');
},
success: function(response){
console.log(response);
$("#products-table").html(response);
}
});
}
If you stay with the class names you've used, subsequent updates are going to have problems because you'll have 2 elements on the page with the same class. Your script could potentially be confused about which one to change.
If this is your actual code, then you have a syntax error in your PHP file. There are a missing close bracket for:
if(isset($_POST['item_name']) && !empty($_POST['item_name']) && isset($_POST['item_price']) && !empty($_POST['item_price']))
The second problem is, you are not print anything, if this condition has failed.
Note
You do not need to use isset, if you are checking empty. empty will return false, if the variable not set.
You can debug your respons by check NET tab in your web developer tools, or see, what is the response of the AJAX.

Get the ID of an elements who have dynamic ID values

I am a newbie in Jquery. I have a table in my webpage which shows the contents of a user table from the database.I have also created an edit button and Delete button for each row of data.I need the id of each edit and delete button for writing code for editing and deleting the records in the database as well as implementing this changes in the table in the webpage also.
$query = mysqli_query($con,"SELECT * FROM user_details");
while($row = mysqli_fetch_array($query))
{
echo "<tr>";
echo "<td>".$row['fname']."</td>";
echo "<td>".$row['mname']."</td>";
echo "<td>".$row['childname']."</td>";
echo "<td><input type='button' id = 'edit".$row['Id']."' value='Edit'></td>";
echo "<td><input type='button' id = 'delete".$row['Id']."' value='Delete'></td>";
echo "</tr>";
}
If I am using Jquery,how to get the IDof each button?Or If I write a onclick event using javascript for each button and passes the ID's as arguments,can I access via Jquery.Please help me
$("button").each(function(index, item) {
var itemId = $(item).attr('id');
});
But I would set the $row['id'] into a data-id attribute and then use:
$("button").each(function(index, item) {
var itemId = $(item).data('id');
});
Add common class name and use that as a selector to get id of the buttons like below
Try like this
$(document).on('click','.edit_btn',function(){
alert($(this).attr('id'));
});
$(document).on('click','.del_btn',function(){
alert($(this).attr('id'));
});
HTML
<input type='button' id ='edit' class="edit_btn" value='Edit'>
<input type='button' id ='delete' class="del_btn" value='Delete'>
DEMO
First of all, you need to escape your variables in HTML context using htmlspecialchars(). Second, you can use data attributes to easily identify the record that needs be edited or deleted.
?>
<tr>
<td><?= htmlspecialchars($row['fname'], ENT_QUOTES, 'UTF-8') ?></td>
<td><?= htmlspecialchars($row['mname'], ENT_QUOTES, 'UTF-8') ?></td>
<td><?= htmlspecialchars($row['childname'], ENT_QUOTES, 'UTF-8') ?></td>
<td><input type="button" class="edit" data-id="<?= $row['Id'] ?>" value="Edit"></td>
<td><input type="button" class="delete" data-id="<?= $row['Id'] ?>" value="Delete"></td>
</tr>
<?php
Then, you can use classes to identify the buttons instead:
$('.edit').on('click', function() {
var id = $(this).data('id');
// edit stuff
});
$('.delete').on('click', function() {
var id = $(this).data('id');
// delete stuff
});
You can use a data-* attribute to specify the ID and use a common class to call the click handler
echo "<td><input type='button' id = 'edit".$row['Id']."' data-id='".$row['Id']."' value='Edit' class='edit-record'></td>";
then in jQuery
jQuery(function ($) {
$(document).on('click', '.edit-record', function () {
//this is called when the edit button is clicked
var $this = $(this),
id = $this.data('id');
//now id has the value of current record's id
})
})
Use Attribute starts with selector, and Event Delegation
$(document).on("click" , "[id^='edit']" ,function() {
console.log(this.id);
});
$(document).on("click" , "[id^='delete']" , function() {
console.log(this.id);
});

Refreshing Datatable data without reloading the whole page

I am using codeigniter to load data on datatables, on the data table each row has a link that when clicked data is sent elsewhere. The data in that particular row should disappear and only links that have not been clicked remain. I have managed to do that with AJAXbut on success i am forced to reload the page on jQuery timeout
sample:
//Table headers here
<tbody class="tablebody">
<?php foreach ($worksheets as $sheets) : ?>
<tr>
<td><?php echo $sheets->filename ?></td>
<td class="bold assign">
<?php echo $sheets->nqcl_number ?>
<?php echo anchor('assign/assing_reviewer/' . $sheets->nqcl_number, 'Assign') ?>
<a id="inline" href="#data">Assign1</a>
<input type="hidden" id="labref_no" value="<?php echo $sheets->nqcl_number; ?>" />
</td>
<td><?php echo $sheets->uploaded_by ?></td>
<td><?php echo $sheets->datetime_uploaded ?></td>
<td></td>
</tr>
<?php endforeach; ?>
</tbody>
I would like that on AJAX success, the row of the datatables where the link was is dynamically removed from the table without page refresh.
$.ajax({
type: "POST",
url: "<?php echo base_url(); ?>assign/sendSamplesFolder/" + labref,
data: data1,
success: function(data) {
var content = $('.tablebody');
$('div.success').slideDown('slow').animate({opacity: 1.0}, 2000).slideUp('slow');
$.fancybox.close();
//Reload the table data dynamically in the mean time i'm refreshing the page
setTimeout(function() {
window.location.href='<?php echo base_url();?>Uploaded_Worksheets';
}, 3000);
return true;
},
error: function(data) {
$('div.error').slideDown('slow').animate({opacity: 1.0}, 5000).slideUp('slow');
$.fancybox.close();
return false;
}
});
I have tried this but it loads two same pages. what's the work around?
content.load(url);
You can use fnDraw() to force the datatable to re-query the datasource. Try this:
// store a reference to the datatable
var $dataTable = $("#myTable").dataTable({ /* Your settings */ });
// in the AJAX success:
success: function(data) {
$dataTable.fnDraw();
},
Have a read of the fnDraw entry in the documentation.
var $dataTable = $("#myTable").dataTable({ /* Your settings */ });
var oSettings = $dataTable.fnSettings();
var page = Math.ceil(oSettings._iDisplayStart / oSettings._iDisplayLength);
$dataTable.fnPageChange(page);

Categories