Refresh jQuery datatable table - ajax

Been plenty of questions about this but I never found one that worked for me. I have a plain and simple HTML table whos body is being filled with rows from an AJAX call.
Then I want to update the table with DataTable plugin but it does not work.
I have a HTML table that looks like this:
<table id="myTable">
<thead>
<tr>
<th>1</th>
<th>2</th>
<th>3</th>
<th>4</th>
<th>5</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
In my jQuery pageload
$(document).ready(function(){
var oTable = $('#myTable').dataTable({
"aoColumns": [
{ "bSortable": false },
null, null, null, null
]
});
});
And finally my on dropdownlist change function
$("#dropdownlist").on("change", function () {
$("tbody").empty();
$.ajax({
type: "POST",
url: "#Url.Action("ActionHere", "Controller")",
dataType: "json",
success: function (data) {
$.each(data, function (key, item) {
$("tbody").append("<tr><td>1</td><td>2</td><td>3</td><td>4</td><td>5</td></tr>");
});
}
})
var oTable = $('#myTable').dataTable(); // Nothing happens
var oTable = $('#myTable').dataTable({ // Cannot initialize it again error
"aoColumns": [
{ "bSortable": false },
null, null, null, null
]
});
});
The append and so on has been modified to shorten it down, etc so do not focus too much on it.
Basically the question is how to update the table, I can do my AJAX and add new data to the table fine, but the datatable plugin does not update with it.
I've tried other things like
.fnDraw(false);
But it does nothing
While I get an JSON error from
fnReloadAjax()
Any clues on just how to refresh the table?

Try this
Initially you initialized the table so first clear that table
$('#myTable').dataTable().fnDestroy();
Then initialize again after ajax success
$('#myTable').dataTable();
Like this
$("#dropdownlist").on("change", function () {
$("tbody").empty();
$.ajax({
type: "POST",
url: "#Url.Action("ActionHere", "Controller")",
dataType: "json",
success: function (data) {
$.each(data, function (key, item) {
$("tbody").append("<tr><td>1</td><td>2</td><td>3</td><td>4</td><td>5</td></tr>");
});
}
})
$('#myTable').dataTable().fnDestroy();
$('#myTable').dataTable({ // Cannot initialize it again error
"aoColumns": [
{ "bSortable": false },
null, null, null, null
]
});
});
DEMO

I Know this is an old post, but I've just investigated about the problem and I find the easiest way to solve it in DataTable man pages: https://datatables.net/reference/api/ajax.reload%28%29
All you need to call table.ajax.reload();

var table = $('#product_table').DataTable({
"bProcessing": true,
"serverSide": true,
responsive: true,
"ajax": {
url: get_base_url + "product_table", // json datasource
type: "post", // type of method ,GET/POST/DELETE
error: function () {
$("#employee_grid_processing").css("display", "none");
}
}
});
//call this funtion
$(document).on('click', '#view_product', function () {
table.ajax.reload();
});

I had done something that relates to this... Below is a sample javascript with what you need. There is a demo on this here: http://codersfolder.com/2016/07/crud-with-php-mysqli-bootstrap-datatables-jquery-plugin/
//global the manage member table
var manageMemberTable;
function updateMember(id = null) {
if(id) {
// click on update button
$("#updatebutton").unbind('click').bind('click', function() {
$.ajax({
url: 'webdesign_action/update.php',
type: 'post',
data: {member_id : id},
dataType: 'json',
success:function(response) {
if(response.success == true) {
$(".removeMessages").html('<div class="alert alert-success alert-dismissible" role="alert">'+
'<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button>'+
'<strong> <span class="glyphicon glyphicon-ok-sign"></span> </strong>'+response.messages+
'</div>');
// refresh the table
manageMemberTable.ajax.reload();
// close the modal
$("#updateModal").modal('hide');
} else {
$(".removeMessages").html('<div class="alert alert-warning alert-dismissible" role="alert">'+
'<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button>'+
'<strong> <span class="glyphicon glyphicon-exclamation-sign"></span> </strong>'+response.messages+
'</div>');
// refresh the table
manageMemberTable.ajax.reload();
// close the modal
$("#updateModal").modal('hide');
}
}
});
}); // click remove btn
} else {
alert('Error: Refresh the page again');
}
}

