Ajax based range search in jquery plugin "Datatables" - javascript

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);

Related

Submitted chat not posting and retrieving chat not working

I using the below php chat script to create chat section between two users on my web app. I am having a problem with the Ajax posting. When a user submits a chat it doesn't post or show in the chat window. I tried to inspect the error and this is the error message
Failed to load resource: the server responded with a status of 404 (Not Found)
The same error message is shown for submit.php and refresh.php.
Here's my code:
JS
//CHAT FUNCTION
var lastTimeID = 0;
$(document).ready(function() {
$('#btnSend').click( function() {
sendChatText();
$('#chatInput').val("");
});
startChat();
});
function startChat(){
setInterval( function() { getChatText(); }, 2000);
}
function getChatText() {
$.ajax({
type: "GET",
url: "refresh.php?lastTimeID=" + lastTimeID
}).done( function( data )
{
var jsonData = JSON.parse(data);
var jsonLength = jsonData.results.length;
var html = "";
for (var i = 0; i < jsonLength; i++) {
var result = jsonData.results[i];
html += '<div style="color:#' + result.color + '">(' + result.chattime + ') <b>' + result.usrname +'</b>: ' + result.chattext + '</div>';
lastTimeID = result.id;
}
$('#view_ajax').append(html);
});
}
function sendChatText(){
var chatInput = $('#chatInput').val();
if(chatInput != ""){
$.ajax({
type: "GET",
url: "submit.php?chattext=" + encodeURIComponent( chatInput )
});
}
}
chatClass.php
<?PHP
class chatClass
{
public static function getRestChatLines($id)
{
$arr = array();
$jsonData = '{"results":[';
$statement = $db->prepare( "SELECT id, usrname, color, chattext, chattime FROM chat WHERE id > ? and chattime >= DATE_SUB(NOW(), INTERVAL 1 HOUR)");
$statement->bind_param( 'i', $id);
$statement->execute();
$statement->bind_result( $id, $usrname, $color, $chattext, $chattime);
$line = new stdClass;
while ($statement->fetch()) {
$line->id = $id;
$line->usrname = $usrname;
$line->color = $color;
$line->chattext = $chattext;
$line->chattime = date('H:i:s', strtotime($chattime));
$arr[] = json_encode($line);
}
$statement->close();
$jsonData .= implode(",", $arr);
$jsonData .= ']}';
return $jsonData;
}
public static function setChatLines( $chattext, $usrname, $color) {
$statement = $db->prepare( "INSERT INTO chat( usrname, color, chattext) VALUES(?, ?, ?)");
$statement->bind_param( 'sss', $usrname, $color, $chattext);
$statement->execute();
$statement->close();
}
}
?>
submit.php
<?php
require_once( "chatClass.php" );
$chattext = htmlspecialchars( $_GET['chattext'] );
chatClass::setChatLines( $chattext, $_SESSION['usrname'], $_SESSION['color']);
?>
refresh.php
<?php
require_once( "chatClass.php" );
$id = intval( $_GET[ 'lastTimeID' ] );
$jsonData = chatClass::getRestChatLines( $id );
print $jsonData;
?>

Ajax datatables multiple column search

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.

i have booked dates in calendarm i want to show info from datesbase on the dates

