how to get city by selected country using mysql in php - javascript

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

Related

Get data from database using php,ajax

I have a simple section in which I am displaying data from the database, my database looks like this.
Now I have four buttons looks like this
When a user clicks one of the above buttons it displays this
So now when user eg select construction and next select eg Egypt' in the console and clicks buttonconfirmdisplays [855,599075], user can select multiple countries, this works as expected forconstruction ,power,oil`,
Now I want if user eg clicks All available industries button in those four buttons and next select eg Egypt and click confirm it should display
the sum of egypt total projects in construction, oil, power sector 855+337+406 =1598 and the sum of total budgets in both sectors 1136173
Here is my solution
HTML
<div id="interactive-layers">
<div buttonid="43" class="video-btns">
<span class="label">Construction</span></div>
<div buttonid="44" class="video-btns">
<span class="label">Power</span></div>
<div buttonid="45" class="video-btns">
<span class="label">Oil</span></div>
<div buttonid="103" class="video-btns">
<span class="label">All available industries</span>
</div>
</div>
Here is js ajax
$("#interactive-layers").on("click", ".video-btns", function(){
if( $(e.target).find("span.label").html()=="Confirm" ) {
var selectedCountries = [];
$('.video-btns .selected').each(function () {
selectedCountries.push( $(this).parent().find("span.label").html() ) ;
});
if( selectedCountries.length>0 ) {
if(selectedCountries.indexOf("All available countries")>-1) {
selectedCountries = [];
}
} else {
return;
}
var ajaxurl = "";
if(selectedCountries.length>0) {
ajaxurl = "data.php";
} else {
ajaxurl = "dataall.php";
}
$.ajax({
url: ajaxurl,
type: 'POST',
data: {
countries: selectedCountries.join(","),
sector: selectedSector
},
success: function(result){
console.log(result);
result = JSON.parse(result);
$(".video-btns").each(function () {
var getBtn = $(this).attr('buttonid');
if (getBtn == 106) {
var totalProjects = $("<span class='totalprojects'>"+ result[0] + "</span>");
$(this).append(totalProjects)
}else if(getBtn ==107){
var resultBudget = result[1]
var totalBudgets = $("<span class='totalbudget'>"+ '&#36m' +" " + resultBudget +"</span>");
$(this).append( totalBudgets)
}
});
return;
}
});
}
});
Here is php to get all dataall.php
$selectedSectorByUser = $_POST['sector'];
$conn = mysqli_connect("localhost", "root", "", "love");
$result = mysqli_query($conn, "SELECT * FROM meed");
$data = array();
$wynik = [];
$totalProjects = 0;
$totalBudget = 0;
while ($row = mysqli_fetch_array($result))
{
if($row['Sector']==$selectedSectorByUser ) {
$totalProjects+= $row['SumofNoOfProjects'];
$totalBudget+= $row['SumofTotalBudgetValue'];
}
}
echo json_encode([ $totalProjects, $totalBudget ] );
exit();
?>
Here is data.php
<?php
$selectedSectorByUser = $_POST['sector'];
$countries = explode(",", $_POST['countries']);
//var_dump($countries);
$conn = mysqli_connect("localhost", "root", "", "meedadb");
$result = mysqli_query($conn, "SELECT * FROM meed");
$data = array();
$wynik = [];
$totalProjects = 0;
$totalBudget = 0;
while ($row = mysqli_fetch_array($result))
{
if($row['Sector']==$selectedSectorByUser && in_array($row['Countries'],$countries ) ) {
// array_push($data, $row);
$totalProjects+= $row['SumofNoOfProjects'];
$totalBudget+= $row['SumofTotalBudgetValue'];
}
}
// array_push($wynik, $row);
echo json_encode([ $totalProjects, $totalBudget ] );
//echo json_encode($data);
exit();
?>
Now when the user clicks All available industries btn and selects a country I get [0,0] on the console.
What do I need to change to get what I want? any help or suggestion will be appreciated,
in you dataAll.php
If you have select All available industries
you shold not check for sector because you need all sector (eventually you should check for countries )
so you should avoid the check for this condition
<?php
$conn = mysqli_connect("localhost", "root", "", "love");
$result = mysqli_query($conn, "SELECT * FROM meed");
$data = [];
$wynik = [];
$totalProjects = 0;
$totalBudget = 0;
while ($row = mysqli_fetch_array($result)) {
$totalProjects += $row['SumofNoOfProjects'];
$totalBudget += $row['SumofTotalBudgetValue'];
}
echo json_encode([$totalProjects, $totalBudget]);
You can use the SQL JOIN operator, or in this case an implicit join would be cleanest:
$result = mysqli_query($conn, "SELECT * FROM construction, power, oil_and_gas, industrial WHERE construction.Countries = power.Countries AND power.Countries = oil_and_gas.Countries AND oil_and_gas.Countries = industrial.Countries");
You need the WHERE conditions so it knows how the rows of each different table are related to each other. You can shorten it a bit with aliases for the tables:
$result = mysqli_query($conn, "SELECT * FROM construction as C, power as P, oil_and_gas as G, industrial as I WHERE C.Countries = P.Countries AND P.Countries = G.Countries AND G.Countries = I.Countries");
In this case, however, I think you may want to consider changing the structure of your database. It seems like you repeat columns quite a bit across them. Perhaps these can all be in a single table, with a "type" column that specifies whether it's power, construction, etc. Then you can query just the one table and group by country name to get all your results without the messy joins across 4 tables.
The single table looks OK.
(The rest of this Answer is not complete, but might be useful.)
First, let's design the URL that will request the data.
.../foo.php?industry=...&country=...
But, rather than special casing the "all" in the client, do it in the server. That is, the last button for industry will generate
?industry=all
and the PHP code will not include this in the WHERE clause:
AND industry IN (...)
Similarly for &country=all versus &country=egypt,iran,iraq
Now, let me focus briefly on the PHP:
$wheres = array();
$industry = #$_GET['industry'];
if (! isset($industry)) { ...issue error message or use some default... }
elseif ($industry != 'all') {
$inds = array();
foreach (explode(',', $industry) as $ind) {
// .. should test validity here; left to user ...
$inds[] = "'$ind'";
}
$wheres[] = "industry IN (" . implode(',', $inds) . )";
}
// ... repeat for country ...
$where_clause = '';
if (! empty($wheres)) {
$where_clause = "WHERE " . implode(' AND ', $wheres);
}
// (Note that this is a generic way to build arbitrary WHEREs from the data)
// Build the SQL:
$sql = "SELECT ... FROM ...
$where_clause
ORDER BY ...";
// then execute it via mysqli or pdo (NOT mysql_query)
Now, let's talk about using AJAX. Or not. There were 2 choices:
you could have had the call to PHP be via a GET and have that PHP display a new page. This means that PHP will be constructing the table of results.
you could have used AJAX to request the data. This means that Javascript will be constructing the data of results.
Which choice to pick probably depends on which language you are more comfortable in.

want to fetch multiple details from database if value is selected in selected tag

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

bring data from a JSON and show in a popup

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!

Updating the server-side json to output filtered table data

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
}
}

Creating D3 Line Graph Based off of Drop-down selection

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.

Categories

Resources