Format data output using php - javascript

I have the following function which pulls data from the database :
public function get_dataset() {
$dataset = "";
$data_set = $this->operations_model->get_date();
foreach ($data_set as $value) {
$dataset .= '["' . $value['date'] . '","' . $value['revenue'] . '"],';
}
echo $dataset;
}
And return data in the following format :
["2015-10-13 15:53:20","15000.00"],["2015-10-13 15:53:20","5800.00"],["2015-10-13 15:53:20","5800.00"],["2015-10-13 15:53:20","5800.00"],["2015-10-13 15:54:56","15000.00"],
I would like to format the above data to be in the following format :
[[2015-10-13 15:53:20,15000.00],[2015-10-13 15:53:20,5800.00],[2015-10-13 15:53:20,5800.00],[2015-10-13 15:53:20,5800.00],[2015-10-13 15:54:56,15000.00]]

try this
public function get_dataset() {
$dataset = "[";
$data_set = $this->operations_model->get_date();
foreach ($data_set as $value) {
$dataset .= '["' . $value['date'] . '","' . $value['revenue'] . '"],';
}
$dataset = substr($dataset, 0, -1);
$dataset .= "]";
echo $dataset;
}

try:
public function get_dataset() {
$dataset = "";
$comma='';
$data_set = $this->operations_model->get_date();
foreach ($data_set as $value) {
$dataset .= $comma.'[' . $value['date'] . ',' . $value['revenue'] . ']';
$comma=',';
}
echo '['.$dataset.']';
}

Related

Adding DropDown list in jQuery DataTable

