Datatables - add rows with PHP - javascript

I have an issue with jquery and datatables. I want to get the informations for the datatable from an mysql database with PHP and after that update the datatable with this informations.
I already tried it with something like this:
var datatable = $("#example").DataTable();
$.get('load_session_overview.php', function(newDataArray) {
//datatable.clear();
datatable.row.add(['Random','12','18','Menu']);
datatable.row.add([newDataArray]);
datatable.draw();
});
The first line with the add is working fine, but I don't know how to format the data in the php script correctly.
And if I'm getting more rows from the php script how can I add them all the the table?
Thanks, Phil

One way to format the data correctly in your PHP script is to return it in a JSON format. You can use the json_encode() function in PHP to convert your data into a JSON string.
For example:
<?php
$data = array(
array('Random','12','18','Menu'),
array('Data1','13','19','Menu2'),
array('Data2','14','20','Menu3')
);
echo json_encode($data);
?>
Then, in your jQuery code, you can use the JSON.parse() method to convert the JSON string into a JavaScript object, and loop through the data to add each row to the table.
$.get('load_session_overview.php',
function(newDataArray) {
var data = JSON.parse(newDataArray);
for(var i = 0; i < data.length; i++) {
datatable.row.add(data[i]);
}
datatable.draw();
});
Alternatively, you can use ajax call and pass the data to it to load it in the datatable and also you can use the ajax call to update the datatable as well.
$.ajax({
url: "load_session_overview.php",
type: "GET",
dataType: "json",
success: function (data) {
datatable.clear();
datatable.rows.add(data);
datatable.draw();
}
});
This way you can load the data in the datatable and also update it as well.

There are several ways to achieve this, for instance
php writes javascript code in an html script tag
see How to print JSON array inside script tag?
XHR request
see Displaying JSON data in HTML

Related

Is there a way to get create a php varialble from ajax data returned from another php script

