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.
Related
I have a form, running through jquery validation which then submits via ajax to a PHP script to handle backend functions. Ajax collects form values through serializeArray() and looks to do the job. Script fires and data is sent through(I think) to PHP. I've tried probably close to 100 combinations to receive the data at the PHP side but with no luck. I'm convinced this must be simple, something I've overlooked. Code for the ajax is below, along with a screenshot of developer tools showing what's being sent.
No matter what I try on the PHP side, I either get an empty array, NULL through $_POST/$_GET. I've tried json_decode, parsing the string, var_dump etc.
var data=$(form).serializeArray();
$.ajax({
cache: false,
type: "POST",
dataType: "JSON",
url: "process/create_site.php",
data: data,
success: function(response) {
console.log(response);
//$(form).html("<div id='message'></div>");
//$('#message').html("<h2>Your request is on the way!</h2>")
// .append("<p>someone</p>")
// .hide()
// .fadeIn(1500, function() {
// $('#message').append("<img id='checkmark' src='images/ok.png' />");
// });
}
});
I managed to get to the bottom of this, after an embarrassing amount of time. I'd like to post the simple reason here to help others.
The entire JS block was wrapped in $(document).ready(function(){
which was causing the values to be stripped when posting to the PHP.
I can't find any documentation or answer to a question with a similar scenario - so here it is!
I'm working on a ASP.NET MVC project that uses some jQuery on the client side. I have a jQuery call like this, which works correctly:
$.post($('form').attr("action"), $('form').serialize(), function(data){
// Deal with the data that came back from the ASP.NET MVC controller
}
I want to do the exact same call, except I also want to send in a custom header. I am able to successfully create and send a custom header like this:
var token = $('input[name="__RequestVerificationToken"]').val();
var headers = {};
headers['__RequestVerificationToken'] = token;
$.ajax({
url: "/report_observation/" + submitType,
cache: false,
type: "POST",
data: {
'viewModel': $('form').serialize(),
},
headers: headers,
success: function (data) {
// Deal with the data that came back from the ASP.NET MVC controller
},
error: function (response) {
alert("Error: " + response);
}
});
There are two problems with this second bit of code. One is that I have to make a custom url to go to the correct controller, and I don't know of a way to simply use $('form').attr("action") to automatically go to the correct place.
The second -- and bigger -- problem is that I'm not able to pass over the form data with $('form').serialize() as I could in the one liner $.post example. Doing a #Html.Raw(Json.Encode(Model)) in my Razor cshtml file doesn't send over the model for the whole form, presumably because this code is within a partial view that doesn't know the state of the models in the other partial views that make up this form.
Anyway, I'm thinking there must be an easy way to take this code...
var token = $('input[name="__RequestVerificationToken"]').val();
var headers = {};
headers['__RequestVerificationToken'] = token;
...and incorporate the headers property into this bit of code:
$.post($('form').attr("action"), $('form').serialize(), function(data){
// Deal with the data that came back from the ASP.NET MVC controller
}
However, I can't figure out the correct syntax. Any ideas?
OK, I figured it out. The second example can indeed work if the data field looks like this:
data: $("form").serialize(),
In other words, I had to NOT assign it to the viewModel parameter.
yes, for the second problem use that dev5000 says, and, for the URL, simply get the value for the attribute action fo the form and use it:
var url = $("from").attr("action");
$.ajax({
url: url,
...
})
I have a php file with a lot of checkboxes on the left hand side. I extract the values via javscript and pass them into an array. Which works just fine. I would like to pass then this array via Ajax to PHP in order to mess around with the values and create SQL-statements out of them.
$(document).ready(function(e) {
$('#getSelectedValues').click(function() {
var chkBoxArray = [];
$('.graphselectors:checked').each(function() {
chkBoxArray.push($(this).val());
});
for (var i = 0; i < chkBoxArray.length; i++) {
console.log(i + " = " + chkBoxArray[i]);
}
$.ajax({
url: 'index.php', // (1)
type: 'POST',
dataType:'json',
data: chkBoxArray, //(2)
success: function(data){
console.log(data.length);
console.log(data);
}
});
});
});
Several questions:
(1) what file name do I need to add here? The origion or the target?
(2) I have numerous ways of this: serialization, with these brackets {}, and so on. How to get it done right?
An error that I get is the following:
Notice: Undefined index: data in graph.php
That makes me wondering a bit, because it clearly shows no data is being send.
var_dumps on $_POST and $_SERVER offer these results:
array(0) { }
array(0) { }
which is somewhat unsatisfying.
Where am I doing things wrong? The only puzzling aspect is the ajax, all other stuff is not much of an issue.
The site is supposed to work in the following way:
Page -> Checkbox(clicked) -> Button -> result (ajax) -> PHP fetches result -> SQL DB -> PHP gets DB result -> fetch result (ajax) -> jslibrary uses result for something.
1- You need to point your ajax to the script that will use the data you are sending. I would not recommend to point to index.php, since you'll need to add a if statement checking if there is data on $_POST that is exactly what your're expecting, otherwise it will return the same page that you're in (considering that you are in index.php and is making a request to index.php). A point to consider. Since it is a whole request and it's not a method call to actually return something to your page you need to echo things. That said, consider also to set header('Content-Type: application/json') then, since you're expecting dataType: 'json', echo json_encode($objectorarray);
2- Since you're sending a Javascript array to PHP, it can't interpret correctly the structure, that is why you should use JSON.stringify(chkBoxArray) before sending it. But just setting it on data attribute would send the number of checkboxes you selected as values to POST, so consider to data: {myCheckboxValues: JSON.stringify(chkBoxArray)}
In your PHP script, considering all the security measures to take, you can $foo = json_decode($_POST['myCheckboxValues']);
Well, of course you need to pass the target page as url in your ajax call. It can't guess which file should process the data.
As for the data property. You need to give your data a name.
data: {
something: "something"
}
Becomes: $_POST['something']. (value: something)
$.ajax({
url: 'target.php', // (1)
type: 'POST',
dataType:'json',
data: { data: chkBoxArray }, //(2) Now $_POST['data'] will work
success: function(data){
console.log(data.length);
console.log(data);
}
});
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.
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());
}