I want to display table's data with jQuery DataTable and sometimes apply an extra data filtering, using the output of a dropdown select input.
The main code for fetching data (fetch.php) is:
<?php
include('db.php');
include('function.php');
$query = '';
$output = array();
$query .= "SELECT * FROM Part_tb ";
if(isset($_POST["search"]["value"]))
{
$query .= 'WHERE part_manufacturer LIKE "%'.$_POST["search"]["value"].'%" ';
$query .= 'OR part_id LIKE "%'.$_POST["search"]["value"].'%" ';
}
if(isset($_POST["order"]))
{
$query .= 'ORDER BY '.$_POST['order']['0']['column'].' '.$_POST['order']['0']['dir'].' ';
}
else
{
$query .= 'ORDER BY part_id ASC ';
}
if($_POST["length"] != -1)
{
$query .= 'LIMIT ' . $_POST['start'] . ', ' . $_POST['length'];
}
$statement = $connection->prepare($query);
$statement->execute();
$result = $statement->fetchAll();
$data = array();
$filtered_rows = $statement->rowCount();
foreach($result as $row)
{
$sub_array = array();
$sub_array[] = $row["part_manufacturer"];
$sub_array[] = $row["part_id"];
$sub_array[] = $row["part_category"];
$sub_array[] = $row["part_stock"];
$data[] = $sub_array;
}
$output = array(
"draw" => intval($_POST["draw"]),
"recordsTotal" => $filtered_rows,
"recordsFiltered" => get_total_all_records(),
"data" => $data
);
echo json_encode($output);
?>
while the DataTable is defined in index.php as follows:
var dataTable = $('#user_data').DataTable({
"processing":true,
"serverSide":true,
"order":[],
"ajax":{
url:"actions/fetch.php",
type:"POST"
},
"columnDefs":[
{
"targets":[0, 1],
"orderable":false,
},
],
});
In index.php, i've created 3 dependent dropdown lists, which load data from other tables. Now, i want to take the id of 3rd dropdown list and update the data of Part_tb in fetch.php accordingly. Below, you can see that when 3rd dropdown change, i call a function load_parts():
$(document).on('change', '#sub3_category_item', function(){
load_parts();
});
function load_parts()
{
var action = 'fetch_data';
var filter_part_id = $('#sub2_category_item').val();
$.ajax({
url:"actions/fetch.php",
method:"post",
data:{action:action, filter_part_id:filter_part_id},
success:function(data)
{
$('#user_data').DataTable().ajax.reload();
}
});
}
The problem is that i can't filter the data of fetch.php according to the selected id of #sub2_category_item. Could you help me on that?
I've modified the index.php as follows:
$(document).on('change', '#sub3_category_item', function(){
var filter_part_id = $('#sub3_category_item').val();
$('#user_data').DataTable().destroy();
fill_datatable(filter_part_id);
});
fill_datatable();
function fill_datatable(filter_part_id = '')
{
var dataTable = $('#user_data').DataTable({
"processing":true,
"serverSide":true,
"order":[],
"searching" : false,
"ajax":{
url:"actions/fetch.php",
type:"POST",
data:{filter_part_id:filter_part_id}
}
});
and fetch.php:
$query .= "SELECT * FROM Part_tb ";
if(isset($_POST['filter_part_id']) && $_POST['filter_part_id'] != '')
{
$query .= "SELECT * FROM Part_tb WHERE part_id IN (SELECT pcfit_name from Part_car_fit_tb WHERE pcfit_id ='".$_POST["filter_part_id"]."') ";
}
but dataTable crashes, when #sub3_category_item is selected. Any idea, how to filter datatable with the value $_POST["filter_part_id"]?

jQuery DataTables column sorting on other column

My jQuery Datatable is not sorting properly in some columns. When I sort the GGC_ID column, it's sorting properly, but when I sort the CustomerID column, its not sorting. And when I sort the Customer Name column, the CustomerID column is the one that is sorting.
Here's my code:
record.js:
var tbl = $('#tbl').DataTable({
"processing": true,
"serverSide": true,
"order": [],
"searchable": true,
"columnDefs": [
{
"orderable": false,
"targets": [0,4]
}
],
"ajax": {
url: "fetch.php",
method: "POST"
}
});
fetch.php
$query = '';
$query .= "SELECT records.GGC_ID, company.Comp_Name, customer.CUST_ID, customer.CUST_NAME FROM records INNER JOIN company on company.Comp_ID = records.COMP_ID INNER JOIN customer ON customer.CUST_ID = records.CUST_ID ";
if(isset($_POST["search"]["value"]))
{
$query .= 'WHERE Comp_Name LIKE "%'.$_POST["search"]["value"].'%" ';
$query .= 'OR CUST_NAME LIKE "%'.$_POST["search"]["value"].'%" ';
$query .= 'OR GGC_ID LIKE "%'.$_POST["search"]["value"].'%" ';
}
if(isset($_POST["order"])) {
$query .= 'ORDER BY '.$_POST['order']['0']['column'].' '.$_POST['order']['0']['dir'].
' ';
} else {
$query .= "ORDER BY GGC_ID DESC ";
}
if($_POST["length"] != -1) {
$query .= 'LIMIT ' . $_POST['start'] . ', ' . $_POST['length'];
}
$stmt = $db->prepare($query);
$stmt->execute();
$result = $stmt->fetchAll();
$data = array();
$filtered_rows = $stmt->rowCount();
foreach ($result as $row) {
$sub_array = array();
$sub_array[] = $row["Comp_Name"];
$sub_array[] = $row["GGC_ID"];
$sub_array[] = $row["CUST_ID"];
$sub_array[] = $row["CUST_NAME"];
$sub_array[] = '<button type="button" name="update" id="'.$row["CUST_ID"].'"
class = "btn btn-default details" data-toggle="modal" data-target="#customer_modal">Details</button> ';
$data[] = $sub_array;
}
$output = array(
"draw" => intval($_POST["draw"]),
"recordsTotal" => $filtered_rows,
"recordsFiltered" => get_total_all_records(),
"data" => $data
);
echo json_encode($output);
$_REQUEST["order"][0][column] - does not have field name, it has index of field in columns
$index = $_REQUEST["order"][0][column];
ORDER BY $_REQUEST["columns"][ $index ]["name"]
You can open google console, network tab, find server request - header tab to see variables it sends.
Also
echo "<pre>";
print_r($_REQUEST);
echo "</pre>";
exit();
Your fixed code:
$index = $_POST['order']['0']['column'];
$field = $_POST["columns"][ $index ]["name"];
$query .= 'ORDER BY '.$field.' '.$_POST['order']['0']['dir'].
' ';
When you sort the Customer Name column, echo $query, check sql is right.

How to get equal columns?

I have this class for a megamenu used in a category menu for an ecommerce web application.
class categories {
var $categorie;
var $tabs;
var $subcategorie;
var $website;
var $coloane = 3;
var $randuri = 10;
function tabs(){
global $pdoconnect;
$stmt = $pdoconnect->query("SELECT * FROM taburi WHERE vizibil = '1' ORDER BY ordine ASC");
$tabs = $stmt->fetchAll(PDO::FETCH_ASSOC);
$tabs_c = $stmt->rowCount();
$return = "";
if($tabs_c > 0){
$i = 1;
$return .= "\n<ul class=\"tabs\">\n";
foreach($tabs as $t){
$return .= "\t<li class=\"level0\">\n";
$return .= "\t\t<div class=\"tab-title\">\n";
$return .= "\t\t\t<span class=\"tab-image\">\n";
$return .= "\t\t\t\t".'<img src="'.$this->website.'/media/taburi/'.$t['logo'].'" />'."\n";
$return .= "\t\t\t</span>\n";
$return .= $t['nume'];
$return .= "\t\t</div>\n";
$return .= "\t".'<div class="level1 hmm-megamenu-box">'."\n";
$return .= $this->categorie($t['id']);
$return .= "\t</div>\n";
$return .= "\t</li>\n";
}
$return .= "</ul>";
}
return $return;
}
function categorie($tab){
global $pdoconnect;
$return = "";
$stmt = $pdoconnect->prepare("SELECT * FROM categorii WHERE tab =:tab AND vizibil='1'");
$stmt->bindValue(':tab', $tab, PDO::PARAM_INT);
$stmt->execute();
$categorie = $stmt->fetchAll(PDO::FETCH_ASSOC);
$categorie_c = $stmt->rowCount();
if($categorie_c > 0){
$i = 0;
$return .= "<div class=\"hmm-megamenu-block\">\n";
foreach ($categorie as $cat) {
$return .= "\t<div class=\"hmm-megamenu-column\">\n";
// if($i % 2 == 0 && !empty($i) && $this->countSubcategorii($cat['categorie']) <= $this->randuri){
// $return .= "</div><div class=\"hmm-megamenu-column\">\n";
// }
$return .= "\t\t\t<a class=\"head-list\">".$cat['categorie']."<i class=\"fa fa-chevron-right\" style=\"font-size: 8px; margin-left: 5px;\"></i></a>\n";
$return .= $this->subcategorie($cat['categorie']);
$return .= "\t\t</div>\n";
$i++;
}
$return .= "</div>";
}
return $return;
}
function subcategorie($cat){
global $pdoconnect;
$return = "";
$stmt = $pdoconnect->prepare("SELECT * FROM categorii WHERE categorie=:categorie AND subcategorie IS NOT NULL");
$stmt->bindValue(':categorie', $cat, PDO::PARAM_STR);
$stmt->execute();
$subcategorie = $stmt->fetchAll(PDO::FETCH_ASSOC);
$subcategorie_c = $stmt->rowCount();
if($subcategorie_c > 0){
foreach ($subcategorie as $scat) {
$return .= "\t".''.$scat['subcategorie'].''."\n";
}
}
return $return;
}
}
For the moment the menu items looks like this
but the desired result should be
How can i get this result just with php?
I suspect the problem is two fold, in both style and HTML markup.
From a style perspective, your current layout is more or less a grid. You need something a lot more fluid within your CSS.
To allow this, you might need to pre-calculate columns so that you know you're evenly distributing X groups with a total of Y items into 3 columns. This lets you deal with cases where one group may have more items than can fit in the height of the menu (and need to overflow).
Solved
function categorie($tab){
global $pdoconnect;
$return = "";
$stmt = $pdoconnect->prepare("SELECT * FROM categorii WHERE tab =:tab AND vizibil='1'");
$stmt->bindValue(':tab', $tab, PDO::PARAM_INT);
$stmt->execute();
$categorie = $stmt->fetchAll(PDO::FETCH_ASSOC);
$categorie_c = $stmt->rowCount();
$return .= "<div class=\"hmm-megamenu-block\">\n";
if($categorie_c > 0){
$i = 1;
$return .= "\t<div class=\"hmm-megamenu-column\">\n";
foreach ($categorie as $cat) {
if($i % 3 == 0 && !empty($i) && $this->countSubcategorii($cat['categorie']) <= $this->randuri){
$return .= "</div><div class=\"hmm-megamenu-column\">\n";
}else if($i % 3 == 0 && !empty($i) && $this->countCategorii($tab) >= $this->coloane){
$return .= "</div><div class=\"hmm-megamenu-column\">\n";
}else if($i % 2== 0 && $this->countCategorii($tab) == 2){
$return .= "</div><div class=\"hmm-megamenu-column\">\n";
}
$return .= "\t\t\t<a class=\"head-list\">".$cat['categorie']."<i class=\"fa fa-chevron-right\" style=\"font-size: 8px; margin-left: 5px;\"></i></a>\n";
$return .= $this->subcategorie($cat['categorie']);
$i++;
}
$return .= "</div>";
}
$return .= "</div>";
return $return;
}

Read a JSON object with Javascript (Error)

I've writen this code but it doesn't work. I'm pretty sure it's mostly correct, but I don't know what's wrong with it. The script returns as output "undefined"
------PHP ON SERVER----------------- (http://www.autofficinacicco.it/json.php)
<?php
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
$conn = new mysqli($nomehost, $nomeuser, $password, "");
$result = $conn->query("SELECT codice, immagine, testo FROM Promozioni");
$outp = array();
while($rs = $result->fetch_array(MYSQLI_ASSOC))
{
$outp[]=$rs;
}
$conn->close();
echo json_encode($outp);
?>
-----JAVA SCRIPT----------------------------------------
<script>
var xmlhttp = new XMLHttpRequest();
var url = "http://www.autofficinacicco.it/json.php";
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
myFunction(xmlhttp.responseText);
}
}
xmlhttp.open("GET", url, true);
xmlhttp.send();
function myFunction(response) {
var arr = JSON.parse(response);
var i;
var out = "<table>";
for(i = 0; i < arr.length; i++) {
out+=arr["immagine"];
out+="</br>";
out+=arr["codice"];
out+="</br>";
out+=arr["testo"];
out+="</br>";
}
out += "</table>"
document.getElementById("id").innerHTML =out;
}
</script>
Your JSON is not proper document. Change json formating and use json_encode(); function
$outp = "[";
while($rs = $result->fetch_array(MYSQLI_ASSOC))
{
if ($outp != "[") {$outp .= ",";}
$outp .= '{"Codice":"' . $rs["codice"] . '",';
$outp .= '"Testo":"' . $rs["testo"] . '",';
$outp .= '"Immagine":"'. $rs["immagine"] . '"}';
}
$outp .="]";
$conn->close();
to
$outp = array();
while($rs = $result->fetch_array(MYSQLI_ASSOC))
{
$outp[] = $rs;
}
$conn->close();
echo json_encode($outp);

