Refreshing Datatable data without reloading the whole page - javascript

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);

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');
});

Unable to remove a table row after ajax success

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")

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);

want to update dropdown in each row in the database using Ajax

Here is my UI Screenshot. Highlighted is the Dropdown
What i want?
As i Select any option in the Dropdown it should get updated for that particular row in Database using AJAX
Below are the Codes that i've written. I'm just a Beginner, please excuse if the code is not neat!!
I'm using Codeigniter
Front End
<?php if( is_array( $fbrecords ) && count( $fbrecords ) > 0 )
foreach($fbrecords as $r) { ?>
<tr>
<td><?php echo $r->fullname; ?></td>
<td><?php echo $r->email; ?></td>
<td><?php echo $r->mobile; ?></td>
<td><?php echo $r->message; ?></td>
<td><?php echo $r->jtime; ?></td>
<td> <?php $data=array(
'name'=>'status',
'row' => '12px',
'id' => 'status',
'selected'=>'none',
'class'=>'statusClass'
);
$data_status = array(
'none' => 'none',
'A&A' => 'Attended & Acted',
'YTA' => 'Yet to Attend',
);
echo form_dropdown($data, $data_status, set_value('status')); ?> </td>
Ajax Code - I've added a Console.log to see weather next row dropdown is being selected or not
$(document).ready( function() {
$(".statusClass").change(function(event) {
//var dropDown = document.getElementById("status");
//var status = dropDown.options[dropDown.selectedIndex].value;
var status = $("select.statusClass").val();
console.log(status);
jQuery.ajax({
type: "POST",
url: "<?php echo base_url(); ?>" + "index.php/user_authentication/user_data_status_submit",
dataType: 'json',
data: {status:status},
success: function(data){
if (result)
{
alert("success");
}
}
});
});
});
Controller
public function user_data_status_submit(){
$data = array(
'status' => $this->input->post('status'),
);
//Either you can print value or you can send value to database
echo json_encode($data);
$this->login_database->feedback_update($data);
}
*Console Ouputs for the first 3 rows show the 1 row selection thrice - Below is the Screeshots of that *
You are checking the values of all select box. Instead of that you get the values which you are updating to obtain the result this keyword will use.
$(document).ready( function() {
$(".statusClass").change(function(event) {
var status = $(this).val();

Passing a AJAX Variable to PHP

Hi wondering how to send a AJAX variable to php, I thought I had it but apparently not. In my console I get the error "Uncaught TypeError: Illegal invocation line 6"
Im taking it there is something wrong with my code straight after the alert?
(NOTE where it say "jquery" is in replace of $ simply because joomla does not like $ in scripts for some reason)
UPDATED, Pay attention to
Script to click and get rowID
<script language="javascript" type="text/javascript">
jQuery(document).ready(function()
{
jQuery("tr.getRow").click(function()
{
rowID = jQuery(this).find("td.idCell");
alert(jQuery(rowID).text());
//Send the row ID to ajaxupdate.php
jQuery.post("ajaxupdate.php", { submit: "update", ID_ID: rowID})
.done( function(data) {
var results = jQuery.parseJSON(data);
console.log( results );
})
.fail( function() {
console.log("AJAX POST failed.");
});
});
});
</script>
Load first table(the one thats being clicked)
<table border="",th,td, width="500", align="center">
<tr>
<th>TP ID</th> <th>Permit Deny</th> <th>Level</th> <th>Session</th> <th>Information Specialist</th>
</tr>
<?php foreach ($results as $row): ?>
<tr class="getRow">
<td class="idCell"><?php echo $row->TP_ID ?></td>
<td><?php echo $row->Permit_or_Deny ?></td>
<td><?php echo $row->Level ?></td>
<td><?php echo $row->Session ?></td>
<td><?php echo $row->Information_specialist ?></td>
</tr>
<?php endforeach ?>
<br>
</table>
Second table, the one that im trying to get to load
<?php
// In ajaxupdate.php file
if( (isset($_POST['ID_ID'])) || (isset($_POST['submit']))) //im Sure this part is wrong
{
$ID_ID =($_POST['ID_ID']); // pass JS var as a PHP var
$db = JFactory::getDbo();
$query = $db->getQuery(true);
$query
->select($db->quoteName(array('CV_ID', 'Classifier', 'Value', 'TP_ID')))
->from($db->quoteName('sessionta'))
->where($db->quoteName('TP_ID') . ' LIKE '. $db->quote('".$ID_ID."'));
$db->setQuery($query);
$results = $db->loadObjectList();
}
?>
3425742,
I rewrote your script and tested it with this JSfiddle. Try it out.
I see that you are using Joomla. Diving into Joomla as a novice is daunting. Within ajaxupdate.php the script is expecting to see a $_POST['submit'] variable. Either remove that requirement or add it like I did below. At the bottom of ajaxupdate.php add this line so that jQuery has something to test.
echo $results ? json_encode("succeeded") : json_encode("failed"); die();
Here is the jQuery ajax code:
//Send the row ID to ajaxupdate.php
$.post("ajaxupdate.php", { submit: "update", TP_ID: rowID})
.done( function(data) {
var results = $.parseJSON(data);
console.log( results );
})
.fail( function() {
console.log("AJAX POST failed.");
});
Edit "ajaxupdate.php" to the correct location of that file. If ajaxupdate.php is in a different directory you have to tell jQuery to look there. For example, if your $.post is in index.php in the root of your webserver and ajaxupdate is in the /js directory change "ajaxupdate.php" to "js/ajaxupdate.php".
you are passing rowID as an object, not as a single text-variable. You'd need
$.post("ajaxupdate.php", ({ TP_ID: rowID.attr('id') }), function( data )
...

Categories