So I've been working on this code for awhile now and I've done a lot of debugging but can't figure this out. What I want to do is: if a checkbox is checked send a request to run a query on the mySQL database FROM items WHERE .class(of the checkbox) '<' this.value(of the checkbox again) then get the filtered results and then use my javascript to format it:
index.php:
<form>
<label><input type="checkbox" class="calories "name="calories" value="300">Less than 300</label><br>
<label><input type="checkbox" class="calories" name="calories" value="500">Less than 500</label><br>
</form>
<script>
$("input.calories:checkbox").on("change",function(){
if(this.checked){
var column = $(this).attr('class'); //The class determines which column of the table is called
var value = $(this).attr('value'); //Takes the numeric value from the selected box
console.log(column);
//$.post('showItems.php', {type: column});
//$.post('showItems.php', {value: value});
//Can we call the php code above to run a query using variables column and value?
//make a php function above and call it
// function below will run showItemss.php?c=column?v=value
$.ajax({
type: "POST",
url: "showItems.php" ,
data: { c: column,
v: value},
error: function(){console.log("error")},
success: function(data) {
console.log("success");
console.log(test);
console.log(filteredList);
</script>
Here is the PHP file showItems.php I'm calling (the relevant part):
//This array holds items from database.
$itemList = array();
//Connect and Select
$con = makeConnection($dbhost, $dbuser, $dbpass, $dbname);
//Get the value and type from the javascript below
//If the type is null display the whole table
$c = $_POST['c'];
//echo $c;
//$v = mysqli_real_escape_string($con,$v);
//$type = $_POST['value'];
if($c==null){
$query = "SELECT * FROM items";
}
else{
$v = $_POST['v'];
$query = "SELECT * FROM items WHERE ".$c."< ".$v."";
}
$result = mysqli_query($con, $query);
//Collect data from all items
while($row = $result->fetch_assoc())
{
$tempItem = new Item($row['itemID'], $row['itemName'], $row['price'], $row['description'], $row['calories'], $row['protein'], $row['choles'], $row['sodi'], $row['picLink']);
$itemList[] = $tempItem;
}
echo json_encode($query);
?>
<script>
var test = <?php echo json_encode($query); ?>;
var filteredList = <?php echo json_encode($itemList); ?>;
</script>
So I want this code to be run every time I click a checkbox in my Index.php file so I can get the updated filtered items, $itemList, but I cannot figure out how to do this. Something I've done to test this is store my php values as javascript variables, Include showItems.php then console.log the variables from ShowItems.php in Index.php, and the query isn't being updated upon click which makes sense I guess. In the AJAX success function 'data' contains the entire HTML source with an updated query, but I can't figure out how use only the specific code I need in the success function. Any ideas at all would be helpful.
Try doing this:
Go from on("change",...) to on("click",...)
Also try using instead of this.checked, $(this).prop("checked") which will return you true or false depending on wether the checkbox is checked or not.
You might want to change either your selector or your checkbox classes because both are the same, and can give you undesired functionality in order to get your values when you click on a checkbox, since the selector finds you both checkboxes.
Hope this ideas can get you closer where you want to be.
Cheers
In database table I have age column in which have more than 50 rows.
id age
1 45
2 41
3 09
......
60 11
I always have 10 keys in array ,
<?php
$arr = array(0,0,0,0,0,0,0,0,0);
echo json_encode($arr)."<br>";
$con = mysqli_connect('127.0.0.1','app_user2','qwe123','test');
$select="select age from ad;";
$res = mysqli_query($con, $select);
while ($row=$res->fetch_assoc()) {
$arr=array_slice($arr,1,9);
//$arr[]=$row['id'];
$arr[]=array($i++, (int)$row['age']);
echo json_encode($arr)."<br>";
}
?>
I'm getting following output=>
[0,0,0,0,0,0,0,0,0,[0,45]]
[0,0,0,0,0,0,0,0,[0,45],[1,41]]
[0,0,0,0,0,0,0,[0,45],[1,41],[2,11]]
[0,0,0,0,0,0,[0,45],[1,41],[2,11],[3,21]]
[0,0,0,0,0,[0,45],[1,41],[2,11],[3,21],[4,44]]
.............................
[[1,41],[2,11],[3,21],[4,44],[5,13],[6,15],[7,12],[8,7],[9,14],[10,11]]
........................
Now when i execute
echo json_encode($arr)
in JavaScript i'm getting only last 10 values. i want to execute all the rows one by one. how can i do that? Is it possible?please help.
here is my script code
<script type="text/javascript">
var data=[];
data=<?php echo json_encode($arr); ?>;
document.write(data);
</script>
That's because your string isn't in a valid json format. Then you get output of just one line. You may consider build in a correct way like:
$myArray = []
while ($row=$res->fetch_assoc()) {
$arr=array_slice($arr,1,9);
//$arr[]=$row['id'];
$arr[]=array($i++, (int)$row['age']);
array_push($myArray, $arr);
}
then:
data=<?php echo json_encode($myArray ); ?>;
(PS.: hardcode server side code in javascript isn't a good practice)
On each run through the loop, you assign $arr using array_slice and assign 9 elements to it (starting from element 1, length 9). Later in the loop iteration, you add a new element to the end of the array with a $arr[] = ... assignment.
Since you are assigning the array to have 9 elements and then adding 1 element on each iteration, it will always end up being 10 elements long at most, and no more.
I am trying to add a pair of variables 'product_name' and 'photos' (which is the URL of the car photo) into an array. I have a friend that said my efforts are failing because I am pushing into a flat array. I've looked to see how to do this with variable pairs and am stymied. He had suggested pushing row into $isotopecubes instead of how I have it below, but when I try I am getting null values. I need to be able to access val.photo and val.product_name in my javascript call in my php file that references this ajax code.
Note: if I just use:
array_push($isotopecubes, $row['photo']);
I get back the following JSON response on my console:
"/images/photos/cars/vw/14_Virginia_L.jpg",
"/images/photos/cars/mazda/2013/14hybrid.jpg"
so I know I am reaching the database and getting the correct values. Here is my ajax code:
<?php
include '../../global_config.php';
include 'config.php';
if ($_GET['action'] == 'get-images') {
$selectSql = "SELECT product_name, photo FROM cars WHERE publish = 1;";
$isotopecubeResult = $db->query($selectSql);
$isotopecubes = array();
while($isotopecubeResult->fetchInto($row, DB_FETCHMODE_ASSOC)) {
array_push($isotopecubes, $row['photo'], $col['product_name']);
// $isotopecubes = array_merge($isotopecubes, $row['photo']);
}
echo json_encode($isotopecubes);
}
?>
It can be done by
<?php
include '../../global_config.php';
include 'config.php';
if ($_GET['action'] == 'get-images') {
$selectSql = "SELECT product_name, photo FROM cars WHERE publish = 1;";
$isotopecubeResult = $db->query($selectSql);
$isotopecubes = array();
while($isotopecubeResult->fetchInto($row, DB_FETCHMODE_ASSOC)) {
//array_push($isotopecubes, $row['photo'], $col['product_name']);
// $isotopecubes = array_merge($isotopecubes, $row['photo']);
$isotopecubes[] = array('product_name' => $row['product_name'], 'photo' => $row['photo']);
}
echo json_encode($isotopecubes);
}
?>
Now you will be able to get value through val.product_name and val.photo
I'm using bootstrap's typeahead and I'm wondering how I can return a JSON array with multiple pieces of data for each result.
For example, I want to be able to return two pieces of data for each result, the name and the description. How would this be done?
The only way to do this is using "Multiple Datasets" as mentioned in the following link:
http://twitter.github.io/typeahead.js/examples/#multiple-datasets
You'll have to create 2 different sources: one for the "name" and one for the "description".
In case you don't want to search using the "description", then you can use the following code:
http://twitter.github.io/typeahead.js/examples/#custom-templates
You'll be able to search using the "name" and the description will be displayed next to the name.
This code will make the output to show result from two columns when you type. You have to change only in search.php code, not any other place. Try it and give feedback.
$key=$_GET['key'];
$mysqli = new mysqli("localhost", "root", "", "yourbd");
/* check connection */
if ($mysqli->connect_errno) {
printf("Connect failed: %s\n", $mysqli->connect_error);
exit();
}
$mysqli->set_charset("utf8");
$result = $mysqli->query("select * from yourtb where yourcolumn LIKE '%{$key}%'");
if (!$result) {
die(mysqli_error($mysqli));
}
$rows = array();
while($r = mysqli_fetch_array($result)) {
$rows[] = $r['col1']. ' - ' . $r['col2'];
}
echo json_encode($rows);
I would like to replicate this highcharts column graph: http://jsfiddle.net/gh/get/jquery/1.9.1/highslide-software/highcharts.com/tree/master/samples/highcharts/demo/column-drilldown/
I'm pulling my data from a table and it looks like this.
I want the Job_Num on the x-axis where brands are in the fiddle, PercentofBudgetedHrs would be the brandsData. Now when you click a job number, it drills down to departments and shows their percentage of budgeted hrs.
I have the first part working, but I'm using different code like so: http://jsfiddle.net/98Fuq/4/
Here is what I changed in that code:
$sql = "SELECT * FROM view_percentof_budgeted WHERE PercentofBudgetedHrs < 1000 && PercentofBudgetedHrs IS NOT NULL";
$result = mysqli_query($dbc3, $sql);
while($row = mysqli_fetch_assoc($result)) {
$jobNum[] = $row['Job_Num'];
$jobData[$row['Job_Num']] = $row['PercentofBudgetedHrs'];
$jobDrillData[$row['Job_Num']][] = $row;
}
The part I changed in the JS:
var colors = Highcharts.getOptions().colors,
categories = [<?php echo join($jobNum, ',') ?>],
name = '% of budgeted hours',
level = 0,
data = [
<?php echo join($jobData, ',') ?>,
];
function setChart(name, categories, data, color, level) {
chart.xAxis[0].setCategories(categories);
chart.series[0].remove();
chart.addSeries({
name: name,
data: data,
level: level,
color: color || 'red'
});
}
How do I go about doing it the way that first fiddle I posted does it? I like my method of pulling the data from a table so I don't want to use a tsv, I'm just confused on the drilldown part. I've looked at examples but can't seem to figure it out.
Instaed of using join() I advice to prepare correct strucutre of arrays in php, then use json_encode() including JSON_NUMERIC_CHECK flag. As a result you can get this json by $.getJSON and put in highcharts.