I have a leaderboard where if you click on a name a popup is displayed : https://jsfiddle.net/pvwvdgLn/1/
In practice, I will pull the list of the leaderboard from a DB.What you see here in the list are static names of employees,just for reference. So,how do I assign names using data attributes and search for that name in the JSON?
There are various fields in the popup like: Name,Email,Date of birth etc which I want to display for the respective person whose name is clicked by the user.
I have below JSON which is fetching me the array which contains all these data of all the people in the list :
<?php
session_start();
$servername = "xxxxx";
$connectioninfo = array(
'Database' => 'xxxxxxxxxxxxx'
);
$conn = sqlsrv_connect($servername, $connectioninfo);
if (!$conn) {
echo 'connection failure';
die(print_r(sqlsrv_errors() , TRUE));
}
$q1 = "select top 10 *
from pointsBadgeTable
WHERE WeekNumber ='week51'
order by pointsRewarded desc";
$stmt = sqlsrv_query($conn, $q1);
if ($stmt == false) {
echo 'error to retrieve info !! <br/>';
die(print_r(sqlsrv_errors() , TRUE));
}
do {
while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
$result[] = $row;
}
}
while (sqlsrv_next_result($stmt));
sqlsrv_free_stmt($stmt);
sqlsrv_close($conn); //Close the connnectiokn first
//Set content type to json
header('Content-Type: application/json');
//Echo a json object to the browser
echo json_encode($result);
?>
As can be seen in the query,it fetches JSON for all the top10 ,whose names can be seen in the list.
the html and JS related to the popup is here : https://jsfiddle.net/woef5mn6/
How can I display the respective data in the popup from the JSON only for the person whose name is clicked ?
please help me.
I have edited your fiddle to show how your problem can be solved. This is just a simple solution. It needs to modified according to your requirement.
Here is the fiddle
I am creating the employee list from your JSON and populating the ordered list
function employeeList() {
$("#myOL").empty();
$.each(employee, function(i,o) {
$("#myOL").append("<li><mark>" + o.EmployeeName + "</mark><small>" + o.score + "</small></li>");
});
}
Then onclick of the individual employee, i am getting his details from JSON by his name and then populating the popup details (as a best practice here - you should get the employee details by calling a service through ajax using a unique identifier [employeeId] ):
function getEmployeeByName(name) {
var index = -1;
var filteredObj = employee.find(function(item, i) {
if(item.EmployeeName === name){
index = i;
}
});
return employee[index];
}
Hope this helps!
Related
i have a table 'class' with thier fee structure. i want to show fee amount if a particular class is selected by user.
i'm able to fetch only one value from database want ot show multiple value..
here is my db table:
here are my codes:-
fetch.js
$('#class').click(function(){
$.getJSON(
'fetch2.php',
'class=' + $('#class').val(),
function(result){
$('#tution_fee').empty();
$.each(result.result, function(){
$('#tution_fee').append('<option>'+this['tution_fee']+'</option>');
});
}
);
});
fetch.php
<?php
define('HOST','localhost');
define('USERNAME', 'root');
define('PASSWORD','');
define('DB','bethel');
$con = mysqli_connect(HOST,USERNAME,PASSWORD,DB);
$class = $_GET['class'];
$sql = "SELECT tution_fee FROM class WHERE class='$class'";
$res = mysqli_query($con,$sql);
$result = array();
while ($row = mysqli_fetch_array($res)) {
array_push($result,
array('tution_fee'=>$row[0])
);
}
echo json_encode(array('result'=>$result));
mysqli_close($con);
?>
first one is fetch.js and second fetch.php
here you can see the JS code that one value can be fetched from database but i want to fetch multiple value.
please help
i want to get cities of selected country i create one table of location with id,country and cities and get country through Json
var items="";
$.getJSON("get-data.php",function(data){
$.each(data,function(index,item)
{
items+="<option value='"+item.id+"'>"+item.country+"</option>";
});
$("#class_id").html(items);
});
$('select').on('change', function() {
a=this.value;
});
now i want to select cities when country is selected..
<?php
error_reporting(0);
$conn=mysql_connect('localhost', 'root', '') or die("Can't Connect With Local");
mysql_select_db('f_o_r',$conn) or die("Local DB Not Found");
$q = "SELECT DISTINCT country FROM location";
$sql = mysql_query($q) or die("query failed");
$data = array();
while($row = mysql_fetch_array($sql, true)){
$data[] = $row;
}
echo json_encode($data);
?>
You can populate your values as follows:
$.getJSON("get-data.php",function(data){
$.each(data,function(index,item)
{
$("#country_id").append('<option value="'+item.id+'">'+item.country+'</option>'); // It will append all values
}
}
And after selecting this you can select states on select of country list as follows:
Use post for this:
$("#country_id").change(function()
{
$.post('getstate.php',{country_id:$("#country_id").val()},function(data)
{
for(var i=0;i<data.length;i++)
{
$("#state_id").append('<option value="'+data[i].state_id+'">'+data[i].state_name+'</option>'); // It will append all values
}
});
});
And in getstate.php write the code to get states based on $_POST['country_id'].
Inorder to relate cities with country. add this code after removing $data = []
while($row = mysql_fetch_array($sql, true)){
$data1['country'] = $row['country'];
$citysql = "SELECT cities from location where country = '".$row['country']."'";
while($row1 = mysql_fetch_array($citysql,true))
{
array_push($data1['cities'],$row1['cities']);
}
array_push($data,array($data1['country'],$data1['cities']));
}
I think you can add column level to table location for remark the location type.
exp:
0 => country
1 => city
2 => ...
and your api may need to change:
[params]
parent_id: the parent id
level: look for level
[exp]
url: get-data.php?parent_id=6&level=1
then you may get US(id equal 6)'s all cities
your js need add change listener on country, when it is changed send a ajax to like
$('#country_id').change(function(){
$.post('get-data.php',{parent_id:$('#country_id').val(),level:1},function(data){
console.log(data);
//get your data cities do want you want
});
});
get-data.php => router /xxx/location method GET more restful
Is it possible to update the server-side JSON file using AJAX in bootstrap-table?
data-url="scripts/users.php"
I am using a PHP file to echo the output of the sql queries to the table.
First Name | Last Name | Category | Group
This works well, but I want to add 4 select tags each to filter a column. I have replicated the server-side JSON within users.php but this time it will echo the filtered rows to the JSON.
Can this be done? How can I switch to the filtered JSON?
NOTE: all this logic is within users.php (aside from the AJAX of course).
if (!empty($_POST['first_name'])) {
//code to create and return filtered JSON
} else if (!empty($_POST['last_name'])) {
//code to create and return filtered JSON
} else if (!empty($_POST['category'])) {
//code to create and return filtered JSON
} else if (!empty($_POST['group'])) {
//code to create and return filtered JSON
} else {
//code to create and return unfiltered JSON
/*THIS ALWAYS EXECUTES ONLOAD, BUT **I WANT IT TO GIVE WAY FOR THE FILTERED JSON AND ONLY REACTIVATE ONLOAD OR IF ALL FILTERS ARE REMOVED***/
}
UPDATE:
In my users.php code I have successfully been able to run each filtered query individually (depending on what is selected). When the page first loads the table is empty but present. Users must select at least one option for the table to output any data.
I am having issues letting the table (written in the .html page) know to switch to the filtered results while the filter is active.
Here is the code that resides in each of the if/else conditions:
$limit = $_GET['limit'];
$offset = $_GET['offset'];
fname = $_POST['first_name'];
if (!empty($_POST['first_name'])) { //filter by the selected name
//get TOTAL rows for PAGINATION
$stmt_TOTAL_ROWS = "SELECT first_name, last_name, category, group
. "\
n "
. "
FROM users
.
"\n"
.
"WHERE first_name ='$fname'";
$result_TOTAL_ROWS = mysqli_query($mysqli, $stmt_TOTAL_ROWS);
$num_rows_TOTAL_ROWS = mysqli_num_rows($result_TOTAL_ROWS);
$stmt = "SELECT first_name, last_name, category, group
. "\
n "
. "
FROM users
.
"\n"
.
"WHERE first_name ='$fname' ORDER BY first_name LIMIT $offset, $limit";
$result = mysqli_query($mysqli, $stmt);
$cart = array();
$i = 0; //index the entries
if ($num_rows_TOTAL_ROWS > 0) { //if table is populated...
// enter data of each row
while ($row = mysqli_fetch_assoc($result)) {
$cart[$i] = array(
"First Name" => htmlspecialchars($row['first_name']),
"Last Name" => htmlspecialchars($row['last_name']),
"Category" => htmlspecialchars($row['category']),
"Group" => htmlspecialchars($row['group']),
);
$i = $i + 1; //add next row
}
//encoding the PHP array
$json_server_pagination_data = array(
"total" => intval($num_rows_TOTAL_ROWS), // total rows in data
"rows" => $cart, //data
);
echo json_encode($json_server_pagination_data); // allow table to access the data
} else {
//do nothing . no data in sql query
}
}
I am trying to create a D3 line graph that will display a graph specific to the item that is selected in the drop-down menu. I have one script that queries my MySQL database and fills a drop-down menu with all of the correct options. From there, I want to click on an option and go to another page that creates a line graph based off of that selection. When I click on an option, I use json_encode to create a JSON object that should be compatible with D3.
I have another script that deals completely with drawing the graph and try to use d3.json to get the JSON object that is created when the specific selection is clicked. Whenever I try to load the graph page, it is completely blank. I am not sure if what I am trying to do is even possible. I have not tried including the drop-down in the same script as the one that creates the graph but do not think that I will be able to get the information from the database the same way.
Any guidance or suggestions would be greatly appreciated. I can post the code later if it is determined what I am trying to do is possible. Thanks!
EDIT:
This is the script that queries my database for the users that are put in the drop-down menu and then queries the database again for that selection's data. The drop-down menu has the desired result and the data is correctly echoed as well.
<?php
if (isset($_POST['name']))
{
$out = $_POST['name'];
$temp = explode(",", $out);
$populate_selection = "SELECT id, lastname, firstname FROM users WHERE id != '$temp[0]' ORDER BY lastname";
$out = $temp[1] . ', ' . $temp[2];
$student_hours = "SELECT ai_averages.user_id, ai_averages.title, ai_averages.hours FROM ai_averages INNER JOIN users ON ai_averages.user_id = users.id WHERE $temp[0] = ai_averages.user_id";
}
else
{
$temp[0] = " ";
$populate_selection = "SELECT id, lastname, firstname FROM users ORDER BY lastname";
$student_hours = "SELECT ai_averages.user_id, ai_averages.title, ai_averages.hours FROM ai_averages INNER JOIN users ON ai_averages.user_id = users.id WHERE $temp[0] = ai_averages.user_id";
$out = " ";
}
$result = $mysqli->query($populate_selection);
$option = "<option value= '{$temp[0]}'>$out</option>";
while($row = mysqli_fetch_assoc($result)) {
$option .= "<option value = '{$row['id']}, {$row['lastname']}, {$row['firstname']}'>{$row['lastname']}, {$row['firstname']} </option>";
}
if($student_results = $mysqli->query($student_hours))
{
$data = array();
for ($x = 0; $x < mysqli_num_rows($student_results); $x++)
{
//this array contains the data that I want in my graph
//the correct data is echoed every time that I click on the different choices
$data[] = mysqli_fetch_assoc($student_results);
}
echo json_encode($data, JSON_PRETTY_PRINT);
}
?>
<form id = "hello" method = "POST" >
<select name = "name" onchange = 'this.form.submit()'> <?php echo $option; ?> </select>
</form>
I then try and use d3.json("filename.php", etc) to get the information from the $data array but this has not worked.
Form a php page I am sending some value using json.
$result = mysql_query("SELECT * FROM user_info");
$i=1;
while($row = mysql_fetch_array($result, MYSQL_NUM)) {
if(is_array($row) && count($row)>0)
{
$res['user_name'.$i] = $row[1];
$res['user_email'.$i] = $row[2];
$res['gender'.$i] = $row[4];
$res['i'] = $i;
$i++;
}
}
echo json_encode($res);
I have no problem with this code.But in another page I want to get that data code follows
$.post(urlName, function(data) {
var obj = jQuery.parseJSON ( data );
$noOfUser = obj.i;
alert("No of user- "+$noOfUser);
for($i=0;$i<=$noOfUser;$i++)
{
$user_name = obj.user_name+$i;
$user_emai = obj.user_email+$i;
$gender = obj.gender+$i;
alert("User Name- "+$user_name);
alert("User Email- "+$user_emai);
alert("User Gender- "+$gender);
}
});
But the problem is when I am adding this obj.user_name+$i instead of simple obj.user_name it can't retrieve the data properly but I need to get those value how to do that?
What you are trying to do attempts to get the user_name member of obj and appending the value of $i. Since user_name is not defined, the script fails.
This is because in javascript to access a member of an object using a dynamically generated key you must use the [] accessor, so in your case, the following example should work.
$user_name = obj['user_name' + $i];