From version 1.10.0 onwards you can use ajax.reload() api.
var table = $('#myTable').DataTable();
table.ajax.reload();
Keep in mind to use $('#myTable').DataTable() and not
$('#myTable').dataTable()

Related

How can I delete using ajax in laravel?

BLADE FILE
<td><button class="deleteuser" data-id="{{ $user->id }}" data-token="{{ csrf_token() }}" >DELETE</button>
</td>
AJAX
$(document).ready( function () {
$(".deleteuser").click(function(){
var id = $(this).data("id");
var token = $(this).data("token");
$.ajax(
{
url: "user/delete/"+id,
type: 'DELETE',
dataType: "JSON",
data: {
"id": id,
"_method": 'DELETE',
"_token": token,
},
success: function ()
{
console.log("it Work");
}
});
console.log("It failed");
});
});
CONTROLLER
public function destroyuser($id){
$this->authorize('Admin');
User::find($id)->delete($id);
return response()->json([
'success' => 'Record has been deleted successfully!'
]);
return view('viewuser');
}
If I click on delete button, there is no response. Any suggestion or correction will be appreciated. Thanks in advance
I don't know if the JS is in a different file but to check if the "$( document ).ready()" is working add a console.log() call at the beginning.
$(document).ready( function () {console.log("document is ready")
$(".deleteuser").click(function(){
Refresh the page and check if "document is ready" is logged to the console.
If it isn't then the javascript is not loading
Check if the route is properly defined
You can replace your url as this and check:
var id = data.id;
var url = "{{route('your_route',":id") }}";
url = url.replace(':id', id);
pass url in your ajax url param
Or make above changes:
BLADE FILE
<td>
<button style="background-color: red;" onclick="clickOffConfirmed" title="Delete" class="btn btn-sm btn-clean btn-icon btn-icon-md delete"><i class="la la-trash" style="color: white;"></i></button>
</td>
SCRIPT
<script>
$(document).ready(function() {
$(document).on('click', '.delete', function ()
{
var obj = $(this);
var id=$(this).closest('td').find(".delete_id").val();
var result = confirm("Are you sure want to delete?");
if(result)
{
$.ajax(
{
type: "POST",
url: "{{route('delete_method')}}",
data: {
'_token': $('input[name="_token"]').val(),
'id': id
},
cache: false,
success: function (data)
{
if (data.status === 'success')
{
window.location = "{{route('redirect_route')}}";
toastr["success"]("Deleted Successfully", "Success");
}
else if (data.status === 'error')
{
location.reload();
toastr["error"]("Something went wrong", "Opps");
}
}
});
}
});
});
</script>
Controller
public function delete_method(Request $request)
{
$del = ModelName::findOrFail($request->id)->delete();
if($del)
{
return response()->json(['status' => 'success']);
}
else{
return response()->json(['status' => 'error']);
}
}
Route
Route::post('/test/delete','TestController#delete_method')->name('delete_method');
In your ajax codes, change this:
url: "user/delete/"+id,
To:
url: "{{ url('user/delete') }}/" + id
If your ajax codes are inside of your blade file also you can use this way:
url: "{{ route('YOUR_ROUTE_NAME', $user->id) }}/"
You incorrectly define delete function!
change
User::find($id)->delete($id);
To
User::find($id)->delete();

How to SUM cells from DataTables when checked?

I want to SUM values from cells when I check then. Like:
I´ve found how on DataTables website but it is not quite like I need.
Will be a lot of data on this table, and I want to SUM their values when the checkbox is checked, the save the total on a variable to pass to a controller.
P.S.: I forgot to say that I am using VueJS. Let´s see some code.
#section('scripts')
<script type="text/javascript"
src="https://cdn.datatables.net/v/dt/jszip-2.5.0/dt-1.10.16/af-2.2.2/b-1.5.1/b-colvis-1.5.1/b-flash-1.5.1/b-html5-1.5.1/b-print-1.5.1/cr-1.4.1/fh-3.1.3/kt-2.3.2/rg-1.0.2/rr-1.2.3/sl-1.2.5/datatables.min.js">
</script>
<script type="text/javascript" src="{{ asset('js/moment-with-locales.min.js') }}"></script>
<script>
var vue = new Vue({
el: '#app',
data: {
isLoading: false,
cliente: '{{ $contemplado->id }}',
checked : false,
nrocpfCnpj: "{!! $contemplado->cpfCnpj !!}",
porte: '{!! $contemplado->porte !!}',
natureza_juridica: '{!! $contemplado->natureza_juridica !!}',
idERP: '{!! $contrato->idERP !!}',
originalSegmento: '{!! $contrato->originalSegmento !!}',
novoSegmento: '{!! $contrato->novoSegmento !!}',
isLoading: false,
grupo: '{!! $contrato->grupo !!}',
cota: '{!! $contrato->cota !!}',
},
mounted() {
const vm = this
var tabela = $('#example').dataTable({
"language": {
'url': '//cdn.datatables.net/plug-ins/1.10.16/i18n/Portuguese-Brasil.json'
},
'scrollX': true,
'scrollY': false,
'autoWidth': true,
responsive: true,
processing: true,
"ajax": {
"url": "montaTabelaMultiCota",
"data": {
"nrocpfCnpj": vm.nrocpfCnpj
}
},
columns: [
{ data: null,
fnCreatedCell: function (nTd, sData, oData, iRow, iCol) {
$(nTd).html("<div class='form-check'><input class='form-check-input' type='checkbox' name='cota"+oData['NUMERO-COTA']+"' value='"+oData['VALOR-BEM']+"'></div>")
}
},
{ data: 'CODIGO-GRUPO'},
{ data: 'NUMERO-COTA',
fnCreatedCell: function (nTd, sData, oData, iRow, iCol) {
$(nTd).html(oData['NUMERO-COTA'])
}
},
{ data: 'DESCRICAO-BEM'},
{ data: 'VALOR-BEM',
fnCreatedCell: function (nTd, sData, oData, iRow, iCol) {
$(nTd).html("R$ "+oData['VALOR-BEM']+",00")
}
},
{ data: 'NUMERO-CONTRATO'},
{ data: 'DATA-CONTEMPLACAO',
fnCreatedCell: function (nTd, sData, oData, iRow, iCol) {
moment.locale('pt-br');
var data = oData['DATA-CONTEMPLACAO'];
let criado = moment(data, 'YYYYMMDD').fromNow();
$(nTd).html(criado);
}
},
{ data: 'DATA-ENTREGA',
fnCreatedCell: function (nTd, sData, oData, iRow, iCol) {
moment.locale('pt-br');
var data = oData['DATA-ENTREGA'];
let criado = moment(data, 'YYYYMMDD').fromNow();
$(nTd).html(criado);
}
}
]
});
// Adds the values and updates the readonly input.
function updateTotal(){
$('input#total').val($('input.selected:checked').toArray().reduce(function(last, current){
return last + parseInt($(current).attr('data-value'));
}, 0));
}
// init the total value and bind updateTotal function to the change event on the checkboxes.
function dt_init(){
updateTotal();
$('.selected').off('change').on('change', function(e) {
updateTotal();
});
}
var dt = $('#dt_container').DataTable({
// Add the checkboxes and set the values in a data-* attribute for later
rowCallback: function(row, data){
let value = parseInt($('td:eq(4)', row).html().substring(3))
// $('td:eq(4)', row).html() : 'R$ 12975.00'
// 'R$ 12975.00'.substring(3) : '12975.00'
// parseInt('12975.00') : 12975
$('td:eq(0)', row).html(`<input class="selected" type="checkbox" data-value=${value}>`)
},
// If you need to redraw your table (sort, search, page), then you need to redo some things, that's why dt_init is called upon every time.
initComplete: function(settings, json, param){
// show the footer after the DataTable is done
$(dt.table().footer()).css('display', '');
dt_init();
},
drawCallback: function(settings){
dt_init();
}
});
},
});
</script>
#endsection
Any helps?
Thanks a lot!
You can use a footer in your datatable. Just make it initially invisible and add some boilerplate to show some results.
<table id="dt_container">
<tfoot style="display: none;">
<tr>
<th>Total:</th>
<th><input id="total" type="text" name="total" value="" readonly></th>
</tr>
</tfoot>
</table>
Next, in the javascript init the DataTable but add some callbacks
// Adds the values and updates the readonly input.
function updateTotal(){
$('input#total').val($('input.selected:checked').toArray().reduce(function(last, current){
return last + parseInt($(current).attr('data-value'));
}, 0);
}
// init the total value and bind updateTotal function to the change event on the checkboxes.
function dt_init(){
updateTotal();
$('.selected').off('change').on('change', function(e){
updateTotal();
});
}
var dt = $('#dt_container').DataTable({
// Add the checkboxes and set the values in a data-* attribute for later
rowCallback: function(row, data){
let value = parseInt($('td:eq(4)', row).html().substring(3))
// $('td:eq(4)', row).html() : 'R$ 12975.00'
// 'R$ 12975.00'.substring(3) : '12975.00'
// parseInt('12975.00') : 12975
$('td:eq(0)', row).html(`<input class="selected" type="checkbox" data-value=${value}>`)
},
// If you need to redraw your table (sort, search, page), then you need to redo some things, that's why dt_init is called upon every time.
initComplete: function(settings, json, param){
// show the footer after the DataTable is done
$(dt.table().footer()).css('display', '');
dt_init();
},
drawCallback: function(settings){
dt_init();
}
});

Confirm Before Deleting with Sweet Alert Laravel 5.5

I want the sweet alert box to go out without deleting.
But id not found for ajax
Route
Route::get('room/delete/{id}', 'RoomList#destroy')->name('roomdelete');
View File rooms-list.blade.php
#foreach($rooms as $room)
<tr>
<td>{!! $room->room_id !!}</td>
<td>{!! $room->hotel_id !!}</td>
<td>{!! $room->room_name !!}</td>
<td>
<i class="fa fa-close text-danger"></i> </td>
</tr>
#endforeach
SweetAlert Js Code above
<script>
$(document).on('click', '.button', function (e) {
e.preventDefault();
var id = $(this).data('id');
swal({
title: "Are you sure!",
type: "error",
confirmButtonClass: "btn-danger",
confirmButtonText: "Yes!",
showCancelButton: true,
},
function() {
$.ajax({
type: "POST",
url: "{{url('room/delete')}}",
data: {id:id},
success: function (data) {
}
});
});
});
</script>
Controller File RoomList.php
public function destroy($id) {
$rooms = Room::find($id);
$rooms->delete();
return redirect()->back()->with('deleted', 'Delete Success!');
}
Clicking on the delete button does not work
Best Regards
First thing first, you have a GET route and you are sending a POST request here so first change your ajax method to GET like this:
<script>
$(document).on('click', '.button', function (e) {
e.preventDefault();
var id = $(this).data('id');
swal({
title: "Are you sure!",
type: "error",
confirmButtonClass: "btn-danger",
confirmButtonText: "Yes!",
showCancelButton: true,
},
function() {
$.ajax({
type: "GET",
url: "{{url('room/delete/')}}+id", // since your route has /{id}
data: {id:id},
success: function (data) {
}
});
});
});
</script>
Also I'm not sure about $(document).on('click', '.button', function (e) I guess it should be like this:
$('.button').on('click', '.button', function (e)
Let me know If you still have any issue.

React Tutorial - Page Refreshing after Comments Added

I'm working through the official React tutorial and having a little trouble. When I add a comment I expect the comment to appear in the view, and for a split second it does, but then the page refreshes and the comment's gone.
On a related matter (and really just a request for a little FYI as I'm still learning AJAX), the code is supposed to add the comment to the JSON. I'm presuming that this wouldn't work on the Plunker but is there enough code there to actually update a JSON if the page is live?
Thanks for any help! Plunker link and code follows:
https://plnkr.co/edit/p76jB1W4Pizo0rDFYIwq?p=preview
<script type="text/babel">
// To get started with this tutorial running your own code, simply remove
// the script tag loading scripts/example.js and start writing code here.
var CommentBox = React.createClass({
loadCommentsFromServer: function() {
$.ajax({
url: this.props.url,
dataType: 'json',
cache: false,
success: function(data) {
this.setState({data: data});
}.bind(this),
error: function(xhr, status, err) {
console.error(this.props.url, status, err.toString());
}.bind(this)
});
},
handleCommentSubmit: function(comment) {
var comments = this.state.data;
// Optimistically set an id on the new comment. It will be replaced by an
// id generated by the server. In a production application you would likely
// not use Date.now() for this and would have a more robust system in place.
comment.id = Date.now();
var newComments = comments.concat([comment]);
this.setState({data: newComments});
$.ajax({
url: this.props.url,
dataType: 'json',
type: 'POST',
data: comment,
success: function(data) {
this.setState({data: data});
}.bind(this),
error: function(xhr, status, err) {
this.setState({data: comments});
console.error(this.props.url, status, err.toString());
}.bind(this)
});
},
getInitialState: function() {
return {data: []};
},
componentDidMount: function() {
this.loadCommentsFromServer();
setInterval(this.loadCommentsFromServer, this.props.pollInterval);
},
render: function() {
return (
<div className="commentBox">
<h1>Comments</h1>
<CommentList data={this.state.data} />
<CommentForm onCommentSubmit={this.handleCommentSubmit} />
</div>
);
}
});
var CommentList = React.createClass({
render: function() {
var commentNodes = this.props.data.map(function(comment) {
return (
<Comment author={comment.author} key={comment.id}>
{comment.text}
</Comment>
);
});
return (
<div className="commentList">
{commentNodes}
</div>
);
}
});
var CommentForm = React.createClass({
getInitialState: function() {
return {author: '', text: ''};
},
handleAuthorChange: function(e) {
this.setState({author: e.target.value});
},
handleTextChange: function(e) {
this.setState({text: e.target.value});
},
handleSubmit: function(e) {
e.preventDefault();
var author = this.state.author.trim();
var text = this.state.text.trim();
if (!text || !author) {
return;
}
this.props.onCommentSubmit({author: author, text: text});
this.setState({author: '', text: ''});
},
render: function() {
return (
<form className="commentForm" onSubmit={this.handleSubmit}>
<input
type="text"
placeholder="Your name"
value={this.state.author}
onChange={this.handleAuthorChange}
/>
<input
type="text"
placeholder="Say something..."
value={this.state.text}
onChange={this.handleTextChange}
/>
<input type="submit" value="Post" />
</form>
);
}
});
var Comment = React.createClass({
rawMarkup: function() {
var md = new Remarkable();
var rawMarkup = md.render(this.props.children.toString());
return { __html: rawMarkup };
},
render: function() {
return (
<div className="comment">
<h2 className="commentAuthor">
{this.props.author}
</h2>
<span dangerouslySetInnerHTML={this.rawMarkup()} />
</div>
);
}
});
ReactDOM.render(
<CommentBox url="comments.json" pollInterval={2000} />,
document.getElementById('content')
);
</script>
As you said, your problem is that the information in the json file is static (see last paragraph), so every time the comments are refreshed, you lose the new one. The way you could handle it is using the json file during the first load and then just prevent refreshing them, just adding the new ones to the comment box state (after all this is just a example and you just want to see some eye candy, don't you?).
Checking the browser's console you can see that your AJAX request to store the new file is failing, you cannot update it on Plunker, that file is immutable.

value is undefined in emberjs nested view

i have a script handlebar..
<script id="ownerItem" data-template-name='ownerItem' type="text/x-handlebars">
{{value.UserName}} <button {{action "remove" on="click"}}>Remove</button>
</script>
And its view..
ResAdmin.ownerView = Ember.View.extend({
templateName: 'ownerItem',
remove: function() {
var selectedRest;
selectedRest = ResAdmin.adminController.get('selectedRestaurant');
alert(value.RestaurantOwnerID);
return $.ajax({
url: '/api/RestaurantOwner/' + value.RestaurantOwnerID,
cache: false,
type: 'delete',
data: {
RestaurantID: selectedRest.RestaurantID,
MethodOverride: 'delete'
},
dataType: 'jsonp',
success: function(data) {
return ResAdmin.adminController.getRestaurantList();
}
});
}
});
and in some other view i am using this view like
{{#each ResAdmin.adminController.selectedRestaurant.Owners}}
{{view ResAdmin.ownerView valueBinding="this" content="this"}}
{{/each}}
but i am getting error(value is not defined) when user click on remove button of my nested view...can anybody help me ??
value is a property of the ownerView so you need to qualify it with this.get('value')
e.g.
this.get('value').RestaurantOwnerId

Resources