How to use server-side processing in JQuery DataTables without Ajax - javascript

I'm using JQuery DataTables with Vue 2. The below snippet shows how I'm using it with a JSON data source fetched from a custom method using the wretch package (it also handles authorization).
...
mounted: function () {
this.dataTable = window.$(this.$el).DataTable({
data: this.getGridData,
columns: this.getColumns,
// serverSide: true
});
},
...
This method is working fine. Now I want to enable the serverSide feature to control pagination and search without using the ajax option.
My backend application is running in .NET Framework. I have created my response data structure as shown here, but it doesn't seem to help.
Simply, I want to use my custom method to fetch data into the DataTable while using the serverSide feature.
Is this possible? I'm looking forward to your help.

DataTables has various different forms for its ajax option.
One of these is as follows:
$('#example').dataTable( {
"serverSide": true,
"ajax": function (data, callback, settings) {
// whatever logic you want to use can go here,
// as long as it evaluates to a valid JSON structure
// expected by DataTables, as a server-side response.
callback(
resultsOfYourLogic
);
}
} );
You can read its description in the linked documentation - but it basically states:
As a function, making the Ajax call is left up to yourself allowing complete control of the Ajax request. Indeed, if desired, a method other than Ajax could be used to obtain the required data...
Therefore, you can use this - with serverSide: true - to use any alternative method you wish to source your data.
Example:
"ajax": function (data, callback, settings) {
var dataSet = yourCustomFunction(data);
callback(
dataSet
);
},
Here, the custom function is invoked first, returning the JSON which needs to be displayed. The request data is passed to that custom function. Then the results of that custom function are placed in the callback.
One important note here is: The data parameter in the callback will be pre-populated with the server-side request data (automatically created by DataTables whenever the user sorts/filters/pages). So you will need to handle this request data, to know how your response data needs to be built.
(The response data structure you link to in your question, is the correct structure.)

Related

Update Data in Table on Save with No Refresh (Ajax/JavaScript)

