How to check the condition in the jquery? - php

I am create the js tree to show the folder path name, and my problem is how to check the condition if database table status is 0(inactive) then will show the line-through in the js tree. Else table status is 1(active) just back to normal. Below is my coding:
<?php
$folderData = mysqli_query($mysql_con,"SELECT * FROM filing_code_management");
$folders_arr = array();
while($row = mysqli_fetch_assoc($folderData)){
$parentid = $row['parentid'];
if($parentid == '0') $parentid = "#";
$selected = false;$opened = false;
if($row['id'] == 2){
$selected = true;$opened = true;
}
$folders_arr[] = array(
"id" => $row['id'],
"parent" => $parentid,
"text" => $row['name'] . ' ' . "<span id='category'>". $row['category']."</span>",
"category" => $row['category'],
"status" => $row['status'], // status 0 is inactive, status 1 is active
"state" => array("selected" => $selected,"opened"=>$opened)
);
}
?>
<script style="text/javascript">
var StrikeNodes = function(nodelist) {
var tree = $('#folder_jstree').jstree(true);
nodelist.forEach(function(n) {
tree.get_node(n.id).a_attr.style = "text-decoration:" + getStrike(parseInt(n.text.substr(0, 3), 10));
tree.redraw_node(n.id); //Redraw tree
StrikeNodes(n.children); //Update leaf nodes
});
};
var getStrike = function(i) {
if (status = '0' ) {
return "line-through;";
} else {
return "";
}
};
$('#folder_jstree').bind('load_node.jstree', function(e, data) {
var tree = $('#folder_jstree').jstree(true);
StrikeNodes(tree.get_json());
});
</script>
Now my output show all the all the line-through in the js tree, not detect which is active or inactive.
My working JSFiddle code here: https://jsfiddle.net/ason5861_cs/9x0dsotz/3/
Hope someone can guide me which part I am getting wrong.

looking at your code. you are not comparing the status it should be status == '0' instead of status = '0'
also there is available option that jstree provided. data option this can be anything you want. it is metadata you want attached to the nod. you will be able to access and modify it any time later - it has no effect on the visuals of the node.
[{
"id": "1",
"parent": "#",
"text": "100 PENTADBIRAN <span id='category'>JTM<\/span>",
"category": "JTM",
"data": { "status": 0 },
"state": {
"selected": false,
"opened": false
}
}]
var StrikeNodes = function(nodelist) {
var tree = $('#folder_jstree').jstree(true);
nodelist.forEach(function(n) {
tree.get_node(n.id).a_attr.style = "text-decoration:" + getStrike(n.data.status);
tree.redraw_node(n.id); //Redraw tree
StrikeNodes(n.children); //Update leaf nodes
});
};
var getStrike = function(status) {
if (status == 0) {
return "line-through;";
}
return "";
};
here's i've edited your fiddle https://jsfiddle.net/Hafizu/1xt7bhem/11/

Related

display ajax information under input field

