how to use jquery datatables with ajax calls - javascript

How to use ajax callbacks with jquery datatables i.e. call function on click?:
THIS WORKS
$(document).ready(function() {
var table = $('#example').DataTable();
$('#example tbody').on('click', 'tr', function () {
var data = table.row( this ).data();
alert( 'You clicked on '+data[0]+'\'s row' );
} );
} );
replacing alert( 'You clicked on '+data[0]+'\'s row' ); with Ajax call:
DOES NOT WORK
$(document).ready(function() {
var table = $('#example').DataTable();
$('#example tbody').on('click', 'tr', function () {
var data = table.row( this ).data();
//alert( 'You clicked on '+data[0]+'\'s row' );
$.ajax({
url: '/process',
data: data[0],
type: 'POST',
success: function(response) {
$("#response_placeholder").html(response);
},
error: function(error) {
console.log(error);
}
});
} );
} );
backend
#--app.py----
#app.route('/process', methods=['POST'])
def process_data():
data = request.form['data[0]'];
print data
return render_template('mypage.html', result=data)

try to use this.
$('body').delegate('#example tbody tr','click' , function () {
} );
Delegate helps to add events on elements that get added to the dom after it has been loaded.
also it is handy to put the data in an object like this
data: {data: data[0]},
and the url should contain a extension probably
url: '/process.js', // or process.php depends on what extension it has.
and for standards you should define the 3 attributes that will be returned with error eg.
error: function(jqXHR, textStatus, errorThrown) {

Related

DataTables.js removes multiple rows on row().remove().draw() call

When I row(row).remove().draw(false) on a row Datatables removes an extra row.
This is my javascript:
$('.wrapper').on('click', '#confirm_delete', function(e) {
e.preventDefault();
var modal = $(this).closest('.modal');
var id = modal.find('#delete_id').val();
var row = $('#list_bkng_bus').find('.booking-id[value="'+id+'"]').closest('tr');
$.ajax({
type: 'POST',
url: '/includes/ajax/bookings-bus.php',
dataType: 'json',
data: { 'delete_id': id },
success: function(result) {
bkng_bus_table.row(row).remove().draw(false);
modal.modal('hide');
status_message('success', 'Boeking verwijderd');
},
error: function(xhr, status, error) {
console.log(xhr.responseText);
console.log(error);
status_message('error', 'Databasefout. (Remove booking business)');
}
});
});
This is the content of my row variable:
0 : tr.even
context : document
length : 1
prevObject : [input.booking-id, prevObject: n.fn.init(1), context: document, selector: "#list_bkng_bus .booking-id[value="57"]"]
So it contains a tr.
you code should work, and if not then you VAR row should have problem.
in case of more information you can check
The issue was the fact that because of the way the table was generated (dynamically), multiple event listeners were attached to the element.
The solution was using .off('click') before .on('click', '#confirm_delete', function(e) {.
Which makes this code function as expected:
$('.wrapper').off('click').on('click', '#confirm_delete', function(e) {
e.preventDefault();
var modal = $(this).closest('.modal');
var id = modal.find('#delete_id').val();
var row = $('#list_bkng_bus').find('.booking-id[value="'+id+'"]').closest('tr');
$.ajax({
type: 'POST',
url: '/includes/ajax/bookings-bus.php',
dataType: 'json',
data: { 'delete_id': id },
success: function(result) {
bkng_bus_table.row(row).remove().draw(false);
modal.modal('hide');
status_message('success', 'Boeking verwijderd');
},
error: function(xhr, status, error) {
console.log(xhr.responseText);
console.log(error);
status_message('error', 'Databasefout. (Remove booking business)');
}
});
});

MVC5 Ajax update

I have a dropdown with selection id StaffId. What I am doing is once an item is selected I want to pass on the StaffId to controller to fetch records in a database using the staffId. This is giving an error on page load without passing the StaffId to the controller. below is the snippet
controller
[HttpPost]
public PartialViewResult GetStaffPosts(int? id)
{
var sPost = db.StaffPosts.Where(a => a.StaffId == id.Value);
return PartialView(sPost.ToList());
}
<div id="divPartialView">
#{Html.RenderPartial("GetStaffPosts");}
</div>
<script type="text/javascript">
$(document).ready(function () {
$("#StaffId").change(function (event) {
var options = {};
options.url= "/StaffPost/GetStaffPosts/" + $(this).val(),
options.data= { id: $(this).val() },
options.cache= false,
optionstype= "POST",
options.dataType= "html",
options.success= function (data, textStatus, XMLHttpRequest) {
$("#divPartialView").html(data); // HTML DOM replace
$.ajax(options);
}
});
});
</script>
Your current code is not actually making an ajax call on the change event because you are invoking the $.ajax(options); call inside the success callback of the options object. You are not calling the $.ajax method on the change event!
This should work (assuming your controller code is returning a 200 response).
$("#StaffId").change(function (event) {
var options = {};
options.url= "/StaffPost/GetStaffPosts/" + $(this).val(),
options.data= { id: $(this).val() },
options.cache= false,
options.type= "POST",
options.dataType= "html",
options.success= function (data, textStatus, XMLHttpRequest) {
$("#divPartialView").html(data); // HTML DOM replace
}
$.ajax(options);
});
You may also simplify your code using the $.post method.
$("#StaffId").change(function() {
$.post("/StaffPost/GetStaffPosts/",{ id: $(this).val() } ,function (data) {
$("#divPartialView").html(data);
});
});
Or even using the $.load method and a one liner
$("#StaffId").change(function(event) {
$("#divPartialView").load("/StaffPost/GetStaffPosts/", { id: $(this).val() });
});
Hi just put your ajax call outside of the success function and make an url like the below code and try again
Your changed code:
<script type="text/javascript">
$(document).ready(function () {
$("#StaffId").change(function (event) {
var options = {};
options.url= "../StaffPost/GetStaffPosts,
options.data= { id: $(this).val() },
options.cache= false,
optionstype= "POST",
options.dataType= "html",
options.success= function (data, textStatus, XMLHttpRequest)
{
$("#divPartialView").html(data); // HTML DOM replace
}
$.ajax(options);
});
});
</script>

Datatables, change AJAX data ( not with elements )

I have a Datatable which is getting populated by AJAX. All is good but i want to have some shortcuts to request data from the server. Problem is how can i change the data i'm sending on the fly ? I know i can create an element <input> or something and it can get the value from that, but i was hoping i could change the data once something is clicked.
var Table = $('#table').DataTable({
"ajax": {
"type" : "POST",
"url": "url",
"data": function ( d ) {
d.cmd = "offline";
}
},
});
This works fine and passes the cmd as offline back to the server.
How can i change that value on click before the ajax.reload is called.
$('#online_btn').on( 'click', function () {
Table.ajax.reload();
} );
Using this
$('#online_btn').on( 'click', function () {
var d = [];
d.cmd = "online";
Table.ajax.data(d);
Table.ajax.reload();
} );
Gives back an ajax.data is not a function error
You could modify an object and use $.extend() to merge within the data function
var myData ={};
var Table = $('#table').DataTable({
"ajax": {
"type" : "POST",
"url": "url",
"data": function ( d ) {
return $.extend(d, myData);
}
},
});
$('#online_btn').on( 'click', function () {
myData.cmd = "online";
Table.ajax.reload();
});
Use jquery ajax beforesend object.
$.ajax({
url: "http://fiddle.jshell.net/favicon.png",
beforeSend: function( xhr ) {
//update your value here
}
})
source: jquery documentation
beforeSend
Type: Function( jqXHR jqXHR, PlainObject settings )
A pre-request callback function that can be used to modify the jqXHR (in jQuery 1.4.x, XMLHTTPRequest) object before it is sent. Use this to set custom headers, etc. The jqXHR and settings objects are passed as arguments. This is an Ajax Event. Returning false in the beforeSend function will cancel the request. As of jQuery 1.5, the beforeSend option will be called regardless of the type of request.
I do this in 2021:
function customSearch(){
let t = JSON.parse(window.filter);
t["custom-field"] = $('input[name="custom-field"]').val() || "";
window.filter = JSON.stringify(t);
return window.filter;
}
const table = $('#table').DataTable({
ajax:{
url:"my-wonderful-url.json",
type:"POST",
data: function(d) {
const t = customSearch();
return Object.assign(d, {filter:t});
},
error:function(e){console.log(e);},
});
$('input[name="custom-field"]').on('keyup', function(e){
table.ajax.reload(null, false);
});

how to combine post and get method with jquery?

I have two jquery function get and post.
I retrieve data from get method first and post my data with post method.
I want to know how to combine this two function.
POST Method
var url = '/api/sample?id=' + id ;
AJAXnotification("Saving...", 'info');
$.post( url , form)
.done(function(){
AJAXnotification("Saved", 'success', 5000);
})
.fail(function() {
AJAXnotification("Cannot save", 'error');
});
GET Method
AJAXnotification("Loading...", 'info');
var fail_callback = function() {
AJAXnotification("Cannot load ", 'error');
}
$.get('/api/samples', {
'id' : id,
'merge' : 'departures',
'departures.from_date': from_date,
'departures.to_date' : to_date
}).done(function( tours ){
AJAXnotification(" loaded", 'success', 5000);
});
Just embedding the $.post inside the .done function of your $.get will make the $.post fire after the $.get returns, and you'll be able to access all of the returned data:
$.get('/api/samples', {
'id' : id,
'merge' : 'departures',
'departures.from_date': from_date,
'departures.to_date' : to_date
}).done(function( tours ){
AJAXnotification(" loaded", 'success', 5000);
var url = '/api/sample?id=' + id ;
AJAXnotification("Saving...", 'info');
$.post( url , form)
.done(function(){
AJAXnotification("Saved", 'success', 5000);
})
.fail(function() {
AJAXnotification("Cannot save", 'error');
});
});
You can add your POST operation to the .done callback of the GET operation.
$.get('/api/samples', {
...
}).done(function( tours ){
$.post( url , form)
.done(function(){
...
})
.fail(function() {
...
});
});
You can do this way :
<form id="myForm">
<input type="text" name="nameGet" id="nameGet" />
<input type="text" name="namePost" id="namePost" />
<input onclick="submitGetPostForm();" type="button" name="submitBtm" id="submitBtm" value="submit" />
</form>
<script>
function submitGetPostForm()
{
nameGet=$('#nameGet').val();
namePost=$('#namePost').val();
$.ajax({
url: "testPage.php?nameGet="+nameGet,
type: "post",
data: {namePost:namePost},
success: function(response_msg){
response_msg=$.trim(response_msg);
alert(response_msg);
},
error:function(){
alert("Failure, some problem");
}
});
}
</script>

Passing arguments to ajax within a generic function

This is making me crazy:
I can successfully pass arguments into this function, and display them in an alert. I can also populate the div by id, if I define the values in the function.
function getStuff( req, elementid ) {
//var req = 'slider';
//var elementid = '#slider';
//var req = 'thumbnails';
//var elementid = '#thumbnails';
$.ajax({
async: false,
url: '/update',
contentType: 'text/html',
data: { putski: req },
type: 'GET',
dataType: "html",
success: function(stuff) {
$( elementid ).html(stuff);
alert(req+elementid)
},
error: function( xhr, status, errorThrown ) {
alert( "Sorry, there was a problem!" );
( "Error: " + errorThrown );
console.log( "Status: " + status );
console.dir( xhr );
},
complete: function( xhr, status ) {
return false;
}
});
};
$(document).ready( getStuff( 'thumbnails', '#thumbnails' ) ); // alert shows thumbnails#thumbnails but div does not populate.
The following variation is populating and should rule out issues other than the one I've described.
function getStuff( req, elementid ) {
var req = 'slider'; //uncomment these definitions and the div populates
var elementid = '#slider';
//var req = 'thumbnails';
//var elementid = '#thumbnails';
$.ajax({
async: false,
url: '/update',
contentType: 'text/html',
data: { putski: req },
type: 'GET',
dataType: "html",
success: function(stuff) {
$( elementid ).html(stuff);
alert(req+elementid)
},
error: function( xhr, status, errorThrown ) {
alert( "Sorry, there was a problem!" );
( "Error: " + errorThrown );
console.log( "Status: " + status );
console.dir( xhr );
},
complete: function( xhr, status ) {
return false;
}
});
};
$(document).ready( getStuff ); // populated using the values defined at the top.
You are comparing apples to oranges
In the second version, you can try the following:
var req = 'thumbnails';
var elementid = '#thumbnails';
If this doesn't work then you know that either the server code is not dealing with the "thumbnails" parameter correctly, or the element id "#thumbnails" is not defined. I doubt that the problem is with passing the parameters vs. setting them in the function.
Okay, I fixed it but I have to admit, I don't really understand the behavior. I commented out "async: false," and it started working with the thumbnails. I added that line in the first place because the slider doesn't work without it. :p Maybe someone could shed some light on this?

Categories

Resources