I have a php script that creates a webpage with my select box options
Eg index.php has a html select box:
<select id="sel_option">
<option value="0">- Select Option -</option> ....
this is posted on sel_option change using ajax to a php processing script as below:
<script type="text/javascript">
$(document).ready(function(){
$("#sel_option").change(function(){
var optionid = $(this).val();
$.ajax({
url: 'procscript.php',
type: 'post',
data: {option:optionid},
dataType: 'json',
success:function(response){ ...
I would like to pull some of the returned array into Php variables again in order to change some of the tabulator group or format options
eg $("#table1").tabulator({
height:500 ,
VirtualDomHoz:true,
<? echo "groupBy:[\"group_option_from_response array\"]," ?>
So Php script1 sends option data by ajax -> php script2 which gathers data from a mysql db and returns to script1
I have tried creating session variables in php script 2 and it works on first selection , but after that it seems to cache the initial sessions in the browser , the response sessions from the second php script do not seem to copy over to the first script in subsequent calls. I think it might because the first page never reloads , all selections are done within the loaded first page using js??
If what I am trying to do is if not possible by php can I rewrite the php section in tabulator below using some js code?
$("#table1").tabulator({
height:500 ,
VirtualDomHoz:true,
<? echo "groupBy:[\"group_option_from_response array\"]," ?>
placeholder:"No Data Set",
columns:[
{title:"ID", field:"ID",width:30},
{title:"F_name", field:"f_name", sorter:"string"},
<? echo "{title:\"different var\", field:\"field2\", sorter:"string"},"; ?>
Thanks for looking !
Steve
Receive your data through ajax, then create the tabulator object. If there is data coming through ajax for that object, you can add it in, then instantiate it.
success:function(response){ ...
response = JSON.parse(response);
createTabulator(response,"table1")
});
function createTabulator(data, idToUse) {
var tabobject = {
height:500 ,
VirtualDomHoz:true,
placeholder:"No Data Set"
}
if (data.groupBy) {
tabobject.groupBy = [data.groupBy]
}
var cols = [
{title:"ID", field:"ID",width:30},
{title:"F_name", field:"f_name", sorter:"string"}
]
// if there is columns data coming in, bring it as an array...
data.columns.forEach(item => {
cols.push({title: item.title, field: item.field, sorter:"string"})
})
tabobject.columns = cols;
$("#"+idToUse).tabulator(tabobject);
}
There are so many ways to achieve what you want. I think the best way is just to push the variable to the ajax request.
$.ajax({
...
data: {
option:optionid,
groupoption: "groupoptionvalue"
}
...
});
The first time you just have to send it empty. PHP will always be able to handle the value since you will always capture it at the very beginning.
If your variable is an object or an array, just use JSON.parse/JSON.stringify in javascript and json_encode/json_decode in PHP for them to communicate.

How do I transfer the PHP variables to another javascript file?

So my goal is to use PHP to get data from a PostGreSQL database. I want to use this data in a separate javascript file so I can display it on the screen a certain way that I have my website configured. All the tutorials that I have seen online just puts a script tag inside the PHP file but I cannot do that because my website display javascript code is in the separate file. I just need the numbers to be in the javascript file that I got from the PHP file that got its data from the PostGreSQL database. How can I do this?
I just need help with the means to get to the ends because I have researched on my own but it is always not exactly what I want.
PHP:
<?php
$myPDO = new PDO('pgsql:host=myHost; dbname=myDBName', 'myUsername', 'myPassword');
?>
$result = $myPDO->query("SELECT * FROM table WHERE id = 'someID'");
Now I want to use this row's values in another javascript file. How can I do this?
You could use Ajax for this.
You could so something like this in your JS file:
$.ajax({
type: "GET",
url: 'FILENAME.php',
success: function(data){
alert(data);
}
});
and then in your FILENAME.PHP just return the values.
Your JS should then pull through whatever has been returned, in this case, your database query.
Your JS file needs to request the data from your PHP controller, via an AJAX request. You can then manipulate the returned data object whichever way you like.
We have mainly two methods to pass php value to javascript variable
Simple variable method at the time of first page load
<script>
var js_variable = <?php echo $data_php_variable; ?> ;
//this is working only at the first time of the page load
//you can also parse the data to any format
</script>
Use AJAX call to trigger a PHP request and manipulate return PHP value in JS
$.ajax({
type: "GET", //get or post method
url: 'FILENAME.php', //php request url
data :{}, //optional ,you can send data with request
success: function(res){
// this 'res' variable is the php return data in the form of js data
console.log(res);
}
});
ajax method is more dynamic ,it can use any time request handling
use the javascript ajax to call a php api
pass your data at php in your view file , use something like:
var phpData = JSON.parse("<?php echo json_encode($data)); ?>");

Access array posted with Javascript

I'm using the following code to send a form to a php processor:
$(document).ready(function(){
var $form = $('form');
$form.submit(function(){
$.post($(this).attr('action'), $(this).serialize(), function(response){
// do something here on success
},'json');
return false;
});
});
I presume that this sends the form to my php script with all the form values in json format but I then don't know how to then access this json and turn it back into the array i need to process in my PHP script.
Does anyone know how I access this variable in my processor script so I can process the data?
Also, what is the best way for me to view the data being posted so I can work out what to do with it, when I send the data the processor is obviously not displayed, is there a way to echo out/write the information received by the script to I can view it?
You can easily access to the json as an array called "$_POST" in your php.
for example, if you send the form as a json structured like this:
{
"name":"userID",
"psw":"password123"
}
in your php script there will be the variable $_POST with this structure:
$_POST = Array (
"name" => "userID",
"psw" => "password123"
)
EDIT
In a comment you asked me how to display the data received from the server,
that's quite simple,
in your php script just write this:
echo json_encode($_POST);
so that you output the $_POST array in the json format,
then in your script write this:
$.post($(this).attr('action'), $(this).serialize(),
function(data){ //"data" argument will contain the output from the server (that is the encoded $_POST array printed as json with the php code as showed above)
console.log(data); //log data
}
); //as you can see, I've deleted "json", becouse it's unuseful

Return JSON object from php script

I am making an AJAX GET request using jQuery to a PHP file. I want the PHP script to return a JSON object, however, currently it is returning a JSON string. I realise I can use JSON.parse in the jQuery code, however, any experience I have in making an AJAX call to an API a JSON object is returned. I am trying to do the same with the php script however, it is returning a string as opposed to an object.
Does anyone know what the best practice is here, and if the best practise is to return a JSON object how I would do this using PHP?
Please see the code below:
js
$.get('test.php', function(data){
console.log((data));
});
php
<?php
$jsonAnswer = array('test' => 'true');
echo json_encode($jsonAnswer);
In your PHP file, change the content type to application/json.
JS
$.get('/process.php', function(data) {
console.log(data);
} );
PHP
<?php
header( "Content-type: application/json" );
$jsonAnswer = array('test' => 'true');
echo json_encode($jsonAnswer);
Then your console should read Object {test: "true"} rather than just the JSON string.
Add json to the end of your get function to return json
$.get('test.php', function(data){
console.log((data));
},'json');//here
and/or add this header in php
header('Content-Type: application/json');
more info here
Without modifying PHP script you can do:
$.get( "test.php", function( data ) {
var arr = $.parseJSON(data);
console.log(arr);
alert(arr.test);
});

php encoded json to template and javascript

I'm using Codeigniter and Smarty (template engine) and therefore using templates.
I have a method that calls the template which has all html, css and js functions:
public function index()
{
//dashboard text
$this->data['title'] = 'Dashboard';
$this->data['subtitle'] = 'feeds, users, and more';
//load the donut graph data
$fbyg = $this->feed_model->countFeedsByGroups();
echo json_encode($fbyg);
//parses the dashboard template
$this->smartyci->display('dashboard.tpl', $this->data);
}
the thing is that I need to send some information to one of the js files bounded to my dashboard.tpl in order to render a graphic.
So I know I have to encode the php array into jSon object and send it to the template. But, how do I do this when I have not only to send and echo with the json but also I have to display my template sending for it other information?
The other question is, How do I receive the json and get the data? I'm trying and so far no results:
From my dashboard.tpl:
<script src="{site_url()}application/views/js/test.js"></script>
<script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js'></script>
From test.js:
$.getJSON('admin.php', function(data) {
console.log(data.vgro_name);
});
You could set it like
$this->data['fbyg'] = json_encode($fbyg);
And then in your javascript do
var yourVar = <?php echo $fbyg ?>;
A cleaner solution would be to make an ajax call to a function that will return something like
$fbyg = $this->feed_model->countFeedsByGroups();
echo json_encode($fbyg);
after the page has loaded.
Edit jQuery ajax get:
$.ajax({
type: "GET",
url: "urlToYourFunction",
success: function(data){
var yourVar = data;
}
});
I've only ever made get and post requests with angularjs and jquery, but here's another stackoverflow post detailing how to do it with regular javascript:
https://stackoverflow.com/a/18078705/3739551
I hope this helps!

Categories

Resources