I would like to filter my chart by month so I made a <select> input above it. The chart is showing properly but when I changed the month options, the data is not updating based on the value selected. Here's what I've done so far:
index.php
<div class="row form-group">
<select class="form-control col-lg-4" name="month">
<option selected="selected" style="display:none"><?php echo date("F");?></option>
<option value="9">September</option>
<option value="10">October</option>
</select>
</div>
<canvas id="chart"></canvas>
<script>
window.onload = function() {
$.ajax({
type: 'POST',
url: 'data.php ',
datatype: 'json',
success: function (result) {
var ctx = document.getElementById("chart").getContext("2d");
var mychart = new Chart(ctx,
{
type: 'bar',
data: JSON.parse(result),
options: {
scales: {
xAxes: [{ stacked: true }],
yAxes: [{ stacked: true }]
}
}
})
}
})};
</script>
data.php
<?php
$conn = mysqli_connect("localhost","root","","production");
$month = '';
if(isset($_POST["month"]))
{
$month = $_POST["month"];
} else {
$month = date('m');
}
$query = "SELECT finish_date,
SUM(CASE WHEN customer_type = 'customer_A' THEN order_qty ELSE 0 END) AS custom_A,
SUM(CASE WHEN customer_type = 'customer_B' THEN order_qty ELSE 0 END) AS custom_B,
SUM(CASE WHEN customer_type = 'customer_C' THEN order_qty ELSE 0 END) AS custom_C
FROM production WHERE MONTH(finish_date) = ".$month." GROUP BY finish_date ORDER BY finish_date ASC";
if ($stmt = $conn->prepare($query)) {
$stmt->execute();
$stmt->bind_result($date, $custom_A, $custom_B, $custom_C);
$labels = array();
$data_A = array();
$data_B = array();
$data_C = array();
while ($stmt->fetch()) {
$labels[] = $date;
$data_A[] = $custom_A;
$data_B[] = $custom_B;
$data_C[] = $custom_C;
}
$stmt->close();
}
$datasets_A = array('label'=>"A",'data'=> $data_A,'backgroundColor'=>"#D6E9C6");
$datasets_B = array('label'=>"B",'data'=> $data_B,'backgroundColor'=>"#FAEBCC");
$datasets_C = array('label'=>"C",'data'=> $data_C,'backgroundColor'=>"#EBCCD1");
$data = array('labels'=>$labels, 'datasets'=> array($datasets_A,$datasets_B,$datasets_C));
echo json_encode($data);
?>
How can I make it work? I must have miss something but not sure what it is since I'm not getting any error message.
You need to write change event so that whenever select-box is change the value will be send to your backend and the updated json data will send back as response which you will update in your chart .
Jquery code :
window.onload = function() {
update(); //call your function to update chart
}
//onchange of select
$("select[name=month]").on("change", function() {
var month = $(this).val() //get value of select
update(month); //call to update
})
function update(month) {
var value;
//if null
if (month == null) {
value = "default"; //send some dummy data
} else {
value = month; //send actual month
}
$.ajax({
type: 'POST',
url: 'data.php ',
data: {
month: value //send value to backend
},
datatype: 'json',
success: function(result) {
//update chart datas
var ctx = document.getElementById("chart").getContext("2d");
var mychart = new Chart(ctx, {
type: 'bar',
data: JSON.parse(result),
options: {
scales: {
xAxes: [{
stacked: true
}],
yAxes: [{
stacked: true
}]
}
}
})
}
})
}
And only change in php code you need to make is here :
if(isset($_POST["month"]) && $_POST["month"] != "default" ){
$month = $_POST["month"];
} else {
$month = date('m');
}
Related
i have a form that works by filling the next select fields with data based on the previous ones, it works perfect on Localhost / Xampp with PHP8 but now when i try to get it on my server it only works "once" per category.
My problem simplified.
I select category1 and get two results based on that to the next select
Only one of these results works with returning data to the 3rd Select and the other one doesn't return anything with json_encode and only throws an error
More info:
Request that works.
{
"request": "2",
"subcategoryid": "11",
"alakategoriaID": "15"
}
[
Response which is correct.
{
"ID": "23",
"name": "Puu 25"
},
{
"ID": "24",
"name": "Puu 50"
}
Request that doesn't return anything
{
"request": "2",
"subcategoryid": "10",
"alakategoriaID": "15"
}
Main function that contains the select fields etc..
´´´<script>
$(function () {
// Country
$('#sel_country').change(function () {
var categoryID = $(this).val();
// Empty state and city dropdown
$('#sel_state').find('option').not(':first').remove();
$('#sel_city').find('option').not(':first').remove();
$('#varichanger').find('option').not(':first').remove();
// AJAX request
$.ajax({
url: 'helper.php',
type: 'post',
data: {
request: 1,
categoryID: categoryID
},
dataType: 'json',
success: function (response) {
var len = response.length;
for (var i = 0; i < len; i++) {
var id = response[i]['id'];
var name = response[i]['name'];
$("#sel_state").append("<option value='" + id + "'>" + name + "</option>");
}
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert("some error");
}
});
$.ajax({
url: 'helper.php',
type: 'post',
data: {
request: 3,
categoryID: categoryID
},
dataType: 'json',
success: function (response) {
var len = response.length;
for (var i = 0; i < len; i++) {
var id = response[i]['id'];
var name = response[i]['name'];
$("#varichanger").append("<option value='" + id + "'>" + name + "</option>");
}
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert("some error");
}
});
});
// State
$('#sel_state').change(function () {
var subcategoryid = $(this).val();
var alakategoriaID = $('#sel_country').val();
// Empty city dropdown
$('#sel_city').find('option').not(':first').remove();
// AJAX request
$.ajax({
url: 'helper.php',
type: 'post',
data: {
request: 2,
subcategoryid: subcategoryid,
alakategoriaID: alakategoriaID
},
dataType: 'json',
success: function (response) {
console.log(response);
var len = response.length;
for (var i = 0; i < len; i++) {
var id = response[i]['ID'];
var name = response[i]['name'];
$("#sel_city").append("<option value='" + id + "'>" + name + "</option>");
}
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert("some error");
}
});
});
});
</script>´´´
Helper.php
include "pdoconfig.php";
error_reporting(0);
$request = 0;$request = 0;
if(isset($_POST['request'])){
$request = $_POST['request'];
}
// Fetch subcategory list by categoryID
if(trim($request) == 1){
$categoryID = $_POST['categoryID'];
$stmt = $conn->prepare("SELECT * FROM alakategoriat WHERE kategoriaID=:kategoriaID ORDER BY subcategoryname");
$stmt->bindValue(':kategoriaID', (int)$categoryID, PDO::PARAM_INT);
$stmt->execute();
$subcategorysList = $stmt->fetchAll();
$response = array();
foreach($subcategorysList as $subcategory){
$response[] = array(
"id" => $subcategory['id'],
"name" => $subcategory['subcategoryname']
);
}
echo json_encode($response);
exit;
}
// Fetch city list by subcategoryid
if(trim($request) == 2){
$kategoriaID = $_POST['alakategoriaID'];
$alakategoriaID = $_POST['subcategoryid'];
$stmt = $conn->prepare("SELECT * FROM tuotteet
WHERE kategoriaID=$kategoriaID
AND alakategoriaID=$alakategoriaID
ORDER BY productname");
$stmt->execute();
$productslist = $stmt->fetchAll();
$response = array();
foreach($productslist as $product){
$response[] = array(
"ID" => $product['ID'],
"name" => $product['productname']
);
}
echo json_encode($response);
exit;
}
if(trim($request) == 3){
$categoryID = $_POST['categoryID'];
$stmt = $conn->prepare("SELECT *
FROM kategoriavarit
INNER JOIN varit ON kategoriavarit.variID = varit.variID
WHERE kategoriaID=:kategoriaID");
$stmt->bindValue(':kategoriaID', (int)$categoryID, PDO::PARAM_INT);
$stmt->execute();
$varilist = $stmt->fetchAll();
$response = array();
foreach($varilist as $vari){
$response[] = array(
"id" => $vari['variID'],
"name" => $vari['varinimi']
);
}
echo json_encode($response);
exit;
}
you have to save your first category value to session and use it for second time ajax call. As per your code you always get
trim($request) == 1
because each time ajax call it consider as new request. So use session or cookie for store and use parent category.
Solved the problem by clearing and reinserting my database values and following #Foramkumar Patel's answer
EDIT: Cancel that, problem was with scandinavian letters in the response from JSON causing many different problems, solved the problem by utf_8 encoding the response.
Trying to paginate ajax data using Select2 (v 4.0.6.rc1) so that the user can find more results if not present in the first limit ,using the following but not retrieving data.I 'll appreciate if someone helps me out,there is not much of examples about pagination.
i was trying to paginate data using the help of this question Select2 v4 how to paginate results using AJAX its not seems to be working,getting the array but not correct format.
JS:
$('#compose_username').select2({
dropdownParent: $("#modal-compose") ,
placeholder: "Search Username...",
minimumInputLength: 1,
ajax: {
url: "username.php",
dataType: 'json',
delay: 250,
cache: false,
data: function (params) {
return {
term: params.term,
page: params.page || 1
//a: params.term, // search term
//psf: params.page
};
},
processResults: function(data) {
console.log(data);
var result = $.map(data, function (item) { return { id: item.id, text: item.username }});
return { results: result };
}
}
});
PHP
try{
$page= $_GET['page'];
// $resultCount = 10;
// $offset = ($page - 1) * $resultCount;
$pageLength = 20;
$pageStart = ($page - 1) * $pageLength;
$pageEnd = $pageStart + $pageLength;
$stmt = $db_con->query("SELECT id,first_name FROM datatables_demo WHERE first_name LIKE '%".$_GET['term']."%' LIMIT {$pageStart},{$pageEnd}");
$count = $db_con->query("SELECT count(first_name) FROM datatables_demo WHERE first_name LIKE '%".$_GET['term']."%' LIMIT {$pageStart},{$pageEnd}")->fetchColumn();;
$stmt->execute();
$json = [];
while($row = $stmt->fetch(PDO::FETCH_ASSOC)){
$json[] = ['id'=>$row['id'], 'username'=>$row['first_name']];
}
$endCount = $pageStart + $pageLength;
$morePages = $endCount > $count;
$results = array(
"results" => $json,
"pagination" => array(
"more" => $morePages
)
);
echo json_encode($results);
}
catch(PDOException $e){
echo $e->getMessage();
}
Found not much examples about select2 paginate, had to figure it out on my own and here is the full working of how to paginate data(infinite scroll) using Select2: Hope this helps someone else.
JS:
$('#compose_username').select2({
dropdownParent: $("#modal-compose") ,
placeholder: "Search Username...",
minimumInputLength: 1,
allowClear: true,
ajax: {
url: "username.php",
dataType: 'json',
delay: 250,
cache: false,
data: function (params) {
return {
term: params.term,
page: params.page || 1,
};
},
processResults: function(data, params) {
//console.log(data);
// NO NEED TO PARSE DATA `processResults` automatically parse it
//var c = JSON.parse(data);
console.log(data);
var page = params.page || 1;
return {
results: $.map(data, function (item) { return {id: item.col, text: item.col}}),
pagination: {
// THE `10` SHOULD BE SAME AS `$resultCount FROM PHP, it is the number of records to fetch from table`
more: (page * 10) <= data[0].total_count
}
};
},
}
});
PHP(USING PDO):
try{
$page= $_GET['page'];
$resultCount = 10;
$end = ($page - 1) * $resultCount;
$start = $end + $resultCount;
$stmt = $db_con->query("SELECT col,col FROM table WHERE col LIKE '".$_GET['term']."%' LIMIT {$end},{$start}");
$stmt->execute();
$count = $stmt->rowCount();
$data = [];
while($row = $stmt->fetch(PDO::FETCH_ASSOC))
$data[] = ['id'=>$row['id'], 'col'=>$row['col'],'total_count'=>$count];
// IF SEARCH TERM IS NOT FOUND DATA WILL BE EMPTY SO
if (empty($data)){
$empty[] = ['id'=>'', 'col'=>'', 'total_count'=>''];
echo json_encode($empty);
}
else
echo json_encode($data);
}
catch(PDOException $e){
echo $e->getMessage();
}
I have implemented the following autoload code. It fetches result from database but it keeps looping the same result over and over.
php code
<?php
require_once("config.php");
$limit = (intval($_GET['limit']) != 0 ) ? $_GET['limit'] : 10;
$offset = (intval($_GET['offset']) != 0 ) ? $_GET['offset'] : 0;
$keywords = $_GET['keywords'];
$sql = "SELECT * FROM blog_posts WHERE postCat LIKE '".$keywords."' ORDER BY postID ASC LIMIT $limit OFFSET $offset";
try {
$stmt = $DB->prepare($sql);
$stmt->execute();
$results = $stmt->fetchAll();
} catch (Exception $ex) {
echo $ex->getMessage();
}
if (count($results) > 0) {
foreach ($results as $res) {
echo '<h3>' . $res['postTitle'] . '</h3>';
}
}
?>
Try this
<?php
$keywords = 'events';
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Test</title>
<script src="bootstrap/js/jquery-1.11.1.min.js"></script>
</head>
<body>
<div class="col-lg-12" id="results"></div>
<div id="loader_image"><img src="loader.gif" alt="" width="24" height="24"> Loading...please wait</div>
<div class="margin10"></div>
<div id="loader_message"></div>
</div>
<script type="text/javascript">
var keywords = '<?php echo $keywords; ?>'; // Changed
var busy = false;
var limit = 15;
var offset = 0;
function displayRecords(lim, off) {
// Changed/New
var data = {
'limit': lim,
'offset': off,
'keywords': keywords,
};
$.ajax({
type: "GET",
async: false,
url: "getrecords.php",
data: data, // Changed
cache: false,
beforeSend: function() {
$("#loader_message").html("").hide();
$('#loader_image').show();
},
success: function(html,textStatus,jqHXR) {
$("#results").append(html);
$('#loader_image').hide();
if (html == "") {
$("#loader_message").html('<button class="btn btn-default" type="button">No records found.</button>').show()
} else {
$("#loader_message").css('display','none');
$("#loader_message").html(html);
}
window.busy = false;
},
});
}
$(document).ready(function() {
// start to load the first set of data
if (busy == false) {
busy = true;
// start to load the first set of data
displayRecords(limit, offset);
}
$(window).scroll(function() {
// make sure u give the container id of the data to be loaded in.
if ($(window).scrollTop() + $(window).height() > $("#results").height() && !busy) {
$('#result').on('scroll', function() { if($(this).scrollTop() + $(this).innerHeight() >= $(this)[0].scrollHeight) { busy = true; offset = limit + offset; setTimeout(function() { displayRecords(limit, offset); }, 500); } })
// you can remove the above code and can use directly this function
// displayRecords(limit, offset);
}
});
});
</script>
</body>
</html>
this is loading same contents over and over because on each ajax call you are sending same 'data' which is
var data = {
'limit': limit,
'offset': offset,
'keywords': keywords,
};
Change the function to use new limit and offset
function displayRecords(lim, off) {
data = {
'limit': lim,
'offset': off,
'keywords': keywords,
};
$.ajax({
type: "GET",
async: false,
url: "getrecords.php",
data: data, // Changed
cache: false,
beforeSend: function() {
$("#loader_message").html("").hide();
$('#loader_image').show();
},
...
...
I have a text box where I search database for a specific information.
The PHP code when I just type and click on search is the following:
try
{
$date_emp = $_POST['date_emp'];
$val = $_POST['data1'];
$gender = $_POST['gen'];
if($date_emp == "choose" && $gender == "specify")
{
$search = "SELECT * FROM employee
WHERE emp_name = :val OR position = :val
OR salary = :val OR date_employed = :val
OR gender = :val";
$searchStmt = $conn->prepare($search);
$searchStmt->bindValue(":val", $val);
$searchStmt->execute();
$res = $searchStmt->fetchAll();
echo json_encode($res);
}
catch(PDOException $ex)
{
echo $ex->getMessage();
}
And here the AJAX script for it:
$("#search").click(function()
{
var txt = $("#txtSearch").val();
var drop = $("#date_employed").val();
var gender = $("#sex").val();
//console.log(txt);
if(txt == '' && drop == "choose" && gender == "specify")
{
$("#txtSearch").css('border-color', 'red');
}
else
{
if(drop == "choose" && gender == "specify")
{
$.ajax
({
url: 'search.php',
type: 'POST',
data: {data1: txt, date_emp: drop, gen: gender},
dataType: 'JSON',
success:function(res)
{
$("#myTable tr").remove();
$("#myTable").append("<tr><th>Name</th><th>Position</th><th>Salary</th><th>Date</th><th>Gender</th></tr>");
$.each( res, function(key, row){
$("#myTable").append("<tr><td>"+row['emp_name']+"</td><td>"+row['position']+"</td><td>"+row['salary']+"</td><td>"+row['date_employed']+"</td><td>"+row['gender']+"</td></tr>");
});
},
error:function(res)
{
alert("Something Wrong");
}
});
}
$("#date_employed, #sex").change(function()
{
var txt = $("#txtSearch").val();
var drop = $("#date_employed").val();
var gender = $("#sex").val();
$.ajax({
url: 'search.php',
type: 'post',
data: {data1: txt, date_emp: drop, gen: gender},
datatype: 'json',
success:function(res)
{
$("#myTable tr").remove();
$("#myTable").append("<tr><th>Name</th><th>Position</th><th>Salary</th><th>Date</th><th>Gender</th></tr>");
$.each( res, function(key, row){
$("#myTable").append("<tr><td>"+row['emp_name']+"</td><td>"+row['position']+"</td><td>"+row['salary']+"</td><td>"+row['date_employed']+"</td><td>"+row['gender']+"</td></tr>");
});
},
error:function(res)
{
alert("Couldn't find any data!");
}
});
});
}
});
WHERE gender and drop are 2 drop lists that forming a search filters
When I change one of the drop lists, per example, when I choose the date equal to: this week I should see in table 2 rows.
But I can only see them in the network (in devTool), and at console tab I see the following error:
Uncaught TypeError: Cannot use 'in' operator to search for 'length' in
[{"id":"48","0":"48","emp_name":"Alexa","1":"Alexa","position":"Secretary","2":"Secretary","salary":"8000","3":"8000","date_employed":"2016-02-23","4":"2016-02-23","gender":"female","5":"female"}]
The PHP code when I change drop lists is:
if($date_emp == "week" && $gender == "specify")
{
$search = "SELECT * FROM employee WHERE (emp_name = :val OR position = :val
OR salary = :val OR date_employed = :val
OR gender = :val) AND date_employed > DATE_SUB(NOW(), INTERVAL 1 WEEK)";
$searchStmt = $conn->prepare($search);
$searchStmt->bindValue(":val", $val);
$searchStmt->execute();
$res = $searchStmt->fetchAll();
echo json_encode($res);
}
When you make an ajax call and expect the response to be a json you need to send a json header from the PHP
header('Content-Type: application/json');
echo json_encode($data);
Sending the json header from the PHP will turn the "res" param in your ajax to a json object and not a json string.
If you don't send the the header you need to parse the json string into a json object
var json = JSON.parse(res);
For some reason my php can't read the json object javascript has created.
Here is is printed to the console.
{
"product": {
"shipsTo": "Please choose …",
"accountExec": "Please choose …",
"product": "Please choose …",
"productSize": "Please choose …",
"qty": "",
"comments": ""
},
"billing": {
"billingName": "",
"billingAttn": "",
"billingAddress1": "",
"billingAddress2": "",
"billingCity": "",
"billingState": "",
"billingZip": "",
"billingPhone": "",
"billingFax": "",
"billingEmail": "asdf#asdf.com"
}
}
The only thing I have filled in is the billingEmail.
I get these values by collecting about 15 fields from a form and putting them in a javascript object
$(document).ready(function(){
$('#CBS_submit').on("click", function(){
//validate
//collect information
var orderInfo = {};
orderInfo.product = {};
orderInfo.billing = {};
orderInfo.product.shipsTo = $('#CBS_ship_to_select option:selected').val();
orderInfo.product.accountExec = $('#CBS_account_execs_select option:selected').val();
orderInfo.product.product = $('#CBS_product_select option:selected').val();
orderInfo.product.productSize = $('#CBS_product_size_select option:selected').val();
orderInfo.product.qty = $('#CBS_qty').val();
orderInfo.product.comments = $('#CBS_comments').val();
//capture textarea information if other is selected for
//shipsTo, product, productSize
if ( get_selected_id ('CBS_ship_to_select') == 4 ) {
orderInfo.product.shipsTo = $('#other_ship_to_text').val();
}
if ( get_selected_id ('CBS_product_select') == 4 ) {
orderInfo.product.product = $('#other_product_text').val();
}
if ( get_selected_id ('CBS_product_size_select') == 4 ) {
orderInfo.product.productSize = $('#other_product_size_text').val();
}
orderInfo.billing.billingName = $('#CBS_billing_name').val();
orderInfo.billing.billingAttn = $('#CBS_billing_attn').val();
orderInfo.billing.billingAddress1 = $('#CBS_billing_address1').val();
orderInfo.billing.billingAddress2 = $('#CBS_billing_address2').val();
orderInfo.billing.billingCity = $('#CBS_billing_city').val();
orderInfo.billing.billingState = $('#CBS_billing_state').val();
orderInfo.billing.billingZip = $('#CBS_billing_zip').val();
orderInfo.billing.billingPhone = $('#CBS_billing_phone').val();
orderInfo.billing.billingFax = $('#CBS_billing_fax').val();
orderInfo.billing.billingEmail = $('#CBS_billing_email').val();
var orderInfoJSON = JSON.stringify(orderInfo);
console.log(orderInfoJSON);
$.ajax({
type: "POST",
url: "queries/submit_order.php",
data: "order_info=" + orderInfoJSON,
dataType: "json",
success: function (data) {
console.log('test');
}
});
});
});
then request it on the php page and start putting it into html
<?php
$order_info = $_REQUEST['order_info'];
$order_info = json_decode($order_info, TRUE);
$msg = <<<EOD
<table style='width:600px; font-family:\"Helvetica\",\"Arial\", sans-serif; margin:15px' border="0">
accessing the variables like
{$order_info['product']['product']}
But for some reason, I get nothing submitted. Even though when I copy/paste the object
$order_info = '{"product":{"shipsTo":"Please choose …","accountExec":"Please choose …","product":"Please choose …","productSize":"Please choose …","qty":"","comments":""},"billing":{"billingName":"","billingAttn":"","billingAddress1":"","billingAddress2":"","billingCity":"","billingState":"","billingZip":"","billingPhone":"","billingFax":"","billingEmail":"asdf#asdf.com"}}';
it works
what am I doing wrong?
Thanks a million!
Sending it as a string might mess stuff up if it contains special characters. Try using this method instead:
$.ajax({
type: "POST",
url: "queries/submit_order.php",
data: {order_info: orderInfoJSON},
dataType: "json",
success: function (data) {
console.log('test');
}
});