Passing auxiliary data from server to client?
Passing auxiliary data from server to client?
sjordan
Posts: 36Questions: 10Answers: 0
In PHP and JS mixed environments, it's pretty common to see server data passed to the client JS view interpolation (see 'some_server_data' below in the first line of the sample below)
Then that value might be used later in Editor.
While this works, it feels messy and I have to assume there's a recommended way to add this auxiliary data to the payload received by DT on load.
What's the recommended API?
<script>
// some magic computed server data that is not user specific, not computed from user data.
const some_server_data = <?= $some_server_data ?>
$(document).ready(function () {
const editor = new $.fn.dataTable.Editor({
url: "./data/users.json",
table: "#attendance",
fields: [
{
label: "First name:",
name: "users.first_name",
},
{
label: "Last name:",
name: "users.last_name",
def: some_server_data
},
{
label: "Phone #:",
name: "users.phone",
},
{
label: "Site:",
name: "users.site",
type: "select",
},
{
label: "Color:",
name: "users.color",
type: "select",
},
],
table: "#users",
});
...
});
</script>
This question has accepted answers - jump to:
Answers
One option is to add the auxiliary data to the JSON response from the Datatables
ajax
request. You can define thefields.def
option as a function and in the function useajax.json()
to get the JSON response to fetch the auxiliary data.Kevin
Kevin, if I understand you, this seems a little heavy-handed and results in at least 2 ajax calls.
The first call happens on page load when the data is fetched to populate DT. Then, if I read you correctly, a second call would be made to get the default value of the field in question.
It would seem to me there would be a recommended API to add aux data to the initial load and the developer could use that data as needed.
Some like the following pseudocode:
Then the question is what is DT's and/or Editor's recommended way to grab my_aux_data.import_global_var while respecting the library's API?
Use
xhr
. It passes the JSON object that was loaded to the event handler so you can do whever you want with it.Also there is
ajax.json()
to get the loaded JSON object, at whatever point you need it in your script.Allan
No just one ajax request. When datatables loads the table data via
ajax
the server script can add additional data objects to the response. Depeneding on how you want to use the auxiliary data.you can do as Allan suggested and access it in thexhr
event. Or you can useajax.json()
to fetch the auxiliary data. This is from theajax.json()
docs:Kevin
For example the JSON response would look something like this:
Kevin