I have the following function that is the event listener function to a button. When the button is clicked, this function is called and it should be updating an HTML table. It is doing so properly, but not until the user refreshes the page. What must I change on the front-end in order to make the table updates occur as soon as this button is clicked rather than forcing the user to refresh the page? Thank you!
function dialogWindowSaveAddressBookEditsButton_Click(addressBookObject) {
$.ajax({
type: "POST",
url: "/Services/AsyncServices.svc/DialogWindowSaveAddressBookEditsButton_Click",
contentType: "application/json",
data: JSON.stringify(addressBookObject),
success: function (result) {
if (result.d == false) {
...
}
else {
...
}
}
});
}
You have the result from your post request - you need to format it and then set the html table (or whatever component is it) to display that data.
You are not providing enough information (as of are you using any framework or just pure javascript), so I would suggest you to look into how data binding works for web development. https://www.wintellect.com/data-binding-pure-javascript/
If you are using a framework (AngularJs, React, Ember etc) look into how to bind data - it is usually very simple
When you call an ajax request then you must handle its response and update DOM accordingly. If the request is returning HTML then you can just render that under any element you want like this:
$(‘#element).html(response)
If it’s returning JSON then you should set values accordingly to your DOM elements by using Jquery:
$(“.your-table or td”).text(resp.value)
I resolved the issue through adding the following to the success property:
location.reload(true);

jquery tabledit dropdown: is it possible to retrieve values from mysql database?

I'm using the jquery tabledit plug-in to update a database. Works perfectly like in the official examples.
I can succesfuly include a static dropdown with a fixed number of options (defined in custom_table_edit.js).
I'd like to be able to dynamically get those options from a database instead, but I don't know how to customize the code in custom_table_edit.js.
I can code this in php with a loop querying the database and generating a html <select> field. But I don't have knowledge of javascript or if it's even possible in this framework.
This is the custom_table_edit.js file. A dropdown is defined with three colour options. I want this dropdown to be dynamically produced.
// custom_table_edit.js
$('#example2').Tabledit({
url: 'example.php',
eventType: 'dblclick',
editButton: false,
columns: {
identifier: [0, 'id'],
editable: [[1, 'car'], [2, 'color', '{"1": "Red", "2": "Green", "3": "Blue"}']]
}
});
I really haven't tried anything because i'd like to know if it's possible to do in this framework.
Welcome to SO, nucelar.
What you are describing is a HTTP request from the client to server through JavaScript. This is commonly referred as AJAX or Asynchronous JavaScript And XML. This API enables you to manually send requests to the server and there are multiple implementations.
Because you are using jQuery I will recommend you to use the $.ajax function which is included in the jQuery library.
Down here I've made a very basic example of how to send a HTTP request to a server with the GET method to retrieve some data.
$.ajax({
url: 'https://yourdomain.com', // Where to send the request to. Can also be a file.
method: 'GET', // What method of request it uses.
success: function(data) { // When a response is succesfully received.
// Do something with the received data.
console.log(data); // Show what the data looks like in the console.
},
error: function(jqXHR, textStatus, errorThrown) { // When an error occurs while making a request.
console.log(jqXHR, textStatus, errorThrown); // Show the error in the console.
}
});
In your case the url property value might be the URL of a PHP file in which you query the database and return the result, as you mentioned you are able to do.
The response of the AJAX function (which is stored in the data variable in the success method) can be text, as in a string, or even JSON if you want to send structured data.
Beware of the Asynchronous part. This means that the AJAX code does not stop the execution of the rest of your JavaScript code, but simply continues and comes back whenever the HTTP request has been completed.
I hope that this is enough to get you started. Good luck and don't hesitate to ask questions.

Limiting AJAX results, and getting different outputs

I have recently started to use AJAX with JQuery. I now know how to limit results in AJAX GET requests. However, I have no idea how to make a client-side button to load more requests. Say I have 100 people on the JSON file and i want to load 3 at the time. If the button is pressed, the next three load and the last three disappear.
I used this to limit:
$.ajax({
type: "GET",
url: "/people",
data: {limit: 3, order: 'desc'},
dataType: "json",
success: function(data) {
// Do some awesome stuff.
}
});
Other than limiting results, I really have no idea how to load more results.
What you need is to determine the manner in which you can execute your ajax request such as using a button that will load more data.
Firstly, you've mentioned you can successfully return the limited data by passing parameters to your ajax request, that's great.
You can wrap your ajax request in a function that will allow you to pass parameters such as limit and order direction. Now, I won't go all out here since there's very little information to work with. But to create a button that you can click that will load more data is something that can be demonstrated here.
Here's your AJAX request. We can wrap it in a function that accepts parameters. For example, limit defaults to 3, order defaults to "desc". The possibilities here are endless. You'll obviously want offsets and such but that you can work with as you go along. The purpose of this is only to demonstrate how you could create a button to fetch more data.
jQuery has a shorthand method called $.getJSON which will load JSON-encoded data using a GET HTTP request.
So here's the function which we can later call from the click of a button.
function fetchPeople(limit = 3, order = "desc") {
$.getJSON(
"/people",
{
limit: limit,
order: order
},
function (data) {
// Do something with your data
}
);
}
The button may be something like this.
<button type="button" id="loadMore">Load more</button>
In jQuery you can bind event listeners that will trigger, e.g. on click, and this listener will trigger your function that will go off to fetch whatever it is you've configured in the wrapper function.
$("#loadMore").on("click", function () {
fetchPeople();
});
There are a plethora of plugins for jQuery and code examples across StackOverflow and the WWW in general.
But I'm hoping this steers you in the right direction.

Best way to transport data on MVC using jQuery?

I have an Inbox with internal messages from my clients. When I click on the list over the name I'm requesting using jQuery $.ajax so:
$.ajax({
url: 'messages/retrieve/' + client_id,
}).done( function(data) {
$('.messages-dialog').html(data);
});
My controller should return a variable with json data? I understand it should dump it on a view and I should treat it there but how to do it if is client side?
I don't know if is better to treat and create the html structure into controller and than just load it in .messages-dialog with jQuery.html();
Sorry I'm a little lost on that issue.
You can use jQuery.ajax() method, as in the example above. Also see the official documentation with examples http://api.jquery.com/jquery.ajax/.
Besides you can use jQuery.get() and jQuery.post() methods depending on how and what you will send. You can use this methods as shown below:
var url = 'messages/retrieve/' + client_id;
$.post( // for example
url,
function( data ) {
$('.messages-dialog').html(data);
});
See official documentation with examples here: http://api.jquery.com/get/, http://api.jquery.com/jQuery.post/.
Server handler should be like as below:
use JsonResponse; // you must specify the exact component (I use this)
/**
* Change message in dialog // for example
*/
public function changeDialogMessageAction(Request $request) {
// request data processing
$response = new JsonResponse();
$response->setData(array(
// new data for returning to client
));
return $response; // your data, which will be handled in callback
}
You shouldn't create HTML structure in the controller. It's bad style! JavaScript has asynchronous event model, and you should use it. Controller must handle / transform data, which were passed by you and then return back. jQuery callback must embed received handled / transformed data in DOM.

How to receive POST data of ajax call in a javascript function

I need a little help. I am trying to implement bootstrap data table with ajax pagination. As this is mobile app (Cordova), I am fully dependent on javascript for server side too. Thats why in the url I am calling javascript function. Now I am not sure about how to get the POST data in it. Any help will be appreciated.
$(document).ready(function(){
$("‪#‎products‬").dataTable({
aLengthMenu: [
[10, 25, 50, 100, -1], [10, 25, 50, 100, "All"]
],
aaSorting: [],
bProcessing: true,
serverSide: true,
ajax:{
url : ProductList.getProductsPaginated(),
type: "post", // type of method , by default would be get
error: function(){ // error handling code
}
}
});
ProductList.getProductsPaginated(){
// This method gets called succesfully
// Need the post data here
}
});
Edit:
Let, without using the function as url param, let use a html page directly like
url : "page.html",
Now, how to get those post data in the html or js? Is there any other way for what I am looking?
I don't understand why you need the data inside that function, but it isn't getting called on ajax success, it's invoked because of the parenthesis, the only thing I think you could do there is to return the path of your json data, however you can call a function with your post data on ajax success like this:
ajax: {
url : ProductList.getProductsPaginated(),
type: "post",
dataSrc: function (data) {
// you can call a function here with the data as parameter
// you have to return the data, with modifications if you need
return data;
}
}
Thank you all for trying to help me. I have found no way to post data to a javascript function using ajax. In this case, I am unable to use DataTable's ajax feature to minimise data loading time by pagination. Ajax call can be made to server-side scripts only. Thats why I have disabled datatable's paging and implemented custom pagination using javascript.

Categories