I have follow a web site to made a Dynamic Dependent Select using SQL JQuery Ajax with PHP , and it's work !, but i would like to get the value from the second and third select box once i chosen , and auto fill in to the other input box. is that possible to do it ?
look like this
if i selected all 3 select box and the data have shown (fetched from sql)
can i duplicate those 2 value to other input box and auto filled to the box???
Much thanks
code below
Index.php
<?php
$connect = mysqli_connect("localhost", "root", "", "testing");
$country = '';
$query = "SELECT country FROM country_state_city GROUP BY country ORDER BY country ASC";
$result = mysqli_query($connect, $query);
while($row = mysqli_fetch_array($result))
{
$country .= '<option value="'.$row["country"].'">'.$row["country"].'</option>';
}
?>
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<br /><br />
<div class="container" style="width:600px;">
<h2 align="center">Dynamic Dependent Select Box using JQuery Ajax with PHP</h2><br /><br />
<select name="country" id="country" class="form-control action">
<option value="">Select Country</option>
<?php echo $country; ?>
</select>
<br />
<select name="state" id="state" class="form-control action">
<option value="">Select State</option>
</select>
<br />
<select name="city" id="city" class="form-control">
<option value="">Select City</option>
</select>
</div>
</body>
</html>
<script>
$(document).ready(function(){
$('.action').change(function(){
if($(this).val() != '')
{
var action = $(this).attr("id");
var query = $(this).val();
var result = '';
if(action == "country")
{
result = 'state';
}
else
{
result = 'city';
}
$.ajax({
url:"fetch.php",
method:"POST",
data:{action:action, query:query},
success:function(data){
$('#'+result).html(data);
}
})
}
});
});
</script>
fatch.php
<?php
if(isset($_POST["action"]))
{
$connect = mysqli_connect("localhost", "root", "", "testing");
$output = '';
if($_POST["action"] == "country")
{
$query = "SELECT state FROM country_state_city WHERE country = '".$_POST["query"]."' GROUP BY state";
$result = mysqli_query($connect, $query);
$output .= '<option value="">Select State</option>';
while($row = mysqli_fetch_array($result))
{
$output .= '<option value="'.$row["state"].'">'.$row["state"].'</option>';
}
}
if($_POST["action"] == "state")
{
$query = "SELECT city FROM country_state_city WHERE state = '".$_POST["query"]."'";
$result = mysqli_query($connect, $query);
$output .= '<option value="">Select City</option>';
while($row = mysqli_fetch_array($result))
{
$output .= '<option value="'.$row["city"].'">'.$row["city"].'</option>';
}
}
echo $output;
}
?>
Create two input boxes and then use jquery to populate these on change of two select boxes like this.
<div>
<input id="forState" />
<input id="forCity" />
</div>
SCRIPT:
$('#state').change(function(){
console.log($("#state option:selected").val());
$('#forState').val($("#state option:selected").val());
} );
$('#city').change(function(){
console.log($("#city option:selected").val());
$('#forCity').val($("#city option:selected").val());
} );
Related
I've been trying to do a dynamic drop down menu using php/mysql with ajax. But I'm new to php and ajax so i don't know how to insert the selected option into a mysql table. I created a form where the action leads to a insertsql.php file but its not working.I'm using wamp server. Any help would be greatly appreciated.
index1.php
<?php
//index.php
$connect = mysqli_connect("localhost", "root", "", "projects");
$pname = '';
$query = "SELECT pname FROM project_details GROUP BY pname ORDER BY pname ASC";
$result = mysqli_query($connect, $query);
while($row = mysqli_fetch_array($result))
{
$pname .= '<option value="'.$row["pname"].'">'.$row["pname"].'</option>';
}
?>
<!DOCTYPE html>
<html>
<head>
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>zz
</head>
<body>
<br /><br />
<div class="container" style="width:600px;">
<h2 align="center">Dynamic Dependent Select Box using JQuery Ajax with PHP</h2><br /><br />
<form method = "POST" action = "insertsql.php" >
<select name="pname" id="pname" class="form-control action">
<option value="">Select Project</option>
<?php echo $pname; ?>
</select>
<br />
<select name="user" id="user" class="form-control action">
<option value="">Select User Name</option>
</select>
<br />
<input type="submit" name="update" value="Update">
<p id="dem"></p>
<p id="demo"></p>
</form>
</div>
</body>
</html>
<script>
$(document).ready(function(){
$('.action').change(function(){
if($(this).val() != '')
{
var action = $(this).attr("id");
var query = $(this).val();
var result = '';
if(action == "pname")
{
result = 'user';
}
$.ajax({
url:"fetch.php",
method:"POST",
data:{action:action, query:query},
success:function(data){
$('#'+result).html(data);
}
})
}
});
});
</script>
fetch.php
<?php
//fetch.php
if(isset($_POST["action"]))
{
$connect = mysqli_connect("localhost", "root", "", "projects");
$output = '';
if($_POST["action"] == "pname")
{
$query = "SELECT fname,lname FROM users WHERE pname = '".$_POST["query"]."' GROUP BY fname";
$result = mysqli_query($connect, $query);
$output .= '<option value="">Select User</option>';
while($row = mysqli_fetch_array($result))
{
$output .= '<option value="'.$row["fname"].' '.$row["lname"].'">'.$row["fname"]." ".$row["lname"].'</option>';
}
}
echo $output;
}
?>
insertsql.php
<?php
include('sqlconfig.php');
$pname= $_POST['pname'];
$username=$_POST['user'];
$date=$_POST['wdate'];
$hours=$_POST['hours'];
echo "$pname";
echo "<br>$username<br>";
$sql="INSERT INTO worklogging(pname,username,wdate,wkhours) VALUES ('$pname','$username','$date','$hours')";
if(!mysqli_query($con,$sql))
{echo 'not inserted';}
else
{echo 'Inserted';
}
?>
This is the part where the data from the dropdown menu is inserted into the mysql table. Thank you all for the help :)
I am newbie to JQuery Ajax. May i know how to create a PHP to read the subcategory list depends on the selected maincategory? So far i had create a jQuery AJAX in my asset_add.php
<script src="jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function()
{
$('#main_category').on('change',function(){
var categoryNAME = $(this).val();
if(categoryNAME){
$.ajax({
type:'POST',
url:'ajaxData.php',
data:'ac_maincategory='+categoryNAME,
success:function(html){
$('#sub_category').html(html);
}
});
}else{
$('#sub_category').html('<option value="">Select main category first</option>');
}
});
});
</script>
and for HTML,
<tr>
<td valign=top><strong>MAIN CATEGORY</td>
<td><select name="main_category" id="main_category" onchange="this.form.submit()" required>
<?php
$sql = "SELECT * FROM asset_category GROUP BY ac_maincategory" ;
$result = mysqli_query($conn, $sql);
$count=mysqli_num_rows($result);
?>
<option value=""></option>
<?php
if($count > 0)
{
while ($rs = mysqli_fetch_array($result))
{
$ac_maincategory = $rs["ac_maincategory"];
$ac_id = $rs["ac_id"];
?>
<option value="<?=$ac_id?>"><?=$ac_maincategory?></option>
<?php
}
}
?>
</select>
</td>
</tr>
<tr>
<td valign=top><strong>SUB CATEGORY</td>
<td><select id= "sub_category" name="sub_category" autocomplete="off"/ required>
<option value=""></option>
</select>
</tr>
while in my ajaxData.php
<?php
//Include database configuration file
require("config.php");
$conn = dbconnect();
if(isset($_POST["ac_maincategory"]) && !empty($_POST["ac_maincategory"]))
{
$sql = "SELECT * FROM asset_category WHERE ac_maincategory = ".$_POST['ac_maincategory']."" ;
$result = mysqli_query($conn, $sql);
$count=mysqli_num_rows($result);
if($count > 0)
{
echo '<option value="">Select Subcategory</option>';
while ($rs = mysqli_fetch_array($result))
{
$ac_subcategory = $rs["ac_subcategory"];
$ac_id = $rs["ac_id"];
echo '<option value="'.$rs['ac_subcategory'].'">'.$rs['ac_subcategory'].'</option>';
}
}
}
?>
However, when i choose a maincategory in asset_add.php, nothing shown in subcategory. Can anyone tell me which part i do wrong? Thanks for help
Seems you are replacing whole div with $('#sub_category').html(html); so there is only options printed on the view
You can solve it by replacing the line
$('#sub_category').html(html);
to
$('#sub_category').append(html);
Or Just replace this code in ajaxData.php , S
//Include database configuration file
require("config.php");
$conn = dbconnect();
if(empty($_POST["ac_maincategory"])){
die("category is empty");
}
$sql = "SELECT * FROM asset_category WHERE ac_maincategory = " . $_POST['ac_maincategory'];
$result = mysqli_query($conn, $sql);
$count = mysqli_num_rows($result);
if($count > 0)
{
echo '<select id= "sub_category" name="sub_category" autocomplete="off"/ required>';
echo '<option value="">Select Subcategory</option>';
while ($rs = mysqli_fetch_array($result))
{
$ac_subcategory = $rs["ac_subcategory"];
$ac_id = $rs["ac_id"];
echo '<option value="'.$rs['ac_subcategory'].'">'.$rs['ac_subcategory'].'</option>';
}
echo "</select>";
}
this is simple question and should be fixed ASAP. but idk why still not solved yet.
so, please try this
html
remove onchange attribute (remove native js event trigger style with jquery style)
optional:
fix several unclosed tag html
remove unrecomended PHP writing style
into this
<tr>
<td valign="top"><strong>MAIN CATEGORY</strong></td>
<td>
<select name="main_category" id="main_category" required>
<option value=""></option>
<?php
$sql = "SELECT * FROM asset_category GROUP BY ac_maincategory" ;
$result = mysqli_query($conn, $sql);
$count=mysqli_num_rows($result);
if($count > 0)
{
while ($rs = mysqli_fetch_array($result))
{
echo '<option value="'. $rs["ac_id"] .'">'.$rs["ac_maincategory"].'</option>';
}
}
?>
</select>
</td>
</tr>
<tr>
<td valign="top"><strong>SUB CATEGORY</strong></td>
<td>
<select id= "sub_category" name="sub_category" autocomplete="off" required>
<option value="">Select main category first</option>
</select>
</td>
</tr>
jquery
change on('change') with change() // possible dont know when to use on or not
change wrong comparasion on categoryNAME
optional:
change serialize data style using data {} //better for newbie to study
into this
<script>
$(function(){
$('#main-category').change(, function(){
var categoryNAME = $(this).val();
if(categoryNAME != ''){
$.ajax({
type:'POST',
url:'ajaxData.php',
data:{ac_maincategory: categoryNAME},
success:function(html){
$('#sub_category').html(html);
}
});
}else{
$('#sub_category').html('<option value="">Select main category first</option>');
}
})
});
</script>
PHP
reposition default sub-category value out of $count comparasion
into this
<?php
//Include database configuration file
require("config.php");
$conn = dbconnect();
if(isset($_POST["ac_maincategory"]) && !empty($_POST["ac_maincategory"]))
{
$sql = "SELECT * FROM asset_category WHERE ac_maincategory = ".$_POST['ac_maincategory']."" ;
$result = mysqli_query($conn, $sql);
$count=mysqli_num_rows($result);
echo '<option value="">Select Subcategory</option>';
if($count > 0)
{
while ($rs = mysqli_fetch_array($result))
{
$ac_subcategory = $rs["ac_subcategory"];
$ac_id = $rs["ac_id"];
echo '<option value="'.$rs['ac_subcategory'].'">'.$rs['ac_subcategory'].'</option>';
}
}
}
?>
<?php
//.....
//you sql......$result
//.....
if($_POST['ac_maincategory']) {
//this is test
if($_POST['ac_maincategory']=="aaa"){
$result=array("k1"=>"v1","k2"=>"v2");
}else{
$result=array("kk1"=>"v11","kk2"=>"v22");
}
$str = '<option value="">Select Subcategory</option>';
foreach ($result as $k => $v) {
$str .= '<option value="' . $k . '">' . $v . '</option>';
}
echo $str;exit;
}
?>
<html>
<head></head>
<body>
<div>
<select id="main_category">
<option value=""></option>
<option value="aaa">aaa</option>
<option value="bbb">bbb</option>
</select>
</div>
<div>
<select id="sub_category">
<option value=""></option>
</select>
</div>
</body>
</html>
<script src="http://www.w3school.com.cn/jquery/jquery-1.11.1.min.js"></script>
<script>
$("#main_category").change(function () {
var categoryNAME=$(this).val();
$.ajax({
type:'POST',
url:'',
data:{"ac_maincategory":categoryNAME},
success:function(html){
$('#sub_category').html(html);
}
});
})
</script>
test image
https://i.stack.imgur.com/oJLKo.png
https://i.stack.imgur.com/oIw03.png
https://i.stack.imgur.com/vQQrz.png
I want to add part search into a website powered by WordPress. I have currently achieved the function, but I have trouble of integrating it into WordPress. I tried several ways but the dynamic dependent select box still not working.
I followed this tutorial: Dynamic Dependent Select Box using jQuery, Ajax and PHP
Below are my code which works well outside WordPress.
index.php
<head>
<script src="http://code.jquery.com/jquery-3.1.1.min.js"></script>
<script src="js/ajax-ps.js"></script>
</head>
<body>
<form class="select-boxes" action="ps-result.php" method="POST">
<?php
include('dbConfig.php');
$query = $db->query("SELECT * FROM ps_manufact WHERE status = 1 ORDER BY manufact_name ASC");
$rowCount = $query->num_rows;
?>
<select name="manufacturer" id="manufact" class="col-md-2 col-sm-2 col-xs-10" onchange="manufactText(this)">
<option value="">Select Manufacturer</option>
<?php
if($rowCount > 0){
while($row = $query->fetch_assoc()){
echo '<option value="'.$row['manufact_id'].'">'.$row['manufact_name'].'</option>';
}
}else{
echo '<option value="">Manufacturer Not Available</option>';
}
?>
</select>
<input id="manufacturer_text" type="hidden" name="manufacturer_text" value=""/>
<script type="text/javascript">
function manufactText(ddl) {
document.getElementById('manufacturer_text').value = ddl.options[ddl.selectedIndex].text;
}
</script>
<select name="type" id="type" class="col-md-2 col-sm-2 col-xs-10" onchange="typeText(this)">
<option value="">Select Manufacturer First</option>
</select>
<input id="type_text" type="hidden" name="type_text" value=""/>
<script type="text/javascript">
function typeText(ddl) {
document.getElementById('type_text').value = ddl.options[ddl.selectedIndex].text;
}
</script>
<select name="year" id="year" class="col-md-2 col-sm-2 col-xs-10" onchange="yearText(this)">
<option value="">Select Type First</option>
</select>
<input id="year_text" type="hidden" name="year_text" value=""/>
<script type="text/javascript">
function yearText(ddl) {
document.getElementById('year_text').value = ddl.options[ddl.selectedIndex].text;
}
</script>
<select name="model" id="model" class="col-md-2 col-sm-2 col-xs-10" onchange="modelText(this)">
<option value="">Select Year First</option>
</select>
<input id="model_text" type="hidden" name="model_text" value=""/>
<script type="text/javascript">
function modelText(ddl) {
document.getElementById('model_text').value = ddl.options[ddl.selectedIndex].text;
}
</script>
<input type="submit" name="search" id="search" class="col-md-2 col-sm-2 col-xs-10" value="Search">
</form>
</body>
ajax-ps.js
$(document).ready(function(){
$('#manufact').on('change',function(){
var manufactID = $(this).val();
if(manufactID){
$.ajax({
cache: false,
type:'POST',
url:'ajax-data.php',
data:'manufact_id='+manufactID,
success:function(type_data){
$('#type').html(type_data);
$('#year').html('<option value="">Select Type First</option>');
}
});
}else{
$('#type').html('<option value="">Select Manufact First</option>');
$('#year').html('<option value="">Select Type First</option>');
}
});
$('#type').on('change',function(){
var typeID = $(this).val();
if(typeID){
$.ajax({
cache: false,
type:'POST',
url:'ajax-data.php',
data:'type_id='+typeID,
success:function(year_data){
$('#year').html(year_data);
$('#model').html('<option value="">Select Year First</option>');
}
});
}else{
$('#year').html('<option value="">Select Type First</option>');
$('#model').html('<option value="">Select Year First</option>');
}
});
$('#year').on('change',function(){
var yearID = $(this).val();
if(yearID){
$.ajax({
cache: false,
type:'POST',
url:'ajax-data.php',
data:'year_id='+yearID,
success:function(model_data){
$('#model').html(model_data);
}
});
}else{
$('#model').html('<option value="">Select Year First</option>');
}
});
});
ajax-data.php
include('dbConfig.php');
if(isset($_POST["manufact_id"]) && !empty($_POST["manufact_id"])){
$query = $db->query("SELECT * FROM ps_type WHERE manufact_id = ".$_POST['manufact_id']." AND status = 1 ORDER BY type_name ASC");
$rowCount = $query->num_rows;
if($rowCount > 0){
echo '<option value="">Select Type</option>';
while($row = $query->fetch_assoc()){
echo '<option value="'.$row['type_id'].'">'.$row['type_name'].'</option>';
}
}else{
echo '<option value="">Type Not Available</option>';
}
}
if(isset($_POST["type_id"]) && !empty($_POST["type_id"])){
$query = $db->query("SELECT * FROM ps_year WHERE type_id = ".$_POST['type_id']." AND status = 1 ORDER BY year_name ASC");
$rowCount = $query->num_rows;
if($rowCount > 0){
echo '<option value="">Select Year</option>';
while($row = $query->fetch_assoc()){
echo '<option value="'.$row['year_id'].'">'.$row['year_name'].'</option>';
}
}else{
echo '<option value="">Year Not Available</option>';
}
}
if(isset($_POST["year_id"]) && !empty($_POST["year_id"])){
$query = $db->query("SELECT * FROM ps_model WHERE year_id = ".$_POST['year_id']." AND status = 1 ORDER BY model_name ASC");
$rowCount = $query->num_rows;
if($rowCount > 0){
echo '<option value="">Select Model</option>';
while($row = $query->fetch_assoc()){
echo '<option value="'.$row['model_id'].'">'.$row['model_name'].'</option>';
}
}else{
echo '<option value="">Model Not Available</option>';
}
}
Now the problem is, when select the first box, the second one becomes empty, nothing is returned from the database:
Capture - After select the first box
Really appreicate Christos Lytras to help me solve the previous problem.
I have a new problem with action="ps-result.php" in the line <form class="select-boxes" action="ps-result.php" method="POST">.
ps-result.php
<?php
if (isset($_POST['search'])) {
$clauses = array();
if (isset($_POST['manufacturer_text']) && !empty($_POST['manufacturer_text'])) {
$clauses[] = "`manufacturer` = '{$_POST['manufacturer_text']}'";
}
if (isset($_POST['type_text']) && !empty($_POST['type_text'])) {
$clauses[] = "`type` = '{$_POST['type_text']}'";
}
if (isset($_POST['year_text']) && !empty($_POST['year_text'])) {
$clauses[] = "`year` = '{$_POST['year_text']}'";
}
if (isset($_POST['model_text']) && !empty($_POST['model_text'])) {
$clauses[] = "`model` = '{$_POST['model_text']}'";
}
$where = !empty( $clauses ) ? ' where '.implode(' and ',$clauses ) : '';
$sql = "SELECT * FROM `wp_products` ". $where;
$result = filterTable($sql);
}
else {
$sql = "SELECT * FROM `wp_products` WHERE `manufacturer`=''";
$result = filterTable($sql);
}
function filterTable($sql) {
$con = mysqli_connect("localhost", "root", "root", "i2235990_wp2");
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
$filter_Result = mysqli_query($con, $sql);
return $filter_Result;
}
?>
<?php get_header(); ?>
<div class="container">
...
</div>
<?php get_footer(); ?>
Now when I click Search, it returns
Fatal error: Call to undefined function get_header() in /Applications/MAMP/htdocs/wordpress/wp-content/themes/myTheme/inc/ps-result.php on line 42.
The proper way to do this, is to create a wordpress shortcode and then use that shortcode wherever you want, page or post, but if you want to create something more specific, then you should create a small wordpress plugin. I won't get into this, but it’s really not a big deal to create a simple wordpress plugin having such functionality. I’ll go through the steps on how you can have this working in wordpress with the files and the code you already have.
I assume you already have the tables of your example created. My tables are like this:
wp_citytours_dynsel_cities
wp_citytours_dynsel_states
wp_citytours_dynsel_countries
I have imported some data and I have all those tables filled with proper data. I can provide some sql files if you like, but I assume you already have your tables filled with the proper data for each table.
My test theme root directory is:
/wp-content/themes/citytours/
I have created the directory under my theme root directory and I have included all the code files there, so we have 3 files:
/wp-content/themes/citytours/dynsel/index-partial.php
<?php
//Include database configuration file
include('dbConfig.php');
//Get all country data
$query = $db->query("SELECT * FROM wp_citytours_dynsel_countries WHERE status = 1 ORDER BY country_name ASC");
//Count total number of rows
$rowCount = $query->num_rows;
?>
<select name="country" id="country">
<option value="">Select Country</option>
<?php
if($rowCount > 0){
while($row = $query->fetch_assoc()){
echo '<option value="'.$row['country_id'].'">'.$row['country_name'].'</option>';
}
}else{
echo '<option value="">Country not available</option>';
}
?>
</select>
<select name="state" id="state">
<option value="">Select country first</option>
</select>
<select name="city" id="city">
<option value="">Select state first</option>
</select>
<script type="text/javascript">
jQuery(function($) {
$('#country').on('change',function(){
var countryID = $(this).val();
if(countryID){
$.ajax({
type:'POST',
url:'<?php echo home_url('wp-content/themes/citytours/dynsel/ajaxData.php') ?>',
data:'country_id='+countryID,
success:function(html){
$('#state').html(html);
$('#city').html('<option value="">Select state first</option>');
}
});
}else{
$('#state').html('<option value="">Select country first</option>');
$('#city').html('<option value="">Select state first</option>');
}
});
$('#state').on('change',function(){
var stateID = $(this).val();
if(stateID){
$.ajax({
type:'POST',
url:'<?php echo home_url('wp-content/themes/citytours/dynsel/ajaxData.php') ?>',
data:'state_id='+stateID,
success:function(html){
$('#city').html(html);
}
});
}else{
$('#city').html('<option value="">Select state first</option>');
}
});
});
</script>
/wp-content/themes/citytours/dynsel/dbConfig.php
<?php
//db details
$dbHost = 'localhost';
$dbUsername = 'xxxx';
$dbPassword = 'xxxx';
$dbName = 'xxxx';
//Connect and select the database
$db = new mysqli($dbHost, $dbUsername, $dbPassword, $dbName);
if ($db->connect_error) {
die("Connection failed: " . $db->connect_error);
}
?>
/wp-content/themes/citytours/dynsel/ajaxData.php
<?php
//Include database configuration file
include('dbConfig.php');
if(isset($_POST["country_id"]) && !empty($_POST["country_id"])){
//Get all state data
$query = $db->query("SELECT * FROM wp_citytours_dynsel_states WHERE country_id = ".$_POST['country_id']." AND status = 1 ORDER BY state_name ASC");
//Count total number of rows
$rowCount = $query->num_rows;
//Display states list
if($rowCount > 0){
echo '<option value="">Select state</option>';
while($row = $query->fetch_assoc()){
echo '<option value="'.$row['state_id'].'">'.$row['state_name'].'</option>';
}
}else{
echo '<option value="">State not available</option>';
}
}
if(isset($_POST["state_id"]) && !empty($_POST["state_id"])){
//Get all city data
$query = $db->query("SELECT * FROM wp_citytours_dynsel_cities WHERE state_id = ".$_POST['state_id']." AND status = 1 ORDER BY city_name ASC");
//Count total number of rows
$rowCount = $query->num_rows;
//Display cities list
if($rowCount > 0){
echo '<option value="">Select city</option>';
while($row = $query->fetch_assoc()){
echo '<option value="'.$row['city_id'].'">'.$row['city_name'].'</option>';
}
}else{
echo '<option value="">City not available</option>';
}
}
?>
As you can see, the index-partial.php now contains only needed code, without <body>, <head> and script files included. Wordpress already includes jQuery to the application for most themes, but you should always check that.
Now, you can add the functionality wherever you want, even at the theme index.php file, but always with caution. I have used theme's single post template file, which is single-post.php. I have included the example code, under the main post body inside a div. I just include the index-partial.php like this:
<div class="<?php echo esc_attr( $content_class ); ?>">
<div class="box_style_1">
...
</div><!-- end box_style_1 -->
<div class="box_style_1">
<?php include(__DIR__.'/dynsel/index-partial.php'); ?>
</div>
</div><!-- End col-md-9-->
I also have used the wordpress home_url function, to have a proper url rooted for the ajaxData.php file like this:
url:'<?php echo home_url('wp-content/themes/citytours/dynsel/ajaxData.php') ?>'
Now, if you have followed all these steps, then you should have your code example working at under each post. You can now included it wherever you want by using that line of code <?php include(__DIR__.'/dynsel/index-partial.php'); ?>.
Please let me know if that worked for you.
I have two dropdowns which values are populated from MySQL. The second dropdown values depends on the first dropdown option.
Anyways, the code is working. Now using my code I am posting hospital_id to another php. But I want to display hospital_name as text on the dropdown as well, but as of now I am only able to display the hospital_id.
Please see me code below and suggest me a solution:
$query = "SELECT bp_id,bp_name FROM mfb_billing";
$result = $db->query($query);
while($row = $result->fetch_assoc()){
$categories[] = array("bp_id" => $row['bp_id'], "val" => $row['bp_name']);
}
$query = "SELECT bp_id, hospital_id, hospital_name FROM mfb_hospital";
$result = $db->query($query);
while($row = $result->fetch_assoc()){
$subcats[$row['bp_id']][] = array("bp_id" => $row['bp_id'], "val" => $row['hospital_id']);
}
$jsonCats = json_encode($categories);
$jsonSubCats = json_encode($subcats);
This is the script:
<script type='text/javascript'>
<?php
echo "var categories = $jsonCats; \n";
echo "var subcats = $jsonSubCats; \n";
?>
function loadCategories(){
var select = document.getElementById("categoriesSelect");
select.onchange = updateSubCats;
for(var i = 1; i < categories.length; i++){
select.options[i] = new Option(categories[i].val,categories[i].bp_id);
}
}
function updateSubCats(){
var catSelect = this;
var catid = this.value;
var subcatSelect = document.getElementById("subcatsSelect");
subcatSelect.options.length = 0; //delete all options if any present
for(var i = 0; i < subcats[catid].length; i++){
subcatSelect.options[i] = new Option(subcats[catid][i].val,subcats[catid][i].hosp);
}
}
</script>
This is my form:
<body onload='loadCategories()'>
<form id="reportvalue" action="testpj2.php" method="post">
<select id='categoriesSelect'>
<option value="1">Select Billing Provider</option>
</select>
<select name='hospitalname[]' id='subcatsSelect' multiple='multiple'>
<option value="all">Select Billing Provider</option>
</select>
<label for="from">From</label>
<input type="text" id="from" name="from">
<label for="to">to</label>
<input type="text" id="to" name="to">
<?php
//$a = $_REQUEST['hospitalname[]'];
//echo $a;
?>
<input type="submit" name="Submit" value="Submit">
</form>
HTML
<select id="someId"></select>
Javascript
document.getElementById('someId').innerHTML="
<option value='value1'>"+option1+"</option>
<option value='value2'>"+option2+"</option>
<option value='value3'>"+option3+"</option>";
Update:
for dynamic data from SQL query,
Try putting these codes after query execution. replace $row['value'] and $row['option'] with the respected dynamic values.
echo"<script type='text/javascript'> var str = '' </script>";
while($row = $result->fetch_assoc())
{
echo"<script type='text/javascript'>
str = str + '<option value='+".$row['value']."+'>'+".$row['option']."+'</option>
</script>";
}
echo"<script type='text/javascript'>
document.getElementById('someId').innerHTML = str
</script>";
if you are getting the hospital id then it is very easy to populate the selected value by getting it through from mysql
$query = "SELECT hospital_id, hospital_name FROM mfb_hospital where hospital_id = '$_post['hospital_id']'";
$result = $db->query($query);
$res = mysql_fetch_array($result)
In your select option value code put this code
<option value="your ids here will populate" <?php if($hospital_array['hospital_id']==$res['hospital_id']) echo "selected=selected" ?>>Your hospital name will display here which you selected</option>
I am new with php.I want to change query when some event occur on ComboBox. So that according to that query I retrieve data from database in php.The code is given below:-
<form method="POST" action="">
<select id="choose-color">
<option value="all">All</option>
<option value="blue">Blue</option>
<option value="black">Black</option>
<option value="white">White</option>
</select>
</form>
<?php
$conn = mysqli_connect("localhost","root","123");
mysqli_select_db($conn,"DwtCW");
$q = "Select * from Clothes";
$result = mysqli_query($conn, $q);
if (!$result) {
echo 'Some error';
}
while($row = mysqli_fetch_assoc($result)){
if($row{'Image_url'} != ''){
echo '<div>'
. '<img src='.$row{'Image_url'}.'/>'
.'</div>'
}
?>
When I select blue option of ComboBox my $q(query given in above code) is change to
$q = "Select * from Clothes where colour = 'blue'";
So there should appear only images of clothes having blue colour onpage.
How I reach it?
you need to send ajax request to PHP page. onChange event will trigger ajax request and will change query.
<form method="POST" action="">
<select id="choose-color">
<option value="all">All</option>
<option value="blue">Blue</option>
<option value="black">Black</option>
<option value="white">White</option>
</select>
</form>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
$(function(){
$('#choose-color').on('change', function(){
var color = $(this).val();
if(color){
$.ajax({
type: "GET",
url: "index.php", //or your php page
data: { color: color }
})
.done(function( msg ) {
alert( "Data Saved: " + msg );
});
}
});
});
</script>
<?php
$conn = mysqli_connect("localhost","root","123");
mysqli_select_db($conn,"DwtCW");
$whr = ' ';
// check if color is posted on change event
if ( isset($_GET['color'] ) ) {
$whr .= " where colour = '".$color."' ";
}
$q = "Select * from Clothes $whr";
$result = mysqli_query($conn, $q);
if (!$result) {
echo 'Some error';
}
while($row = mysqli_fetch_assoc($result)){
if($row{'Image_url'} == ''){
echo '<div>'
. '<img src='.$row{'Image_url'}.'/>'
.'</div>'
}
?>