Is it possible to catch response from DataTables when reloading the table or is it possible to pass all the data (I mean filters) which is passed by the DataTables request with own function?
I need SQL query built by the SSP class and then use it in my own function. I want to do something with filtered data, but I need much more data than is in my table.
I thought about something like this:
var myData = table.ajax("myFileWithModifiedSSP.php").load();
In this case it would pass all params like to refresh the table, but in the end it would return something else and NOT refresh the dataTable.
My second thought is to send only parameters with ajax to my file and do what I need. Something like this:
function myFuncton(){
$.ajax({
url : "myURL.php",
data : DATATABLES_PARAMETERS,
success : function(data){
//do what I need
}
});
}
EDIT
I didn't mention it earlier that I have initialized table, added some own filters. Everything works perfect now.
The only thing I need is to get somehow all request parameters which are send by the Datatables script and use them for something else.
For example let's say that I have button named "export", I filter data in my table using my filters and search engine (from DataTables), then I get result into my table.
The next step is to click "export" and now I need previously passed arguments (by DataTables) to use them in other script to do something with the data. I only need the same parameters, to build new query and do something with data.
You can use ajax.params(), that gets the data submitted by DataTables to the server in the last Ajax request.
See this example:
var table = $('#example').DataTable({
ajax: "data.json",
serverSide: true
});
table.on('xhr', function () {
var data = table.ajax.params();
alert('Search term was: ' + data.search.value);
});
If you use data returned by ajax.params() as value to data property of $.ajax(), you can get the same request that could be submitted to a different URL, for example:
$.ajax({
'url': 'script.php',
'data': $('#example').DataTable().ajax.params()
});
I think you need like this
$('#datatable_id').dataTable( {
"iDisplayLength": 50,
"ajax": function(data, callback, settings) {
$.get(url, {
param1: param1_value,
param2: param2_value,
}, function(res) {
callback({
data: response.data
});
});
}});
Please note I am using get as ajax method type. You can use post or what ever you would like to.
Related
I'm using ajax POST method
to send objects stored in an array to Mvc Controller to save them to a database, but list in my controller is allways empty
while in Javascript there are items in an array.
here is my code with Console.Log.
My controller is called a ProductController, ActionMethod is called Print, so I written:
"Product/Print"
Console.Log showed this:
So there are 3 items!
var print = function () {
console.log(productList);
$.ajax({
type: "POST",
url: "Product/Print",
traditional: true,
data: { productList: JSON.stringify(productList) }
});}
And when Method in my controller is called list is empty as image shows:
Obliviously something is wrong, and I don't know what, I'm trying to figure it out but It's kinda hard, because I thought everything is allright,
I'm new to javascript so probably this is not best approach?
Thanks guys
Cheers
When sending complex data over ajax, you need to send the json stringified version of the js object while specifying the contentType as "application/json". With the Content-Type header, the model binder will be able to read the data from the right place (in this case, the request body) and map to your parameter.
Also you do not need to specify the parameter name in your data(which will create a json string like productList=yourArraySuff and model binder won't be able to deserialize that to your parameter type). Just send the stringified version of your array.
This should work
var productList = [{ code: 'abc' }, { code: 'def' }];
var url = "Product/Print";
$.ajax({
type: "POST",
url: url,
contentType:"application/json",
data: JSON.stringify(productList)
}).done(function(res) {
console.log('result from the call ',res);
}).fail(function(x, a, e) {
alert(e);
});
If your js code is inside the razor view, you can also leverage the Url.Action helper method to generate the correct relative url to the action method.
var url = "#Url.Action("Print","Product)";
I'm trying to setup my datatable to POST to the contents of it's rows into my PHP script so that I can store it in a database.
I have a working HTML page, which when I click "+ Add Mapping" a BS modal appears and I can add a row to the datatable.
<script>
$(document).ready(function() {
var t = $('#parameters_config').DataTable();
$('#add_new_mapping').on('click', function() {
$('#add_field_mapping').modal('hide');
var wb_field = $("#add_field_mapping #wb_field").val();
var adobe_field = $("#add_field_mapping #adobe_field").val();
t.row.add([
adobe_field,
wb_field,
]).draw();
$('#add_new_field_mapping').trigger("reset");
});
});
</script>
This all works perfectly. I now would like to retrieve all data rows and POST them to my script so that I can process the submitted data and store. So far, I've come up with this based on information provided:
<script>
$(document).ready(function() {
$('#parameters').submit(function(event) {
var table = $('#parameters_config').DataTable();
var dataToSend = table
.rows()
.data();
console.log( 'Data', dataToSend);
alert( 'There are '+dataToSend.length+' row(s) of data in this table');
$.ajax({
type: 'POST',
url: '{$this->homeURL}',
data: dataToSend,
dataType: 'json',
});
});
});
</script>
In my console window I see the following returned for "dataToSend" but no actual data!
[Array[2], context: Array[1], selector: Object, ajax: Object]
Where am I going wrong?
Where the examples went wrong
The two examples you linked in your post aren't really related to what you're trying to do (from what I can gather about your goal).
The first example is about how to obtain data from the server with a POST instead of the default GET, and has nothing to do with sending data to the server for some purpose.
The second example is about serverside processing, which is where you have pagination, ordering, sorting, filtering, and all other DataTables features handled in your own server code where you then send the results to the client (which is pretty complicated and unless you have a huge number of rows, unnecessary).
Therefore, remove serverSide: true!
Your Goal
What you actually want to do (I think) is send your data to a php script so that you can do something with it. This is not handled by any DataTables API call, but is a fairly simple feature to implement. All you really need is a function that will make an AJAX call that will send the data to the script.
Solution
The way you can do this is by obtaining the data with the t.data() API call, and then sending it with an ajax request. It might look like this:
function sendData(){
var dataToSend = t.data();
$.ajax({
type: 'POST',
url: 'URL OF SCRIPT HERE',
data: dataToSend
});
}
Then you simply have to call sendData() whenever it is that you want to send the data. Of course, you'll have to ensure that your controller handles the data correctly, but that's a different matter entirely.
I am working on the backend for a webpage that displays EPG information for TV channels from a SQlite3 database. The data is provided by a PHP script echoing a JSON string. This itself works, executing the php program manually creates a JSON string of this format
[{"id":"0001","name":"RTL","frequency":"626000000"},{"id":...
I want to use these objects later to create HTML elements but the ajax function to get the string doesn't work. I have looked at multiple examples and tutorials but they all seemed to be focused more on having PHP return self contained HTML elements. The relevant js on my page is this:
var channelList;
$(document).ready(function() {
$.ajax({
url: 'channellookup.php',
dataType: "json",
success: function(data) {
console.log(data.success);
channelList = data;
}
});
});
However the channelList variable remains empty when inspected via console.
What am I doing wrong?
Please ensure that your PHP echoing the correct type of content.
To echo the JSON, please add the content-type in response header.
<?php
header(‘Content-type:text/json’); // To ensure output json type.
echo $your_json;
?>
It's because the variable is empty when the program runs. It is only populated once AJAX runs, and isn't updating the DOM when the variable is updated. You should use a callback and pass in the data from success() and use it where you need to.
Wrap the AJAX call in a function with a callback argument. Something like this:
function getChannels(callback){
$.ajax({
url: 'channellookup.php',
dataType: "json",
success: function(data) {
console.log(data);
if (typeof(callback) === 'function') {
callback(data);
}
},
error: function(data) {
if (typeof(callback) === 'function') {
callback(data);
}
}
});
}
Then use it when it becomes available. You should also use error() to help debug and it will quickly tell you if the error is on the client or server. This is slightly verbose because I'm checking to make sure callback is a function, but it's good practice to always check and fail gracefully.
getChannels(function(channels){
$('.channelDiv').html(channels.name);
$('.channelDiv2').html(channels.someOtherProperty);
});
I didn't test this, but this is how the flow should go. This SO post may be helpful.
EDIT: This is why frameworks like Angular are great, because you can quickly set watchers that will handle updating for you.
I know I can use the function fnGetData() but that only gets me the data for whichever page I'm on. I want to get all of the data, even from pages not currently displayed. My purpose is to get all of the latitude & longitude fields so that I can display it on a map using Google Maps v3.
I have this code but, again, it only gets me data for the current page.
var table = $('#example1 table').dataTable();
var data = table.fnGetData();
console.log(data);
When server-side processing is enabled ('serverSide': true), indeed both 1.9.x function fnGetData() and 1.10.x function data() return data for current page only.
This behavior could be confirmed by viewing Server-side processing example and running in the console $('#example').dataTable().fnGetData() or $('#example').DataTable().data().
In order to retrieve all data, you need to make a separate AJAX request mimicking the behavior of the DataTables.
Since your question is tagged datatables-1.10 I assume you're using DataTables 1.10.x. You can use ajax.params(), that gets the data submitted by DataTables to the server in the last Ajax request.
function processAllRecords(){
var req = $('#example1 table').DataTable().ajax.params();
// Reset request parameters to retrieve all records
req.start = 0;
req.length = -1;
req.search.value = "";
// Request data
$.ajax({
'url': 'script.php',
'data': req,
'dataType': 'json'
})
.done(function(json){
// json.data is array of data source objects (array/object),
// one for each row
console.log(json);
});
}
use the fnSettings().fnRecordsTotal() of the datatable.
example : http://www.datatables.net/forums/discussion/2401/record-count-with-server-side-processing
I have used it before and I think I could give you a snippet:
var table = $('#table ').DataTable(
{
"dom" : 'rtp', // Initiate drag column
"fnDraw" : false,
"serverSide": true,
"ajax" : ... ...
}
}),
"fnDrawCallback" : drawCallBack,
});
unction drawCallBack() {
console.log(this.fnSettings().fnRecordsTotal());
}
I have the following code, as part of a code to add some value to a database.
After executing the $.ajax succesfully, I want a specific div (with class 'lijst') to be reloaded with the refreshed data.
$.ajax({
url: \"frontend/inc/functions/add_selectie.php\",
type: \"POST\",
data: ({ 'p_id' : p_id, 'v_id' : v_id, 'pd_id' : pd_id }),
cache: false,
success: function()
{
$(\".lijst\").hide().fadeIn('slow');
}
});
However, with this solution, only the div is refreshed, not the actual PHP variables that are specified in there. When I refresh my browser manually, the values are updated.
How can I refresh the div and also update the variables?
According to the jQuery.ajax documentation, the function signature of "success".
Type: Function( PlainObject data, String textStatus, jqXHR
jqXHR ) A function to be called if the request succeeds. The function
gets passed three arguments: The data returned from the server ...
So in other words:
success: function(data) {
$(".lijst").html(data).hide().fadeIn('slow');
}
Actually, the PHP variables specified in the html are worked at the sever part. PHP variables in the html have replaced by the string of there value when it is ready to be sent to the browser. And your ajax request will cause PHP to update database. So when you have sent the request and then refresh the page, PHP will replace the varables in the html again.
According to this above, your ajax request and the server repsonse are not aware of the PHP variables's existence. So you must update the content yourself.
Maybe you will do something like this:
success: function(data) {
$(".lijst").hide();
$(".title").html(data.title); // $(".title") may be a tag that surround a PHP variable
$(".content").html(data.content); // the same as $(".title")
$(".lijst").fadeIn('slow');
}