I tried to develop an ajax to display some information.
My ajax works fine but it do not display the information under the input field.
Do you have any idea to resolve that ?
thank you.
$content .= HTML::inputField('suppliers_id', $suppliers_id . ' ' . $suppliers_name, 'id="ajax_suppliers_id" list="supplier_list" class="form-control"', null, null, null);
$content .= '<datalist id="supplier_list"></datalist>';
$suppliers_ajax = this->link('ajax/suppliers.php');
<script>
window.addEventListener("load", function(){
// Add a keyup event listener to our input element
document.getElementById('ajax_suppliers_id').addEventListener("keyup", function(event){hinter(event)});
// create one global XHR object
// so we can abort old requests when a new one is make
window.hinterXHR = new XMLHttpRequest();
});
// Autocomplete for form
function hinter(event) {
var input = event.target;
var ajax_suppliers_id = document.getElementById('ajax_suppliers_id');
// minimum number of characters before we start to generate suggestions
var min_characters = 0;
if (!isNaN(input.value) || input.value.length < min_characters ) {
return;
} else {
window.hinterXHR.abort();
window.hinterXHR.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var response = JSON.parse( this.responseText );
ajax_suppliers_id.innerHTML = "";
response.forEach(function(item) {
// Create a new <option> element.
var option = document.createElement('option');
option.value = item;
ajax_suppliers_id.appendChild(option);
});
}
};
window.hinterXHR.open("GET", "{$suppliers_ajax}?q=" + input.value, true);
window.hinterXHR.send()
}
}
</script>
my ajax request called across the input field, I use to display information:
if (isset($_GET['q'])) {
$terms = HTML::sanitize(strtolower($_GET['q']));
$Qcheck = $this->Db->prepare('select distinct suppliers_id as id,
suppliers_name as name
from :table_suppliers
where suppliers_name LIKE :terms
limit 10;
');
$Qcheck->bindValue(':terms', '%' . $terms . '%');
$Qcheck->execute();
$list = $Qcheck->rowCount();
if ($list > 0) {
$array = [];
while ($value = $Qcheck->fetch()) {
$array[] = $value;
}
# JSON-encode the response
$json_response = json_encode($array); //Return the JSON Array
# Return the response
echo $json_response;
}
example of response I can see on sa keywords:
[{"id":"3","name":"Samsug"}]
You are appending new options inside input but you need to append it inside datalist .Also , option.value = item.name will give you result has [Object object] that's why you need to specify field i.e : id ,name to access same elements . i.e : item.name .
Demo Code :
var ajax_suppliers_id = document.getElementById('supplier_list');//daatlist id
var response = [{
"id": "3",
"name": "Samsug"
},{
"id": "3",
"name": "Samsug1"
},{
"id": "3",
"name": "Samsug2"
}];
ajax_suppliers_id.innerHTML = "";
response.forEach(function(item) {
// Create a new <option> element.
var option = document.createElement('option');
option.value = item.name;//get name
ajax_suppliers_id.appendChild(option);
});
<input list="supplier_list" class="form-control" id="ajax_suppliers_id">
<datalist id="supplier_list"></datalist>

Populate group data to a particular series on Highcharts

Trying to group tow columns and and populate it as a particular series on highcharts. my code not grouping columns, And showing all data as a single series.
$query = $db->Prepare("SELECT class, SUM(marks), DATE(date_column) as
dates FROM classes GROUP BY class,DATE(date_column)");
$query->execute();
while ( $row = $query->fetch(PDO:: FETCH_ASSOC)) {
$date = $row['dates'];
$dates[] = $row['dates'];
$class[] = $row['class'];
$marks[] = $row['SUM(marks)'];
$output[] = array($date,(int)$marks);
}
echo json_encode(array('date'=>$dates,'marks'=>$marks, 'name' => $class));
JS
<script>
$(document).ready(function () {
$(function() {
$.getJSON('data.php', function(data) {
// Create the chart
Highcharts.chart('container', {
title: {
text: 'class Marks'
},
xAxis: {
categories: data.dates
},
series : [{
"name" : data.name,
"data": data.marks
}],
});
});
});
});
</script>
Table
Expected output in JSFiddle
data response
date: ["2019-02-07", "2019-02-09", "2019-02-12", "2019-02-08", "2019-02-12",
"2019-02-13", "2019-03-13",…]
marks: ["45", "166", "78", "64", "64", "627", "87", "352"]
name: ["claas 1", "claas 1", "claas 1", "class 2", "class 2", "class 2", "class 3", "class 3"]
By seeing your fiddle the expected output you want for HighCharts is as follow:
1: Category Data:
It should be an array of dates.
Make sure you remove duplicates and order them in ascending/descending order whichever you want, to see a continuous graph.
"categories":["2019-02-07", "2019-02-08", "2019-02-09", "2019-02-12", "2019-02-13", "2019-02-14"]
2: Series Data:
It would be an array of object, where each object contains two properties name and data.
Data should have n no of values if your categories array has n values and each corresponds to same index.
As we don't have data for each date for each class, we would add 0 there.
So data would look like
"series":[
{
"name":"class 1",
"data":[45,0,166,78,0,0]
},
{
"name":"class 2",
"data":[0,64,0,64,627,0]
},
{
"name":"class 3",
"data":[0,0,0,0,87,352]
}
]
Final Fiddle which can be achieved by PHP using below code:
$arrDates = [];
$arrClass = [];
$arrData = [];
while ( $row = $query->fetch(PDO:: FETCH_ASSOC)) {
$arrDates[] = $row['dates'];
$arrClass[] = $row['class'];
$arrData[$row['class'] . ':' . $row['dates']] = $row['marks']; // to identify for which date & class this marks belong to, we can directly search for index.
}
$arrDates = array_unique($arrDates);
sort($arrDates);
$arrClass = array_unique($arrClass);
// Create series data
$arrSeriesData = [];
foreach($arrClass as $strClass){
$tempArr = ['name' => $strClass];
foreach($arrDates as $strDate){
$tempArr['data'][] = isset($arrData[$strClass . ':' . $strDate]) ? intval($arrData[$strClass . ':' . $strDate]) : 0;
}
$arrSeriesData[] = $tempArr;
}
$response = ['categories' => $arrDates, 'series' => $arrSeriesData];
echo json_encode($response);
Output:
{"categories":["2019-02-07","2019-02-08","2019-02-09","2019-02-12","2019-02-13","2019-02-14"],"series":[{"name":"class 1","data":[45,0,166,78,0,0]},{"name":"class 2","data":[0,64,0,64,627,0]},{"name":"class 3","data":[0,0,0,0,87,352]}]}
Update your javascript code to reflect the above
$(document).ready(function() {
$(function() {
$.getJSON('data.php', function(data) {
// Create the chart
Highcharts.chart('container', {
title: {
text: 'class Marks'
},
xAxis: {
categories: data.categories
},
series: data.series,
});
});
});
});

Convert Ajax value to Another State

I have spent hours looking for help with returning to another text ini script from json encode. I have a Json_Encode output with value
[
{"JumStatus":3,"status_ppid":"1"},
{"JumStatus":4,"status_ppid":"2"},
{"JumStatus":1,"status_ppid":"3"},
{"JumStatus":1,"status_ppid":"6"}
]
url: "_DEFINE_GET/_GetData.php",
method: "GET",
success: function(data) {
console.log(data);
var sta = [];
var jum = [];
for(var i in data) {
sta.push(data[i].status_ppid);
jum.push(data[i].JumStatus);
}
var chartdata = {
labels: sta,
datasets: [{
backgroundColor: [
"#2ecc71",
"#f1c40f",
"#3498db",
"#ff5722",
"#34495e",
'#009688',
"#e91e63"
],
hoverBackgroundColor: [
'rgba(0,255,0,0.3)',
'rgba(255,255,0,0.3)',
'rgba(0,0,255,0.3)',
'rgba(255,0,0,0.3)',
'rgba(192,192,192,0.6)',
'rgba(42,176,99,0.63)',
'rgba(255,0,0,0.3)',
],
data: jum,
}]
};
And my label in labels: sta, is output [1,2,3,6]
But i want to convert that output to another state when in php we use
if ($status_ppid=="1" ) { $status_ppid=="Application"; }
elseif ($status_ppid=="2" ) { $status_ppid=="Proccess"; }
elseif ($status_ppid=="3" ) { $status_ppid=="Staff Validation"; }
elseif ($status_ppid=="4" ) { $status_ppid=="Analys Validation"; }
elseif ($status_ppid=="5" ) { $status_ppid=="Manager Validation"; }
elseif ($status_ppid=="6" ) { $status_ppid=="Done"; }
And my question how to convert like that in Javascript ajax like in PHP?
My Expected value is after change the value but i dont know how to change the value ini script
label is output ['Application','Proccess,Staff','Validation','Done']
Need Help master
I am beginner in php
I think you should create method for convert status like this
function convertStatus(id) {
var status = "";
if (id == '1') {
status = "Application";
} else if (id == '2') {
status = "Proccess";
} else if (id == '3'){
status = "Staff Validation";
} else if (id == '4'){
status = "Analys Validation";
} else if (id == '5'){
status = "Manager Validation";
} else if (id == '6'){
status = "Done";
}
return status;
}
And you call the method before push to array
sta.push(convertStatus(data[i].status_ppid));

Algolia Geo Search Not Working

I am having some trouble with Algolia's geo search feature which was working properly before. Here is the record of interest.
I also had that indexed as described by the doc in order for me to sort it by the nearest distance:
'attributesToIndex' => ['name', 'description', 'geo']
In my client script:
let settings = {
aroundLatLng: '10.309813,123.893154',
getRankingInfo: true,
aroundRadius: 2000
};
index.search(keyword, settings, (err, data) => {
console.log(data);
});
But this gives me 0 hit. Notice the aroundLatLng value -- its the same value from the record of interest.
Am I missing something here?
I have implemented same requirement in node.js as per given in document and its working fine.
Here i am copying my whole code. Hopefully it may help you.
Code
/*
I have used async.water model to create the setting of the index and then searching data as per given parameter. few function is custom so no need to bother about that. read each line patently.
*/
try {
var self = this;
var post = req.body;
var user_id = post.user_id;
var created_mode = post.user_mode == 'requester' ? 'provider' : 'requester';
var kword = post.kword;
var geo = post.geo_loc;
var aroundLatLng = post.aroundLatLng;
var aroundRadius = !cmnFn.empty(post.radious) ? post.radious : 4500;
var hitsPerPage = !cmnFn.empty(post.hitsPerPage) ? post.hitsPerPage : 20;
var offset = !cmnFn.empty(post.offset) ? post.offset : 0;
var length = !cmnFn.empty(post.length) ? post.length : 50;
var budget_from = !cmnFn.empty(post.budget_from) ? post.budget_from : 0;
var budget_to = !cmnFn.empty(post.budget_to) ? post.budget_to : 0;
var day_preference = !cmnFn.empty(post.day_preference) ? post.day_preference : '';
var time_preference = !cmnFn.empty(post.time_preference) ? post.time_preference : '';
var start_date = !cmnFn.empty(post.start_date) ? post.start_date : '';
job_index is index created on Algolia
var job_index = algClient.initIndex('jobs');
var cond = {};
If you are using facet & filter then you need to use filter key to execute your condition same as you may have done in sql using where clouse
cond.filters = 'created_mode:"' + created_mode + '" AND (NOT user_id:"' + user_id + '")';
// Query which need to be search
if (!cmnFn.empty(kword)) {
cond.query = !cmnFn.empty(post.kword) ? post.kword : '';
}
if ((!cmnFn.empty(budget_from) && !cmnFn.empty(budget_to)) && budget_from > 0) {
cond.filters += ' AND min_charge: ' + budget_from + ' TO ' + budget_to;
}
if (!cmnFn.empty(day_preference)) {
cond.filters += ' AND day_preference:"' + day_preference + '"';
}
if (!cmnFn.empty(time_preference)) {
cond.filters += ' AND time_preference:"' + time_preference + '"';
}
if (!cmnFn.empty(start_date) && (new Date(start_date)).getTime() > 0) {
cond.filters += ' AND start_date:"' + start_date + '"';
}
Here i am setting aroundLatLng to get data nearest to far
/*
Do not fogot one thing, before using geo search, your records must have _geoloc key having following format
"_geoloc": {
"lat": 40.639751,
"lng": -73.778925
}
*/
// Around geo search by given lat lng
if (!cmnFn.empty(aroundLatLng) && !cmnFn.empty(aroundLatLng.lat)) {
cond.aroundLatLng = aroundLatLng.lat + ', ' + aroundLatLng.lng;
if (!cmnFn.empty(aroundRadius) && cond.aroundRadius > 0) {
cond.aroundRadius = aroundRadius;
}
}
// total number of searched record
if (!cmnFn.empty(hitsPerPage)) {
cond.hitsPerPage = hitsPerPage;
}
// Record starting position
if (!cmnFn.empty(offset)) {
cond.offset = offset;
}
// Page Limitation
if (!cmnFn.empty(length)) {
cond.length = length;
}
// Don't show attributesToHighlight in result set
cond.attributesToHighlight = false;
/*
restrictSearchableAttributes: List of object key, where to search in given list defined in searchableAttributes
*/
cond.restrictSearchableAttributes = [
'user_id',
'title',
'description',
'_geoloc'
];
/*
It will return raning info of result when search come under geo search
Following output will return
"_rankingInfo": {
"nbTypos": 0,
"firstMatchedWord": 0,
"proximityDistance": 0,
"userScore": 31,
"geoDistance": 9, // Calculated distance between data geolocation given in _geoloc and search criteria in aroundLatLng
"geoPrecision": 1,
"nbExactWords": 0,
"words": 1,
"filters": 0,
"matchedGeoLocation": {
"lat": 28.5503,
"lng": 77.2501,
"distance": 9
}
}
*/
cond.getRankingInfo = true;
async.waterfall([
function (callback) {
job_index.setSettings({
'attributesForFaceting': ['user_id', 'created_mode', 'min_charge', 'day_preference', 'time_preference', 'start_date'],
/*
searchableAttributes: List of object key , where to search
eg: ['title', 'description']
Like in sql: Where title='your searched text' AND description='your searched text'
_geoloc is reserved keyword of algolia which will used to search geo location
*/
searchableAttributes: [
'title',
'description',
'user_id',
'_geoloc'
],
/*
attributesToRetrieve: Here you can specify list of key name which you want to retrive
eg: ['name','address','age']
Like in sql: Select name, address, age
*/
attributesToRetrieve: [
'*'
]
}).then(() => {
return callback(null, 'success');
});
}
], function (err, results) {
if (err) {
console.log('error: ' + err);
}
job_index.search(cond).then(results => {
if (results.nbHits > 0) {
var rows = new Array();
for (i in results.hits) {
var row = {};
var item = results.hits[i];
var user_info = {};
user_info = item.user_info;
// Get distance and calculate
if (!cmnFn.empty(item._rankingInfo)) {
item.distance = cmnFn.meterToKM(item._rankingInfo['geoDistance']);
} else {
let loc = {
geoLoc_1: { latitude: aroundLatLng.lat, longitude: aroundLatLng.lng },
geoLoc_2: { latitude: item._geoloc.lat, longitude: item._geoloc.lng }
}
cmnFn.getDistance(loc, function (distance) {
item.distance = distance
})
}
/* self.isFav({ user_id: item.user_id, job_id: item.job_id }), function (err, flag) {
item.is_favorite = flag;
}; */
self.isFav({ user_id: item.user_id, job_id: item.job_id }).then(function (flag) {
item.is_favorite = flag;
}, function (err) {
item.is_favorite = false;
});
if (cmnFn.empty(item.currency)) {
item.currency = "₹";
}
//Delete few key from object which does not need to send in response
delete item['user_info'];
delete item['objectID'];
delete item['_geoloc'];
delete item['_rankingInfo'];
row.job_info = item;
row.user_info = user_info;
rows.push(row);
}
info = { status: 1, message: util.format(lang.TOTAL_RECORD_FOUND, results.nbHits), data: rows };
cmnFn.showMsg(res, info);
} else {
info = { status: 0, message: lang.RECORD_NOT_FOUND, data: null };
cmnFn.showMsg(res, info);
}
}).catch(err => {
console.log(err);
info = { status: 0, message: lang.RECORD_NOT_FOUND, data: null };
cmnFn.showMsg(res, info);
});
//res.end('' + JSON.stringify(results));
});
} catch (error) {
info = { status: 0, message: lang.RECORD_NOT_FOUND, data: null };
cmnFn.showMsg(res, info);
}
My bad. Malformed indexed data for _geoloc. Should be keyed with lat and lng

Ext Tree, Data is displayed in console, but does not display on page

My data is displayed in console, but does not display in ExtJs tree?
My php file
$data = array();
$sql = "";
if (!isset($_POST['node'])) {
// first select the top node that have no parent
$sql = "SELECT id_no,value_data FROM extjs_tree WHERE parent IS NULL";
} else {
// select data with parent_id = $_POST['node']
$sql = "SELECT id_no, value_data FROM extjs_tree WHERE parent = '". $_POST['node'] ."'";
}
$q = mysql_query($sql);
while ($r = mysql_fetch_array($q)) {
// check if have a child node
$qq = mysql_query("SELECT id_no, value_data FROM extjs_tree WHERE parent = '". $r['id'] ."'");
if (mysql_num_rows($qq) > 0) {
// if have a child
$r['leaf'] = false;
$r['cls'] = 'folder';
} else {
// if have no child
$r['leaf'] = true;
$r['cls'] = 'file';
}
$data[] = $r;
}
echo json_encode($data);
My JS file
Ext.require([
'Ext.tree.*',
'Ext.data.*',
'Ext.tip.*'
]);
Ext.onReady(function() {
Ext.QuickTips.init();
var store = Ext.create('Ext.data.TreeStore', {
proxy: {
type:'ajax',
actionMethods:'post',
url:'get-nodes.php'
},
root: {
text: 'Root Node',
id: 'root_node',
expanded: true
},
folderSort: true,
sorters: [{
property:'text',
direction:'ASC'
}]
});
var tree = Ext.create('Ext.tree.Panel', {
store: store,
renderTo: 'tree_el',
height: 300,
width: 250,
title: 'Products Display'
});
});
I am getting the tree properly, I can see the data in the console. But I cannot see ExtJs displaying the values??
My present result
My expected result should be
In your case you can also add following field to your store:
{
name: 'text',
mapping: 'value'
}
Every item of response has to have text field in it. As I can see from your request-response images You don't send text field. Response should be looking like the following one:
[{
"id": 2,
"text": "Fruits", // this field is required
...
},
...
]

Categories