I have set up a jqgrid and it loads the data via php. No results are displayed
The grid is set up with
$(document).ready(function () {
$("#list_records").jqGrid({
url: "grid.php",
datatype: "json",
mtype: "GET",
colNames: ["ID", "Encuesta", "Fecha", "Quien","Opciones"],
colModel: [
{ name: "id_consulta"},
{ name: "texto"},
{ name: "fecha"},
{ name: "quien"},
{name:'act',index:'act', width:130,sortable:false,formatter:myFormatter, search:false}
],
pager: "#perpage",
rowNum: 8,
rowList: [10,20],
sortname: "id_consulta",
sortorder: "asc",
height: 'auto',
viewrecords: true,
gridview: true,
caption: ""
});
$('#list_records').jqGrid('filterToolbar', {stringResult: true, searchOnEnter: false, defaultSearch : "bw"});
});
function myFormatter (cellvalue, options, rowObject)
{
var idconsulta = rowObject[0];
return "</a><input type=button value='Enviar' onclick=\"loadingForm(" + idconsulta + ");\" />";
}
And the corrsponding json output from the php files is
{"page":1,"total":2,"records":"18","rows":[{"id":"18","cell":["18","Camila quieres participar? ","2015-03-02","dwk"]},{"id":"17","cell":["17","Halo concepci\u00f3n wie gehts ","2015-03-02","idkl"]},{"id":"16","cell":["16","\u00bfAlguien quiere participar?","2015-03-02","dwk"]},{"id":"15","cell":["15","\u00bfEs \u00fatil una aplicaci\u00f3n para realizar encuestas instant\u00e1neas? ","2015-03-02","idkl"]},{"id":"14","cell":["14","Camila quieres participar? ","2015-03-02","idkl"]},{"id":"13","cell":["13","Halo concepci\u00f3n wie gehts ","2015-03-02","idkl"]},{"id":"12","cell":["12","\u00bfAlguien quiere participar?","2015-03-02","dwk"]},{"id":"11","cell":["11","\u00bfEs \u00fatil una aplicaci\u00f3n para realizar encuestas instant\u00e1neas? ","2015-03-02","idkl"]},{"id":"10","cell":["10","Halo concepci\u00f3n wie gehts ","2015-03-02","dwk"]},{"id":"9","cell":["9","\u00bfAlguien quiere participar?","2015-03-02","idkl"]}]}
if I remove
$responce->page = $page;
$responce->total = $total_pages;
$responce->records = $count;
I get results displayed but can not use pagination
i found a solution that works for me so to set up a jqgrid via php mysql with filtering via toolbar and paging i used the following
$(document).ready(function () {
jQuery('#rowed2').jqGrid({
url:'server.php',
datatype: 'json',
colNames:['ID','ENCUESTA', 'FECHA', 'QUIEN','ACTIONS'],
colModel:[
{ name: 'id_consulta',width:30,search:false,sortable:false},
{ name: 'texto', width:250},
{ name: 'fecha', width:65},
{ name: 'quien', width:100},
{name:'act',index:'act', width:100,sortable:false,formatter:myFormatter, search:false}
],
rowNum:10,
rowList:[10,20,30],
pager: '#prowed2',
sortname: 'ID',
viewrecords: true,
height: '400',
width: '600',
sortorder: 'asc'
});
$('#rowed2').jqGrid('filterToolbar', {stringResult: true, searchOnEnter: false, defaultSearch : "bw"});
});
function myFormatter (cellvalue, options, rowObject)
{
var idconsulta = rowObject[0];
return "</a><input type=button value='Ver Resultado' onclick=\"loadingForm(" + idconsulta + ");\" />";
}
the php file used is the following
<?php
error_reporting(0);
ini_set('max_execution_time', 600);
require_once 'cliente/config.php';
$db = mysql_connect($server,$user,$pass);
mysql_select_db($dbname,$db);
$page = $_GET['page']; // get the requested page
$limit = $_GET['rows']; // get how many rows we want to have into the grid
$sidx = $_GET['sidx']; // get index row - i.e. user click to sort
$sord = $_GET['sord']; // get the direction
if(!$sidx) $sidx =1; // connect to the database
$filterResultsJSON = json_decode($_GET['filters']);
$counter = 0;
$sql='';
if($filterResultsJSON != "") {
$filterArray = get_object_vars($filterResultsJSON);
while($counter < count($filterArray['rules']))
{
$filterRules = get_object_vars($filterArray['rules'][$counter]);
if($counter == 0){
$sql .= ' WHERE ' . $filterRules['field'] . ' LIKE "%' . $filterRules['data'] . '%"';
}
else {
$sql .= ' AND ' . $filterRules['field'] . ' LIKE "%' . $filterRules['data'] . '%"';
}
$counter++;
}
}
$result = mysql_query("SELECT COUNT(*) AS count FROM consulta $sql");
$row = mysql_fetch_array($result,MYSQL_ASSOC);
$count = $row['count'];
if( $count >0 ) {
$total_pages = ceil($count/$limit);
} else {
$total_pages = 0;
}
if ($page > $total_pages) $page=$total_pages;
if ($limit<0) $limit = 0;
$start = $limit*$page - $limit; // do not put $limit*($page - 1)
if ($start<0) $start = 0;
$SQL2 = "SELECT * from consulta $sql ORDER BY id_consulta desc LIMIT $start , $limit";
$result = mysql_query( $SQL2 ) or die("Couldn?t execute query.".mysql_error());
$responce->page = $page;
$responce->total = $total_pages;
$responce->records = $count;
$i=0;
while($row = mysql_fetch_array($result,MYSQL_ASSOC)) {
$responce->rows[$i]['id']=$row[id_consulta];
$responce->rows[$i]['cell']=array($row['id_consulta'],utf8_encode($row['texto']),$row[fecha],$row[quien],""); $i++;
}
echo json_encode($responce);
?>
Related
Im trying to add external link to "customer_id" link example has to be like this /edit-customer.php?customer_id=$customer_id(which is link to original customer id) I am creating big detail page most informations its not in the table
I want to add '$' and money format has to be $ 1,250.00. this my code
<script>
$(document).ready(function() {
var dataTable = $('#customer_table').DataTable({
"processing": true,
"serverSide": true,
"order": [],
"ajax": {
url: "serverside/ajax-users.php",
type: "POST"
}
});
$('#customer_table').on('draw.dt', function() {
$('#customer_table').Tabledit({
url: 'serverside/action.php',
dataType: 'json',
columns: {
identifier: [0, 'customer_id'],
editable: [
[1, 'customer_store', '{"1":"B2C","2":"B2B"}'],
[2, 'customer_name'],
[3, 'customer_address'],
[4, 'customer_phone'],
[5, 'customer_email'],
[6, 'customer_status', '{"1":"Inactive","2":"Active"}']
]
},
restoreButton: false,
onSuccess: function(data, textStatus, jqXHR) {
if (data.action == 'delete') {
$('#' + data.customer_id).remove();
$('#customer_table').DataTable().ajax.reload();
}
}
});
});
}); <
/script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.datatables.net/1.10.22/js/jquery.dataTables.min.js"></script>
<table id="customer_table" class="display nowrap form-inline" cellspacing="0" width="100%">
<thead>
<tr>
<th>ID</th>
<th>Store ID</th>
<th>Name</th>
<th>Address</th>
<th>Phone</th>
<th>Email</th>
<th>Status</th>
<th>Signing Date</th>
<th>Orders</th>
<th>Total Sales</th>
<th>Detail</th>
</tr>
</thead>
<tbody></tbody>
</table>
//AJAX-USER.PHP
<?php
link db
$column = array("customer_id", "customer_store", "customer_name", "customer_address", "customer_phone", "customer_email", "customer_status", "customer_date", "customer_order", "customer_sale");
$query = "SELECT * FROM customers ";
if(isset($_POST["search"]["value"]))
{
$query .= '
WHERE customer_id LIKE "%'.$_POST["search"]["value"].'%"
OR customer_name LIKE "%'.$_POST["search"]["value"].'%"
OR customer_store LIKE "%'.$_POST["search"]["value"].'%"
OR customer_address LIKE "%'.$_POST["search"]["value"].'%"
OR customer_phone LIKE "%'.$_POST["search"]["value"].'%"
OR customer_email LIKE "%'.$_POST["search"]["value"].'%"
OR customer_sale LIKE "%'.$_POST["search"]["value"].'%"
OR customer_status LIKE "%'.$_POST["search"]["value"].'%"
';
}
if(isset($_POST["order"]))
{
$query .= 'ORDER BY '.$column[$_POST['order']['0']['column']].' '.$_POST['order']['0']['dir'].' ';
}
else
{
$query .= 'ORDER BY customer_date DESC ';
}
$query1 = '';
if($_POST["length"] != -1)
{
$query1 = 'LIMIT ' . $_POST['start'] . ', ' . $_POST['length'];
}
$statement = $connect->prepare($query);
$statement->execute();
$number_filter_row = $statement->rowCount();
$statement = $connect->prepare($query . $query1);
$statement->execute();
$result = $statement->fetchAll();
$data = array();
foreach($result as $row)
{
$sub_array = array();
$sub_array[] = $row['customer_id'];
$sub_array[] = $row['customer_store'];
$sub_array[] = $row['customer_name'];
$sub_array[] = $row['customer_address'];
$sub_array[] = $row['customer_phone'];
$sub_array[] = $row['customer_email'];
$sub_array[] = $row['customer_status'];
$sub_array[] = $row['customer_date'];
$sub_array[] = $row['customer_order'];
$sub_array[] = $row['customer_sale'];
$sub_array[] = $row['customer_detail'];
$data[] = $sub_array;
}
function count_all_data($connect)
{
$query = "SELECT * FROM customers";
$statement = $connect->prepare($query);
$statement->execute();
return $statement->rowCount();
}
$output = array(
'draw' => intval($_POST['draw']),
'recordsTotal' => count_all_data($connect),
'recordsFiltered' => $number_filter_row,
'data' => $data
);
echo json_encode($output);
?>
//ACTION.PHP
<?php
if ($_POST['action']== 'edit') {
$data = array(
':customer_store' => $_POST['customer_store'],
':customer_name' => $_POST['customer_name'],
':customer_address' => $_POST['customer_address'],
':customer_phone' => $_POST['customer_phone'],
':customer_email' => $_POST['customer_email'],
':customer_status' => $_POST['customer_status'],
':customer_id' => $_POST['customer_id']
);
$query = "
UPDATE customers
SET customer_store = :customer_store,
customer_name = :customer_name,
customer_address = :customer_address,
customer_phone = :customer_phone,
customer_email = :customer_email,
customer_status = :customer_status
WHERE customer_id = :customer_id
";
$statement = $connect->prepare($query);
$statement->execute($data);
echo json_encode($_POST);
}
if ($_POST['action'] == 'delete')
{
$query = "
DELETE FROM customers
WHERE customer_id = '".$_POST["customer_id"]."'
";
$statement = $connect->prepare($query);
$statement->execute();
echo json_encode($_POST);
}
?>
My all information here, thank you for your help.
if you need! adding hyperlinks to table column .
I add this code under type:POST in script section
i have 9 table head. i added 1 more 'th' end of the line.
"columnDefs": [ {
"targets": 10,
"data": 0,
"render": function ( data, type, row, meta ) {
return '<center><button class="btn btn-light btn-sm">Detail</button></center>';
}
}]
targets 10 last 'th' ----
data 0 is customer_id.
I´m using the jquery based table plugin "datatables" and I´m trying to implement an ajax based "range search" between two numbers ("start-date" and "end_date"). These entered values should be used for a query in the MySQL column "order_id".
On the server-sided script (fetch.php) I catch the both values like that.
if(isset($_POST['start_date'], $_POST['end_date'])) {
$query .= 'order_id BETWEEN "'.$_POST["start_date"].'" AND "'.$_POST["end_date"].'" AND ';
}
The problem is I can´t see any errors in the console, but after using the number range search no results are displayed.
The "category select menus" (category and category2) are working as expected.
I´ve setted up a test site, maybe you can help me to find the error: Testsite
This is my script:
$(document).ready(function () {
var category = "";
var category2 = "";
var start_date = "";
var end_date = "";
load_data();
function load_data(is_category, is_category2, start_date, end_date) {
console.log(is_category, is_category2, start_date, end_date);
var dataTable = $('#product_data').DataTable({
"processing": true,
"serverSide": true,
"order": [],
"ajax": {
url: "fetch.php",
type: "POST",
data: {
is_category: is_category,
is_category2: is_category2,
start_date: start_date,
end_date: end_date
},
}
});
}
// Number Range Search
$('#search').click(function () {
console.log($(this).attr('id'), start_date, end_date)
var start_date = $('#start_date').val();
var end_date = $('#end_date').val();
if (start_date != '' && end_date != '') {
$('#product_data').DataTable().destroy();
load_data('','',start_date, end_date);
}
else {
alert("Both Date is Required");
}
});
// Select Menu id="category"
$(document).on('change', '#category, #category2', function () {
//console.log($(this).attr('id'), category, category2)
if ($(this).attr('id') === "category") {
category = $(this).val();
} else if ($(this).attr('id') === "category2") {
category2 = $(this).val();
}
//
$('#product_data').DataTable().destroy();
if (category != '') {
load_data(category, category2);
}
else {
load_data();
}
});
// Select Menu id="category2"
$(document).on('change', '#category2', function () {
var category2 = $(this).val();
$('#product_data').DataTable().destroy();
if (category2 != '') {
load_data(category, category2);
}
else {
load_data();
}
});
});
fetch.php
//fetch.php
$connect = mysqli_connect("localhost", "xxxxx", "xxxxx", "xxxxx");
$columns = array('order_id', 'order_customer_name', 'order_item', 'order_value', 'order_date');
$query = "SELECT * FROM tbl_order WHERE ";
if(isset($_POST['start_date'], $_POST['end_date']))
{
$query .= 'order_id BETWEEN "'.$_POST["start_date"].'" AND "'.$_POST["end_date"].'" AND ';
}
if(isset($_POST["is_category"]))
{
$query .= "order_item = '".$_POST["is_category"]."' OR ";
}
if(isset($_POST["is_category2"]))
{
$query .= "order_customer_name = '".$_POST["is_category2"]."' AND ";
}
if(isset($_POST["search"]["value"]))
{
$query .= '
(order_id LIKE "%'.$_POST["search"]["value"].'%"
OR order_customer_name LIKE "%'.$_POST["search"]["value"].'%"
OR order_item LIKE "%'.$_POST["search"]["value"].'%"
OR order_value LIKE "%'.$_POST["search"]["value"].'%")
';
}
if(isset($_POST["order"]))
{
$query .= 'ORDER BY '.$columns[$_POST['order']['0']['column']].' '.$_POST['order']['0']['dir'].'
';
}
else
{
$query .= 'ORDER BY order_id DESC ';
}
$query1 = '';
if($_POST["length"] != -1)
{
$query1 = 'LIMIT ' . $_POST['start'] . ', ' . $_POST['length'];
}
$number_filter_row = mysqli_num_rows(mysqli_query($connect, $query));
$result = mysqli_query($connect, $query . $query1);
$data = array();
while($row = mysqli_fetch_array($result))
{
$sub_array = array();
$sub_array[] = $row["order_id"];
$sub_array[] = $row["order_customer_name"];
$sub_array[] = $row["order_item"];
$sub_array[] = $row["order_value"];
$sub_array[] = $row["order_date"];
$data[] = $sub_array;
}
function get_all_data($connect)
{
$query = "SELECT * FROM tbl_order";
$result = mysqli_query($connect, $query);
return mysqli_num_rows($result);
}
$output = array(
"draw" => intval($_POST["draw"]),
"recordsTotal" => get_all_data($connect),
"recordsFiltered" => $number_filter_row,
"data" => $data
);
echo json_encode($output);
Thats because the is_category and is_category2 are returning 0. You have probably an if statement on your php like if $_POST[is_category] but you also need to do the same in case there is no category selected. Please share the full php to help you out
on your click function replace load_data(start_date, end_date); with load_data('','',start_date, end_date);
I'm new to js and datables and I'm having a difficulty making single column search into multiple column search. Here's my code:
var dataTable = $('#product_data').DataTable({
"processing":true,
"serverSide":true,
"order":[],
"ajax":{
url:"fetch.php",
type:"POST",
},
"columnDefs":[
{
"targets":[0,5,7],
"orderable":false,
},
],
});
function load_data(is_suppliers)
{
var dataTable = $('#product_data').DataTable({
"processing":true,
"serverSide":true,
"order":[],
"ajax":{
url:"fetch.php",
type:"POST",
data:{is_suppliers:is_suppliers}
},
"columnDefs":[
{
"targets":[0,5,7],
"orderable":false,
},
],
});
}
$(document).on('change', '#supplier_filter', function(){
var supplier = $(this).val();
$('#product_data').DataTable().destroy();
if(supplier != '')
{
load_data(supplier);
}
else
{
load_data();
}
});
And the query i used was:
$query = "
SELECT * FROM products
INNER JOIN suppliers
ON suppliers.supplierid = products.supplier
";
$query .= " WHERE ";
if(isset($_POST["is_suppliers"]))
{
$query .= "products.supplier = '".$_POST["is_suppliers"]."' AND ";
}
if(isset($_POST['search']['value']))
{
$query .= '
(productname LIKE "%'.$_POST['search']['value'].'%"
OR category LIKE "%'.$_POST['search']['value'].'%")
';
}
if(isset($_POST['order']))
{
$query .= 'ORDER BY '.$column[$_POST['order']['0']['column']].' '.$_POST['order']['0']['dir'].' ';
}
else
{
$query .= 'ORDER BY productid DESC ';
}
$query1 = '';
if($_POST['length'] != -1)
{
$query1 = 'LIMIT ' . $_POST['start'] . ', ' . $_POST['length'];
}
(Edited- added full query except execute and fetch part)I've tried replicating the functions and replacing the values with the column i want and i also added another if(isset) to the query but only one column search will work and the others will show no matching records.
function delete_user(email)
{
//if(confirm("Do you want to remove this user with mail id: "+email))
//{
var z = {email : email}
console.log(z)
$.ajax({
url: "delete_user.php",
type: 'POST',
data: z,
success: function (data) {
console.log(data);
return false;
var i=0;
var element = "<table style='border-collapse: collapse;'>"
while(data[i] != null)
{
element = element + "<tr style='height:15px' onmouseover='rowbig(this)' onmouseout='rowsmall(this)'><td>"+data[i].fname+" "+data[i].lname+"</td><td>"+data[i].email+"</td><td>"+data[i].dob+"</td><td><button onclick='delete_user(\""+data[i].email+"\")'><img src='delete.png' style='height:20px;width:20px'/></button></td></tr>";
i++;
}
element = element + "</table>";
$("#response").html( element );
},
cache: false,
contentType: false,
processData: false
});
//}
}
<?php
header("Content-Type:application/json");
$email ="";
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
function deliver_res($status_message,$result)
{
header("$status_message");
$response['status_message']=$status_message;
$response['result']=$result;
$json_response=json_encode ($response);
echo $json_response;
}
$servername = 'localhost';
$username = 'root';
$password = '';
$dbname = 'webdata';
$conn = mysqli_connect($servername, $username, $password, $dbname);
if(isset($_POST['email']))
{
$email = test_input($_POST["email"]);
}
else
{
deliver_res("name not received","false");
exit();
}
$sqll="DELETE FROM admindata WHERE email='".$email."';";
$result = mysqli_query($conn,$sqll);
$return_arr = array();
$sqll="SELECT * FROM admindata ORDER BY id DESC ;";
$result = mysqli_query($conn,$sqll);
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC))
{
$row_array['fname'] = $row['fname'];
$row_array['lname'] = $row['lname'];
$row_array['email'] = $row['email'];
$row_array['dob'] = $row['dob'];
array_push($return_arr,$row_array);
}
echo json_encode($return_arr);
echo "\n";
mysqli_close($conn);
?>
I just can't seem to pass the data as JSON using AJAX and Jquery to the PHP side. Is there anything anything wrong with the syntax?
I have a controller function where it gets my json data for my bar graph
The json code from controller is
{"xkey":[["0","Sun"],["1","Mon"],["2","Tue"],["3","Wed"],["4","Thu"],["5","Fri"],["6","Sat"]],"user":[[2,"1"],[3,"1"]]}
Question from the controller function how am I able to pass the
json['xkey'] and json['user'] to my script
I have looked at Morris Js and Codeigniter pass data from a controller but not work for me.
Here is what I have tried
<script type="text/javascript">
$( document ).ready(function() {
$('#range').on('click', function(e) {
e.preventDefault();
$.ajax({
type: 'get',
url: "<?php echo base_url('admin/dashboard/chart/chart_data');?>/" + $( "#range" ).val(),
dataType: 'json',
success: function(json) {
if (typeof Morris != 'undefined') {
Morris.Bar({
element: 'bar-example',
resize: true,
stacked: false,
xLabelAngle: 50,
grid: true,
gridTextSize: 10,
data: [{m: json['xkey'] a: json['user']}],
xkey: 'm',
ykeys: ['a'],
labels: ['Users']
});
}
}
});
});
});
</script>
Controller
<?php
class Chart extends MX_Controller {
public function index() {
return $this->load->view('template/dashboard/chart_view');
}
public function chart_data() {
$json = array();
$json['xkey'] = array();
$json['user'] = array();
$uri_segment = $this->uri->segment(5);
if (isset($uri_segment)) {
$range = $uri_segment;
} else {
$range = 'month';
}
switch ($range) {
case "week":
$results = $this->getUserTotalByWeek();
foreach ($results as $key => $value) {
$json['user'][] = array($key, $value['total']);
}
$date_start = strtotime('-' . date('w') . ' days');
for ($i = 0; $i < 7; $i++) {
$date = date('Y-m-d', $date_start + ($i * 86400));
$json['xkey'][] = array(date('w', strtotime($date)), date('D', strtotime($date)));
}
break;
default:
echo "Your favorite color is neither red, nor green!";
}
$this->output->set_header('Content-Type: application/json; charset=utf-8');
$this->output->set_output(json_encode($json));
}
public function getUserTotalByWeek() {
$user_data = array();
$date_start = strtotime('-' . date('w') . ' days');
for ($i = 0; $i < 7; $i++) {
$date = date('Y-m-d', $date_start + ($i * 86400));
$customer_data[date('w', strtotime($date))] = array(
'day' => date('D', strtotime($date)),
'total' => 0
);
}
$this->db->select('COUNT(*) AS total, date_reg');
$this->db->from('user');
$this->db->where('date_reg >=', date('Y-m-d', $date_start));
$this->db->group_by('DAYNAME(date_reg)');
$query = $this->db->get();
foreach ($query->result_array() as $result) {
$user_data[date('w', strtotime($result['date_reg']))] = array(
'day' => date('D', strtotime($result['date_reg'])),
'total' => $result['total']
);
}
return $user_data;
}
}