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.
Related
I want to off the click when the First Page and Previous li is disabled also when you are on last page the Next and Last should be not clicked. I used off() and unbind() it is working to off the click but when the li is enabled then the click is not working. You can check it here on this link my project is live here http://199.192.21.232/~admin/category.php?cat_id=2 thank you.
HTML Code
<ul class="pagi cf">
<li><strong id="nav_info"></strong></li>
<li id="nav_first"><a>‹‹ First Page</a></li>
<li id="nav_prev"><a>Previous</a></li>
<select class="btn" id="nav_currentPage"></select>
<li id="nav_next"><a>Next</a></li>
<li id="nav_last"><a>Last ››</a></li>
</ul>
Ajax Script
<script>
$(document).ready(function(e) {
//SHOW LIST WHEN DO STRING SEARCH
$("#src-btn").click(function() {
showList('');
});
//--- start navigation btn
$("#nav_first").click(function(e) {
showList('first');
});
$("#nav_prev").click(function(e) {
showList('prev');
});
$("#nav_next").click(function(e) {
showList('next');
});
$("#nav_last").click(function(e) {
showList('last');
});
$("#per-page").change(function(e) {
showList('');
});
$("#nav_currentPage").change(function(e) {
showList('goto');
});
//--- end navigation btn
//SHOW LIST WHEN CALLED BY OTHER BUTTON [ADD NEW ITEM, THEN RELOAD LIST]
$("#src-frm").submit(function() {
showList();
return false;
});
//START SHOWING LIST
showList('');
function showList(navAction) {
$('body').append('<div class="pgrs"></div><div class="spin"><div class="loader">Loading...</div></div>');
//$("#nav_info").html('<div class="loader"></div>');
var searchKeyword = $("#src-txt").val(),
currentPage = $("#nav_currentPage").val(),
rowsPerPage = $("#per-page").val();
$.ajax({
type: 'POST',
url: "pagination.php",
data: {
cat_id: < ? php echo $_GET['cat_id']; ? > ,
keyword : searchKeyword,
currentPage: currentPage,
rowsPerPage: rowsPerPage,
navAction: navAction
},
// this part is progress bar
xhr: function() {
var xhr = new window.XMLHttpRequest();
xhr.upload.addEventListener("progress", function(evt) {
if (evt.lengthComputable) {
var percentComplete = evt.loaded / evt.total;
percentComplete = parseInt(percentComplete * 100);
//$('.pgrs').text(percentComplete + '%');
$('.pgrs').css('width', percentComplete + '%');
}
}, false);
xhr.addEventListener("progress", function(evt) {
if (evt.lengthComputable) {
var percentComplete = evt.loaded / evt.total;
percentComplete = parseInt(percentComplete * 100);
//$('.pgrs').text(percentComplete + '%');
$('.pgrs').css('width', percentComplete + '%');
}
}, false);
return xhr;
},
success: function(data) {
//parse json string to javascript json object
var data = JSON.parse(data);
//push data to table
$("#category-products").html(data.list);
//select or focus the target page
$("#nav_currentPage").val(data.targetPage);
//check if action is refresh, then reload the GOTO list
if (navAction == 'refresh' || navAction == '') {
//empty the list
$('#nav_currentPage').empty();
//append option item with value to select list
$.each(data.gotoSelectNum, function(key, value) {
$('#nav_currentPage').append($("<option></option>").attr("value", value).text(value));
});
}
//show list page and record info
if (data.totalPages == 0) {
$("#nav_info").html('List Empty');
} else {
$("#nav_info").html('Page ' + data.targetPage + ' of ' + data.totalPages);
$(".pgrs,.spin").remove();
}
//disable or enable pagination button
$.each(data.nav_btn_disable, function(key, jdata) {
if (jdata == 1) {
$("#" + key).removeClass('disabled');
} else {
$("#" + key).addClass('disabled');
}
})
}
});
}
});
</script>
PHP CODE
<?php
include 'config.php';
$currency_symbol = '$';
$conn = OpenCon();
// SCRIPT IN PHP FILE REQUESTED BY AJAX, SEPARATED FILE
$cat_id = $_POST['cat_id'];
$keyword = $_POST['keyword'];
$currentPage = intval($_POST['currentPage']);
$rowsPerPage = $_POST['rowsPerPage'];
$navAction = $_POST['navAction'];
//Applying some condition to SQL
$sql_condition = 'WHERE';
if($keyword<>''){
$sql_condition .= ($sql_condition == 'WHERE' ? '' : ' FIND_IN_SET('.$cat_id.', products_cat.id) AND')." (product_title LIKE '%$keyword%')";
}
if($sql_condition == 'WHERE'){
$sql_condition = 'WHERE FIND_IN_SET('.$cat_id.', products_cat.id)';
}
//Work with total page
//$query = "SELECT * FROM products $sql_condition ORDER BY product_title ASC";
$query = "SELECT * FROM products_cat JOIN products ON FIND_IN_SET(products_cat.id, products.product_category) $sql_condition ORDER BY products.product_title ASC";
$navRow_qry = mysqli_query($conn,$query);
$totalRow = mysqli_num_rows($navRow_qry);
$totalPages = $totalRow/$rowsPerPage;
if($totalRow%$rowsPerPage>0){$totalPages = intval($totalPages) + 1;}
//Get the target page number
$targetPage = 1;$nav_btn_disable = array();
if($navAction=='first'){
$targetPage = 1;
}elseif($navAction=='prev'){
$targetPage = $currentPage-1;
}elseif($navAction=='next'){
$targetPage = $currentPage+1;
}elseif($navAction=='last'){
$targetPage = $totalPages;
}elseif($navAction=='goto'){
$targetPage = $currentPage;
}
//Get goto select list
$gotoSelectNum = array();
for($i=1;$i<=$totalPages;$i++){
$gotoSelectNum[] = $i;
}
//Check button to be disable or enable
if($totalPages==1 or $totalPages==0){
$nav_btn_disable = array('nav_first'=>0,'nav_prev'=>0,'nav_next'=>0,'nav_last'=>0);
}elseif($targetPage==1){
$nav_btn_disable = array('nav_first'=>0,'nav_prev'=>0,'nav_next'=>1,'nav_last'=>1);
}elseif($targetPage==$totalPages){
$nav_btn_disable = array('nav_first'=>1,'nav_prev'=>1,'nav_next'=>0,'nav_last'=>0);
}else{
$nav_btn_disable = array('nav_first'=>1,'nav_prev'=>1,'nav_next'=>1,'nav_last'=>1);
}
//Applying data to be shown according to the criteria [targetPage,rowsPerPage]
$startIndex = ($targetPage-1)*$rowsPerPage;
$dataListString = '';$i=$startIndex+1;
//Querying data from data
//$query = "SELECT * FROM products $sql_condition ORDER BY product_title ASC LIMIT ".$startIndex.",$rowsPerPage";
$query = "SELECT * FROM products_cat JOIN products ON FIND_IN_SET(products_cat.id, products.product_category) $sql_condition ORDER BY products.product_title ASC LIMIT ".$startIndex.",$rowsPerPage";
$data_qry = mysqli_query($conn,$query);
if (!empty($data_qry) && $data_qry->num_rows > 0)
{
$i = 1;
$dataListString .= '<ul id="products" class="products">';
while($data_row = mysqli_fetch_assoc($data_qry))
{
if($i++ % 5 == 0){$last = ' class="last"';}else{$last = '';}
$ids = explode(",", $data_row['product_images']);
$dataListString .= '<li '.$last.'><a href="single.php?product-id='.$data_row['id'].'">';
$dataListString .= getProductImg($ids[0]);
$dataListString .= getProductImg($ids[1]);
$dataListString .= '<div class="ti">'.$data_row['product_title'].'</div>';
if(empty($data_row['product_sprice'])){
$dataListString .= '<span class="sp">'.$currency_symbol.$data_row['product_rprice'].'</span>';
}
else{
$dataListString .= '<span class="sp">'.$currency_symbol.$data_row['product_sprice'].'</span>';
$dataListString .= '<span class="rp">'.$currency_symbol.$data_row['product_rprice'].'</span>';
$dataListString .= '<span class="pr">'.percent($data_row['product_rprice'],$data_row['product_sprice']).'</span>';
}
$dataListString .= '</a></li>';
}
$dataListString .= "</ul>";
}
else
{
$dataListString .='';
}
//check if no data in database, then display 'No Data' message
if($dataListString == ''){$dataListString = 'No Data Found';}
//store all variable to an array
$data = array('list'=>$dataListString,'targetPage'=>$targetPage,'totalPages'=>$totalPages,'gotoSelectNum'=>$gotoSelectNum,'nav_btn_disable'=>$nav_btn_disable);
//convert array to json object, and return it back to ajax
echo json_encode($data);
CloseCon($conn);
I just fixed it with this code.
$(".pagi li").click(function(e){
if (!$(this).hasClass("disabled"))
{
if($(this).is('#nav_first')){
showList('first');
}else if($(this).is('#nav_prev')){
showList('prev');
}else if($(this).is('#nav_next')){
showList('next');
}else if($(this).is('#nav_last')){
showList('last');
}
}
});
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 have a php website linked with Sql Server database, im trying to get data from the database and show it on the page in a table but when it create the table it show me the message "No results found" , what is the code to get the info from the database and show it in the website?
ps:im using jquery.bootgrid
<?php
include 'dbh.inc.php';
$query='';
$data=array();
$records_per_page= 10;
$start_from= 0;
$current_page_number= 0;
if(isset($_POST["rowCount"]))
{
$records_per_page= $_POST["rowCount"];
}
else
{
$records_per_page= 10;
}
if(isset($_POST["current"]))
{
$records_per_page= $_POST["current"];
}
else
{
$records_per_page= 1;
}
$star_from= ($current_page_number - 1)* $records_per_page;
$query .="SELECT * FROM Employee";
if(!empty($_POST["searchPhrase"]))
{
$query .= 'where (Id like "%'.$_POST["searchPhrase"].'%")';
$query .= 'or First_Name like "%'.$_POST["searchPhrase"].'%" ';
$query .= 'or Last_Name like "%'.$_POST["searchPhrase"].'%" ';
$query .= 'or username like "%'.$_POST["searchPhrase"].'%" ';
}
$order_by = '';
if(isset($_POST["sort"]) && is_array($_POST["sort"]))
{
foreach($_POST["sort"] as $key =>$value )
{
$order_by = '$key $value,';
}
}
else
{
$query .= 'order by Id Desc';
}
if($order_by != '')
{
$query .= ' order by ' . substr($order_by,0,-2);
}
if($records_per_page != -1)
{
$query .= "LIMIT" .$star_from. "," .$records_per_page;
}
$result = sqlsrv_query($conn, $query);
while($row=sqlsrv_fetch_array($result))
{
$data[]=$row;
}
$query1 .="SELECT * FROM Employee";
$result1 = sqlsrv_query($conn, $query1);
$total_records=sqlsrv_has_rows($result1);
$output=array('current' => intval($_POST["current"]),
'rowCount' => 10,
'total' => intval($total_records),
'rows' => $data );
echo json_encode($output);
?>
I'm trying about 2 days to fix this I will blow my mind I can't anymore..When I am running it in localhost it's just working fine but when I am trying it online its just returns same values...and all values not returns the search term I can't understand why.
Jquery
$(document).ready(function($){
$('#quick-search-input2').autocomplete({
source:'All/home/directsearch.php',
minLength:2,
autoFocus: true,
select: function(event,ui){
var code = ui.item.id;
if(code != '') {
location.href = 'Movies/' + code;
}
},
html: true,
open: function(event, ui) {
$('ul.ui-autocomplete').slideDown(500)('complete');
$(".ui-autocomplete").css("z-index", 1000);
},
}).data("ui-autocomplete")._renderItem = function (ul, item) {
return $("<li></li>")
.data("item.autocomplete", item)
.append("" + item.label + "")
.appendTo(ul);
};
});
PHP
$server = 'localhost';
$user = 'root';
$password = '';
$database = 'search';
$mysqli = new MySQLi($server,$user,$password,$database);
/* Connect to database and set charset to UTF-8 */
if($mysqli->connect_error) {
echo 'Database connection failed...' . 'Error: ' . $mysqli->connect_errno . ' ' . $mysqli->connect_error;
exit;
} else {
$mysqli->set_charset('utf8');
}
$term = stripslashes($_GET ['term']);
$term = mysql_real_escape_string($_GET ['term']);
$a_json = array();
$a_json_row = array();
include '../../connect.php';
/* ***************************************************************************** */
if ($data = $mysqli->query("SELECT * FROM search WHERE (title LIKE '%$term%' or keywords LIKE '%$term%') and serie = '' and visible = '' and complete = '' group by title, year order by clicks desc LIMIT 5")) {
while($row = mysqli_fetch_array($data)) {
$title = $row['title'];
$year = htmlentities(stripslashes($row['year']));
$type = $row['type'];
$customercode= htmlentities(stripslashes($row['link']));
$category= htmlentities(stripslashes($row['category']));
$synopsis= htmlentities(stripslashes($row['synopsis']));
$img= htmlentities(stripslashes($row['img']));
$id= htmlentities(stripslashes($row['id']));
$category = str_replace(" | ",", ", $category);
$shit = "'";
$ltitle = strtolower($title);
if ($type == "DL-HD")
{
$qualityresponse = '<img class="quality-banner img-responsive" src="Design/types/HD.png">';
}
else if ($type == "Non-HD")
{
$qualityresponse = '<img class="quality-banner img-responsive" src="Design/types/NonHD.png">';
}
else if ($type == "CAM")
{
$qualityresponse = '<img class="quality-banner img-responsive" src="Design/types/CAM.png">';
}
else
{
$qualityresponse = "";
}
$stitle = preg_replace("/[^A-Za-z0-9]/", "", $ltitle);
$a_json_row["id"] = $customercode;
$a_json_row["value"] = ''.$term.'';
$a_json_row["label"] = '
'.$qualityresponse.'<span class="titles">'.$title.'</span><p>'.$year.'</p></center>
';
array_push($a_json, $a_json_row);
}
}
$foundnum = mysql_num_rows(mysql_query("SELECT * FROM search WHERE (title LIKE '%$term%' or keywords LIKE '%$term%') and serie = '' and visible = '' and complete = '' group by title, year order by clicks desc LIMIT 5"));
if ($foundnum == 0)
{
$a_json_row["label"] = '
<li class="ac-no-results ac-item-hover ac-item-selected">No Movies found</li>
';
array_push($a_json, $a_json_row);
}
echo json_encode($a_json);
flush();
$mysqli->close();
$term = mysql_real_escape_string($_GET ['term']);
to
$term = mysqli->real_escape_string($_GET ['term']);
i use select2, i want to format my results like
name, first.
$("#id").select2({
minimumInputLength : 0,
allowClear: true,
ajax : {
url : "Form/page.php",
dataType : 'json',
data : function (term, page) {
return {
q : term
};
},
results: function (data, page) {
return { results : data.ex};
},
formatResult : function formatResult(ex) {
return '<b>' + ex.name + '</b>';
}
}
});
my php file like
while($r=mysql_fetch_array($m)) {
$rows['id']=$r['id'];
$rows['text']=$r['name'];
$rows['first']=", ". $r['first'];
$rows2[]=$rows;
}
print json_encode($rows2);
how can i do that, thanks
I think the php code has to be like this:
while($r=mysql_fetch_array($m)) {
$rows['id']=$r['id'];
$rows['name']=$r['name'];
$rows['first']=$r['first'];
$rows2[]=$rows;
}
print json_encode($rows2);
So, you pass an array of json objects with an id, name and first.
Change the return of formatResult to:
return '<b>' + ex.name + '</b>, ' + ex.first;
PHP example reposted from the Select2 - source example:
https://github.com/ivaynberg/select2/wiki/PHP-Example
In JS:
$('#categories').select2({
placeholder: 'Search for a category',
ajax: {
url: "/ajax/select2_sample.php",
dataType: 'json',
quietMillis: 100,
data: function (term, page) {
return {
term: term, //search term
page_limit: 10 // page size
};
},
results: function (data, page) {
return { results: data.results };
}
},
initSelection: function(element, callback) {
return $.getJSON("/ajax/select2_sample.php?id=" + (element.val()), null, function(data) {
return callback(data);
});
}
});
and in PHP:
<?php
$row = array();
$return_arr = array();
$row_array = array();
if((isset($_GET['term']) && strlen($_GET['term']) > 0) || (isset($_GET['id']) && is_numeric($_GET['id'])))
{
if(isset($_GET['term']))
{
$getVar = $db->real_escape_string($_GET['term']);
$whereClause = " label LIKE '%" . $getVar ."%' ";
}
elseif(isset($_GET['id']))
{
$whereClause = " categoryId = $getVar ";
}
/* limit with page_limit get */
$limit = intval($_GET['page_limit']);
$sql = "SELECT id, text FROM mytable WHERE $whereClause ORDER BY text LIMIT $limit";
/** #var $result MySQLi_result */
$result = $db->query($sql);
if($result->num_rows > 0)
{
while($row = $result->fetch_array())
{
$row_array['id'] = $row['id'];
$row_array['text'] = utf8_encode($row['text']);
array_push($return_arr,$row_array);
}
}
}
else
{
$row_array['id'] = 0;
$row_array['text'] = utf8_encode('Start Typing....');
array_push($return_arr,$row_array);
}
$ret = array();
/* this is the return for a single result needed by select2 for initSelection */
if(isset($_GET['id']))
{
$ret = $row_array;
}
/* this is the return for a multiple results needed by select2
* Your results in select2 options needs to be data.result
*/
else
{
$ret['results'] = $return_arr;
}
echo json_encode($ret);
$db->close();
?>