I'm trying to use server processing with data tables:
$("#my-table-id").DataTable( {
serverSide: true,
ajax: {
url: '/request/path/',
type: 'POST',
}
});
sends data as url encoded, which as you can see is pretty unmanageable:
draw=1&columns%5B0%5D%5Bdata%5D=0&columns%5B0%5D%5Bname%5D=&columns%5B0%5D%5Bsearchable%5D=true&columns%5B0%5D%5Borderable%5D=true&columns%5B0%5D%5Bsearch%5D%5Bvalue%5D=&columns%5B0%5D%5Bsearch%5D%5Bregex%5D=false&columns%5B1%5D%5Bdata%5D=1&columns%5B1%5D%5Bname%5D=&columns%5B1%5D%5Bsearchable%5D=true&columns%5B1%5D%5Borderable%5D=true&columns%5B1%5D%5Bsearch%5D%5Bvalue%5D=&columns%5B1%5D%5Bsearch%5D%5Bregex%5D=false&columns%5B2%5D%5Bdata%5D=2&columns%5B2%5D%5Bname%5D=&columns%5B2%5D%5Bsearchable%5D=true&columns%5B2%5D%5Borderable%5D=true&columns%5B2%5D%5Bsearch%5D%5Bvalue%5D=&columns%5B2%5D%5Bsearch%5D%5Bregex%5D=false&columns%5B3%5D%5Bdata%5D=3&columns%5B3%5D%5Bname%5D=&columns%5B3%5D%5Bsearchable%5D=true&columns%5B3%5D%5Borderable%5D=true&columns%5B3%5D%5Bsearch%5D%5Bvalue%5D=&columns%5B3%5D%5Bsearch%5D%5Bregex%5D=false&columns%5B4%5D%5Bdata%5D=4&columns%5B4%5D%5Bname%5D=&columns%5B4%5D%5Bsearchable%5D=true&columns%5B4%5D%5Borderable%5D=true&columns%5B4%5D%5Bsearch%5D%5Bvalue%5D=&columns%5B4%5D%5Bsearch%5D%5Bregex%5D=false&columns%5B5%5D%5Bdata%5D=5&columns%5B5%5D%5Bname%5D=&columns%5B5%5D%5Bsearchable%5D=true&columns%5B5%5D%5Borderable%5D=true&columns%5B5%5D%5Bsearch%5D%5Bvalue%5D=&columns%5B5%5D%5Bsearch%5D%5Bregex%5D=false&columns%5B6%5D%5Bdata%5D=6&columns%5B6%5D%5Bname%5D=&columns%5B6%5D%5Bsearchable%5D=true&columns%5B6%5D%5Borderable%5D=true&columns%5B6%5D%5Bsearch%5D%5Bvalue%5D=&columns%5B6%5D%5Bsearch%5D%5Bregex%5D=false&columns%5B7%5D%5Bdata%5D=7&columns%5B7%5D%5Bname%5D=&columns%5B7%5D%5Bsearchable%5D=true&columns%5B7%5D%5Borderable%5D=true&columns%5B7%5D%5Bsearch%5D%5Bvalue%5D=&columns%5B7%5D%5Bsearch%5D%5Bregex%5D=false&order%5B0%5D%5Bcolumn%5D=0&order%5B0%5D%5Bdir%5D=asc&start=0&length=100&search%5Bvalue%5D=&search%5Bregex%5D=false
decoded:
draw=1&columns[0][data]=0&columns[0][name]=&columns[0][searchable]=true&columns[0][orderable]=true&columns[0][search][value]=&columns[0][search][regex]=false&columns[1][data]=1&columns[1][name]=&columns[1][searchable]=true&columns[1][orderable]=true&columns[1][search][value]=&columns[1][search][regex]=false&columns[2][data]=2&columns[2][name]=&columns[2][searchable]=true&columns[2][orderable]=true&columns[2][search][value]=&columns[2][search][regex]=false&columns[3][data]=3&columns[3][name]=&columns[3][searchable]=true&columns[3][orderable]=true&columns[3][search][value]=&columns[3][search][regex]=false&columns[4][data]=4&columns[4][name]=&columns[4][searchable]=true&columns[4][orderable]=true&columns[4][search][value]=&columns[4][search][regex]=false&columns[5][data]=5&columns[5][name]=&columns[5][searchable]=true&columns[5][orderable]=true&columns[5][search][value]=&columns[5][search][regex]=false&columns[6][data]=6&columns[6][name]=&columns[6][searchable]=true&columns[6][orderable]=true&columns[6][search][value]=&columns[6][search][regex]=false&columns[7][data]=7&columns[7][name]=&columns[7][searchable]=true&columns[7][orderable]=true&columns[7][search][value]=&columns[7][search][regex]=false&order[0][column]=0&order[0][dir]=asc&start=0&length=100&search[value]=&search[regex]=fals
I want to be able to send it as JSON, which seems like a much cleaner way to receive this data in the backend.
I don't know how it is sending data at the front end, so I can't use the solution that this question is supposed to be a duplicate of
To submit data as JSON string use the code below:
$("#my-table-id").DataTable( {
serverSide: true,
ajax: {
url: '/request/path/',
type: 'POST',
data: function (d) {
return JSON.stringify(d);
}
}
});
See ajax.data for more information.
Related
I am trying to show my JSON data in the table by using Data table. However, data table keep stuck in the processing like this and I don't know why.
https://jsfiddle.net/Lvmertbp/
JSON format
console.log(data)
Java controller code
#GetMapping(value="/projects")
public #ResponseBody List<Project> getProjects() {
return projectService.findAllProjects2();
}
I know this is the old question, but I have tried everything I can but it just don't work.
Try removing the success function, that seemed to work for me:
success:function(data){
console.log(data);
},
You should also check that your array is in the "data" object, if it's just a flat array you should pass an empty string to dataSrc. Working example: http://jsfiddle.net/5snrvL4m
Your server response is returning an array of result , not an object with data key array ,
So you data table will search in the result for a data array key , but not found , in your case you should specify the param dataSrc as empty , so it'll take it as ana array ,
Check here the doc
$(document).ready(function () {
$('#tableProject').DataTable({
processing: true,
serverSide: true,
ajax: {
url: "/projects",
type: "GET",
contentType: "application/json",
dataSrc: '', // <------------------------ here set empty string
data: function () {
},
success:function(data){
console.log(data);
},
},
paging:true,
columns: [
{data: "projectNumber"},
{data: "name"},
{data: "status"},
{data: "customerName"},
{data: "startDate"},
]
});
});
I used an ajax post request to send some variable from my javascript front end to my python back end. Once it was received by the back end, I want to modify these values and send them back to display on the front end. I need to do this all without refreshing the page.
With my existing code, returning the values to the front end gives me a 'null' or '[object object]' response instead of the actual string/json. I believe the formatting of the variables I'm passing is incorrect, but it's too complicated for me to understand what exactly I'm doing wrong or need to fix.
This is the javascript ajax POST request in my template. I would like the success fuction to display the new data using alert.
var arr = { City: 'Moscow', Age: 25 };
$.post({
headers: { "X-CSRFToken": '{{csrf_token}}' },
url: `http://www.joedelistraty.com/user/applications/1/normalize`,
data: {arr},
dataType: "json",
contentType : "application/json",
success: function(norm_data) {
var norm_data = norm_data.toString();
alert( norm_data );
}
});
This is my Django URLs code to receive the request:
path('applications/1/normalize', views.normalize, name="normalize")
This is the python view to retrieve the code and send it back to the javascript file:
from django.http import JsonResponse
def normalize(request,*argv,**kwargs):
norm_data = request.POST.get(*argv, 'true')
return JsonResponse(norm_data, safe = False)
You need to parse your Object to an actual json string. The .toString() will only print out the implementation of an objects toString() method, which is its string representation. By default an object does not print out its json format by just calling toString(). You might be looking for JSON.stringify(obj)
$.post({
headers: { "X-CSRFToken": '{{csrf_token}}' },
url: `http://www.joedelistraty.com/user/applications/1/normalize`,
data: {arr},
dataType: "json",
contentType : "application/json",
success: function(norm_data) {
var norm_data = JSON.stringify(norm_data);
alert( norm_data );
}});
I've observed that there's a difference between POST data being sent by a form and POST data being sent by this AJAX request. The data being sent through a form would be form-encoded whereas you are sending raw JSON data. Using request.body would solve the issue
from django.http import JsonResponse
def normalize(request):
data = request.body.decode('utf-8')
#data now is a string with all the the JSON data.
#data is like this now "arr%5BCity%5D=Moscow&arr%5BAge%5D=25"
data = data.split("&")
data = {item.split("%5D")[0].split("%5B")[1] : item.split("=")[1] for item in data}
#data is like this now "{'City': 'Moscow', 'Age': '25'}"
return JsonResponse(data, safe= False)
I'm trying to create a drag-and-drop table with save and load functionality. I'm using code from REDIPS.drag.
When using the REDIPS save function the table content is returned, client side, to the console and alert like this:
[["d2",2,2,"blue","A1"],["d1",4,5,"blue","A2"],["d3",3,2,"blue","A3"],["d4",1,4,"blue","A4"]].
I've tried a few different ways to POST the data to node and write it to file.
With this method:
script.js
$.ajax({
type: "POST",
url:"post6/json",
data: {table_content},
dataType:'json',
contentType: "application/x-www-form-urlencoded"
});
App.js
var testjson = req.body;
var tablestringify2 = JSON.stringify(testjson);
fs.writeFile('views/test.json', tablestringify2,'utf8', function (err) {
if (err) {
// append failed
} else {
// done
}
})
The data saved to file is:
{"table_content":"[[\"ns1.8b\",3,1,\"\",\"ns1.8b\"],[\"ns3.1\",4,2,\"\",\"ns3.1\"]]"}
With this method:
script.js
$.ajax({
type: "POST",
url:"post6/json",
data: table_content,
dataType:'json',
});
The data is saved to file as:
{"[":{"\"ns1.8b\",3,0,\"\",\"ns1.8b\"":{"\"ns3.1\",3,2,\"\",\"ns3.1\"":""}}}
When I use a GET, I parse the data which returns;
{ table_content: '[["ns1.8b",3,1,"","ns1.8b"],["ns3.1",5,3,"","ns3.1"]]' }
or
{[:{"ns1.8b",3,0,"","ns1.8b":{"ns3.1",3,2,"","ns3.1":""}}}
Either form cant be loaded back into the table using the REDIPS load function.
Is there any way I could get the data in the following format;
[["ns1.8b",3,0,"","ns1.8b"],["ns3.1",3,2,"","ns3.1"]]
...returned on the client side?
Or would it be possible to save it to file like that?
Perform the stringify at the client side:
$.ajax({
type: "POST",
url:"post6/json",
data: {table_content: JSON.stringify(table_content)},
dataType:'json',
});
At the server side you should be able to access req.body.table_content which will be the (JSON) string representation of the array.
I know that DataTables have the ajax.url() method for updating the data source URL, but I would like to know if there is a way I can change the function that is used to prepare the data to be POSTed on Ajax request. In the example below I would like to replace it with dataFunc.
The initialization part works fine.
function updateDataTable(dataFunc) {
// If DataTable initialised then update to correct function
if ($.fn.DataTable.isDataTable("#companyTable")) {
var companyTable = new $.fn.dataTable.Api("#companyTable");
companyTable.settings().ajax.data = dataFunc;
companyTable.ajax.reload();
} else {
$("#companyTable").DataTable({
bFilter: false,
processing: true,
serverSide: true,
ajax: {
url: "/api/GetCompanyRows",
type: "POST",
data: dataFunc
},
....
ajax can take a function where you can do all sorts of things, not the least of which is using localstorage. Check the documentation.
You can use ajax.data option to define a function that can be used to manipulate the data before it's sent to the server.
$('#companyTable').DataTable({
searching: false,
processing: true,
serverSide: true,
ajax: {
url: "/api/GetCompanyRows",
type: "POST",
data: function ( d ){
d.extra_search = $('#extra').val();
}
}
});
I found an alternative to Pro Hands solution, which allowed me to update the settings directly.
companyTable.settings()[0].ajax.data = dataFunc;
companyTable.ajax.reload();
I have written a simple code. In order to avoid flooding a JSON server, i want to break up the JSON response in pieces. So my jquery code should be parsing one variable ("page") to the php page that handles the JSON Oauth Request. On success, it should append the DIV with the latest responses.
My code should be working, except for the fact that my ajax post is not being received by my php file.
Here goes
archief.html
$("#klik").click(function() {
console.log("fire away");
page = page + 1;
$("#archief").load("trytocombinenewageandgettagsendates.php");
console.log(page);
$.ajax({
type: 'POST',
url: "trytocombinenewageandgettagsendates.php",
data: page,
success: function() {
console.log(page);
$.get("trytocombinenewageandgettagsendates.php", function(archief) {
$('#archief').append(archief);
});
},
error: function(err) {
alert(err.responseText);
}
});
return false;
});
The php file doesn't receive anything.
var_dump($_POST);
gives me array(0) { }.
Very strange, i'd really appreciate the help!
You are sending a string instead of key-value pairs. If you want to use $_POST you need to send key-value pairs:
...
$.ajax({
type: 'POST',
url: "trytocombinenewageandgettagsendates.php",
data: { 'page': page },
success: function() {
...
If you send a single value or string, you would need to read the raw input.
Also, you are sending 2 GET requests and 1 POST request to the same file. Is that intentional? Note that only the POST request will have the $_POST variable set.
Thank you for your help and not letting me post "this still doens't work" posts :)
I made the mistake of loading the "unConsulted" php file [$.get("trytocombinenewageandgettagsendates.php"] upon success. Instead, i append the response of the PHP.
The working code below:
$("#klik").click(function() {
console.log("fire away");
page = page + 1;
//$("#archief").load("trytocombinenewageandgettagsendates.php");
console.log(page);
$.ajax({
type: 'POST',
url: "trytocombinenewageandgettagsendates.php",
data: { 'page': page },
success: function(response){
$("#archief").append(response);
},
error: function(err) {
alert(err.responseText);
}
});
return false;