JQuery alerting when a select box is changed

Ok so all of the other functions I've done this same way have worked so far. This one for whatever reason will not work.I don't know if there is something I"m missing or if maybe a potential error in the code earlier could cause this. Here is my code:
jQuery("#teamTab_addPlayerForm").on('change', 'select#teamTab_suggestedPlayer', function(e) {
e.preventDefault();
alert('It Worked');
});
And here is the PHP file that calls it:
$output .= '<div id="ld_addPlayerFunction" style="clear:both; width:100%;"><h3>Add Player</h3>';
$standins = $wpdb->get_results('SELECT * FROM ' . $wpdb->prefix . 'kdc_user_sync ORDER BY computedMMR ASC');
$output .= '<form id="teamTab_addPlayerForm" action="" method="POST">
<select id="teamTab_suggestedPlayer" name="suggestedPlayer">
<option value="base">Suggested Player</option>';
foreach($standins as $standin){
$playerID = $wpdb->get_var('SELECT ID FROM ' . $wpdb->prefix . 'leagueDesigner_players WHERE userID = ' . $standin->userID);
$test = true;
if($playerID != ''){
$leagueTest = $wpdb->get_results('SELECT * FROM ' . $wpdb->prefix . 'leagueDesigner_league_players WHERE playerID = ' . $playerID);
foreach($leagueTest as $test){
if ($test->leagueID == $leagueID){
$test = false;
}
}
}
if($standin->computedMMR < ($suggestedMMR + 100) && $standin->computedMMR > ($suggestedMMR -100) && $test == true){
$output .= '<option value="' . $standin->userID . '">' . substr($standin->profileName, 0, 20) . ' - ' . $standin->computedMMR . ' MMR</option>';
}
}
$output .= '</select><br />';
$output .= '</form>';
The output is then echoed later in the script. So one user has told me to use document instead of #teamTab_addPlayerForm and it works, but I'm wondering why this previous code worked fine and that one didn't:
jQuery("#teamTab_teamListForm").on('change', 'select#teamTab_teamSelect', function (e) {
e.preventDefault();
jQuery(this).attr('disabled', true);
var teamID = jQuery(this).val();
jQuery('select#teamTab_leagueSelect').attr('disabled', true);
var leagueID = jQuery('select#teamTab_leagueSelect').val();
data = { action: "leagueDesignerTeamsTabLoadTeamPlayers", leagueID: leagueID, teamID: teamID };
jQuery.ajax({
type: 'POST', url: ajaxurl, data: data, dataType: 'html', success: function(response) {
if (response == "error") {
jQuery('select#teamTab_teamSelect').attr('disabled', false);
alert('There was an error processing your request');
}
else {
jQuery('select#teamTab_teamSelect').attr('disabled', false);
jQuery('select#teamTab_leagueSelect').attr('disabled', false);
jQuery('.ld_teamEdit').remove();
jQuery('#ld_addPlayerFunction').remove();
jQuery('div#ld_teamTabTeamInfo').remove();
jQuery('#teamTab_teamListForm').after(response);
}
}});
});
That was the code that is dealing with select boxes in the same way. And here is the PHP code:
function leagueDesignerTeamsTabLoadLeagueTeams () {
global $wpdb;
$leagueID = $_POST['leagueID']; //Pull the POST'd leagueID
$output = '<select id="teamTab_teamSelect" name="team"><option value="">Choose a Team</option>'; //Output...
$errors = 0; //Error checking...
$teams = $wpdb->get_results('SELECT * FROM ' . $wpdb->prefix . 'leagueDesigner_teams WHERE leagueID = ' . $leagueID);
foreach($teams as $team){
$output .= '<option value="' . $team->teamID . '"';
if ($_POST['team'] == $team->teamID){
$output .= ' selected';
}
$output .= '>' . $team->teamID . '. ' . $team->teamName . '</option>';
}
if (!$teams) {
$errors++;
}
$output .= '</select>';
if ($errors == 0) { echo $output; } else { echo 'error'; }
die(); // this is required to return a proper result
}
The element is created after page load so you need to bind it to an already existing element (see below)
$(document).on('change', '.class-name', function () {
//Commands to run on change
});

Categories