* In javascript part i got the dates that are booked by user on dates, i n calendar i marked that dates are unavilable, but i want to show user info on that dates
<script type="text/javascript">
// Add New Dates and Block Out Booked Days Below
/*var unavailableDates1 = ["20-5-2016", "21-5-2016", "22-5-2016", "23-5-2016", "5-6-2016", "7-6-2016", "8-6-2016",
"15-6-2016", "16-6-2016", "25-6-2016", "26-6-2016", "27-6-2016", "28-6-2016", "14-2-2016",
"15-7-2016", "16-7-2016", "17-7-2016", "18-7-2016", "19-7-2016","20-7-2016","21-7-2016",
]; */
var unavailableDates = <?php echo json_encode($arr2); ?>;
var unavaila = <?php echo json_encode($e); ?>;
document.write(unavailableDates);
function unavailable(date) {
dmy = date.getDate() + "-" + (date.getMonth() + 1 ) + "-" + date.getFullYear();
if($.inArray(dmy, unavailableDates) == -1) {
return [true, ""];
}else {
return [false, "", unavaila];
}
}
$(function() {
$("#Datepicker1").datepicker({
numberOfMonths:3,
beforeShowDay: unavailable
});
});
</script>
*
and my php code is getting the dates from database in between start to end m, and showing calendar booked, how to show info on that
<?php
include 'dbconfig.php';
$query_getaway = "SELECT * FROM getaway_table; ";
$result_getaway = $db->query($query_getaway);
$category = mysqli_real_escape_string($db, filter_input(INPUT_POST, 'category')) .'<br>';
$resort = mysqli_real_escape_string($db, filter_input(INPUT_POST, 'resorts')) .'<br>';
if( $category != 0 ){
$query = "SELECT * FROM booking_request where room_id = '$resort' '<br>' ";
$result = $db->query($query);
if( $result -> num_rows > 0 ) {
while( $row = $result-> fetch_assoc() )
{
$name = $row['getaway_name']." <br>";
$start = $row['check_in_date']." <br>";
$end = $row['check_out_date']." <br>";
$guest_n[]= $row['guest_name'];
$guest_number[]= $row['guest_phone'];
$arr1 = range(strtotime($row['check_in_date']),strtotime($row['check_out_date']), "86400");
array_walk_recursive($arr1, function(&$element) { $element = date("j-n-Y", $element); });
foreach ($arr1 as $value)
{
$arr2[]= $value;
}
$arrt= (array_merge($guest_n, $guest_number));
//print_r($arrt);
foreach($arrt as $val)
{
echo $arr_val[]=$val;
}
$arr[]= $value;
}
}
else { echo "select" ;}
?>
how to get the result to show user details on mousehover on dates from db.

Want to get the user info from database , and want to show on calendar

I have php code from this I got complete dates of room that are booked by one user like 12-15.
And 17-18, for second user 20-21, I got marked these dates on calendar.
Now I want to show user info on mouse hover:
<?php
include 'dbconfig.php';
$query_getaway = "SELECT * FROM getaway_table; ";
$result_getaway = $db->query($query_getaway);
$category = mysqli_real_escape_string($db, filter_input(INPUT_POST, 'category')) .'<br>';
$resort = mysqli_real_escape_string($db, filter_input(INPUT_POST, 'resorts')) .'<br>';
if( $category != 0 ){
$query = "SELECT * FROM booking_request where room_id = '$resort' '<br>' ";
$result = $db->query($query);
if( $result -> num_rows > 0 ) {
while( $row = $result-> fetch_assoc() )
{
$name = $row['getaway_name']." <br>";
$start = $row['check_in_date']." <br>";
$end = $row['check_out_date']." <br>";
$guest_n[]= $row['guest_name'];
$guest_number[]= $row['guest_phone'];
$arr1 = range(strtotime($row['check_in_date']),strtotime($row['check_out_date']), "86400");
array_walk_recursive($arr1, function(&$element) { $element = date("j-n-Y", $element); });
foreach ($arr1 as $value)
{
$arr2[]= $value;
}
$arrt= (array_merge($guest_n, $guest_number));
//print_r($arrt);
foreach($arrt as $val)
{
echo $arr_val[]=$val;
}
$arr[]= $value;
}
}
else { echo "select" ;}
?>
Then in js part I showed unavailable dates, bot on hover I'm unable to show user complete info:
<script type="text/javascript">
// Add New Dates and Block Out Booked Days Below
/*var unavailableDates1 = ["20-5-2016", "21-5-2016", "22-5-2016", "23-5-2016", "5-6-2016", "7-6-2016", "8-6-2016",
"15-6-2016", "16-6-2016", "25-6-2016", "26-6-2016", "27-6-2016", "28-6-2016", "14-2-2016",
"15-7-2016", "16-7-2016", "17-7-2016", "18-7-2016", "19-7-2016","20-7-2016","21-7-2016",
]; */
var unavailableDates = <?php echo json_encode($arr2); ?>;
document.write(unavailableDates);
function unavailable(date) {
dmy = date.getDate() + "-" + (date.getMonth() + 1 ) + "-" + date.getFullYear();
if($.inArray(dmy, unavailableDates) == -1) {
return [true, ""];
}else {
this line is showing unavlaible on hover, i want from database user info
return [false, "","unavalible"];
<?php echo $val; ?>
}
}
$(function() {
$("#Datepicker1").datepicker({
numberOfMonths:3,
beforeShowDay: unavailable
});
});
</script>

Ui Autocomplete return all values online but in localhost works

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']);

Categories

Resources