Angularjs http request is not working? - php

I have a problem like this.
<!DOCTYPE html>
<html>
<head>
<title>The Wedima</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.1/angular.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script type="text/javascript" src="../controllers/intro.js"></script>
</head>
<body>
<br>
<div class="col-lg-5 panel" style="background-color:#BED3F4" ng-app="myModule">
{{10+30}}
<div ng-controller="introCtrl">
<tr ng-repeat="x in results">
<td>{{ x.id }}</td>
<td>{{ x.vision }}</td>
</tr>
</div>
</div>
</body>
</html>
I have crate a web page using angularJs.I want to get data from database using php.I have create Php and Intermediate javascript files as follows.
var app = angular.module('myModule', []);
app.controller("introCtrl", function($scope) {
//$scope.m="Tharindu"
$http({
method: 'get',
url: '../php/getData.php'
}).then(function chica(response) {
$scope.results = response.data;
});
});
This is my javascript file which contain the controller.
<?php
include 'config.php';
$sel = mysqli_query($con,"select * from vendor");
$data = array();
while ($row = mysqli_fetch_array($sel)) {
$data[] = array("id"=>$row['id'],"vision"=>$row['vision'],"description"=>$row['description']);
}
echo json_encode($data);
This is my php file which retrieving data from database. But this is not working .Without this HTTP request if i define a variable I can access in the view.But when I used it with this nothing was happened.I tried lot of examples have provided in the stack overflow.But I was Unable to get it done.How can I get solve this problem?

Try this :
var app = angular.module('myModule', []);
app.controller("introCtrl", function($scope,$http) {
//$scope.m="Tharindu"
$http({
method: 'get',
url: '../php/getData.php'
}).then(function chica(response) {
$scope.results = response.data;
});
});

Try this one
var request = $http.get('../php/getData.php');
request.then(function (response) {
$scope.results = reponse.data;
});
Note: remember to inject $http module in your controller

try below code, it depended to country dropdown and, on change country dropdown state dropdown events called.
feel free to ask any query.
<?php
//load_country.php
$connect = mysqli_connect("localhost", "root", "", "amit_db");
$output = array();
$query = "SELECT * FROM country ORDER BY country_name ASC";
$result = mysqli_query($connect, $query);
while ($row = mysqli_fetch_array($result)) {
$output[] = $row;
}
echo json_encode($output);
?>
<?php
//load_state.php
$connect = mysqli_connect("localhost", "root", "", "amit_db");
$output = array();
$data = json_decode(file_get_contents("php://input"));
$query = "SELECT * FROM state WHERE country_id='" . $data->country_id . "' ORDER BY state_name ASC";
$result = mysqli_query($connect, $query);
while ($row = mysqli_fetch_array($result)) {
$output[] = $row;
}
echo json_encode($output);
?>
<?php
//load_city.php
$connect = mysqli_connect("localhost", "root", "", "amit_db");
$output = array();
$data = json_decode(file_get_contents("php://input"));
$query = "SELECT * FROM city WHERE state_id='" . $data->state_id . "' ORDER BY city_name ASC";
$result = mysqli_query($connect, $query);
while ($row = mysqli_fetch_array($result)) {
$output[] = $row;
}
echo json_encode($output);
?>
//index.php
<html>
<head>
<title>Webslesson Tutorial | Dynamic Dropdown list using AngularJS in PHP</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
</head>
<body>
<br /><br />
<div class="container" style="width:600px;">
<h3 align="center">Dynamic Dropdown list using AngularJS in PHP</h3>
<br />
<div ng-app="myapp" ng-controller="usercontroller" ng-init="loadCountry()">
<select name="country[]" ng-options="y.country_name for y in countries" ng-model="country" class="form-control" ng-change="loadState()">
<option value="">Select Country</option>
</select>
<br />
<select name="state[]" ng-options=" state.state_name for state in states" ng-model="state" class="form-control" ng-change="loadCity()"> <option value="">Select state</option>
</select>
<br>
<select name="city" ng-model="city" ng-options="city.city_name for city in cities" class="form-control"><option value="">Select City</option>
</select>
</div>
</div>
</body>
</html>
<script>
var app = angular.module("myapp", []);
app.controller("usercontroller", function ($scope, $http) {
console.log($scope);
$scope.loadCountry = function () {
console.log('called loadCountry');
$http.get("load_country.php")
.success(function (data) {
$scope.countries = data;
})
}
$scope.loadState = function () {
console.log('called loadState');
if ($scope.country)
{
console.log($scope.country.country_id);
$http.post("load_state.php", {'country_id': $scope.country.country_id})
.success(function (data) {
$scope.states = data;
});
}
}
$scope.loadCity = function () {
var state = $scope.state.state_id;
console.log("state :" + state);
$http.post("load_city.php", {'state_id': state})
.success(function (data) {
console.log(data);
$scope.cities = data;
});
}
});
</script>

Related

How to obtain the option selected from the drop down menu and insert it into a mysql table

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 :)

AJAX success function not fetching data from MYSQL database

Apologies for similarities between this post and my previous one. I'd appreciate if someone could help me once again spot where I'm going wrong. Everything else appears to be working fine but what is puzzling me is the 'quiet' response on the AJAX success function. Nothing in the console either.
I've tested the JSON output with the json_encode and print_r functions and got the following - so I presume the JSON string should be ok to work with the AJAX:
Array
(
[proj_start_date] => 2017-04-17
[proj_end_date] => 2018-04-30
[wo_nbr_new] => 10002-06
)
{"proj_start_date":"2017-04-17","proj_end_date":"2018-04-30","wo_nbr_new":"10002-06"}
Below is the code for the main file:
<?php
include 'connect_db.php';
$sql = "SELECT * FROM projects ORDER BY proj_nbr";
$result = mysqli_query($connect,$sql);
$rowCount = mysqli_num_rows($result);
?>
<!DOCTYPE html>
<html lang="en">
<head>
<title>Add New Work Order</title>
<script
src="https://code.jquery.com/jquery-3.2.1.min.js"integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
crossorigin="anonymous">
</script>
<link rel="stylesheet" type="text/css" href="styles.css">
</head>
<body>
<h1>Add New Work Order</h1>
<div id="forms-add" name="forms-add">
<form action="add_workorders.php" method="POST">
<label>Work Order Number (Auto-generated):</label>
<input type="text" id="wo_nbr" name="wo_nbr"size="8"maxlength="8" value = "" readonly style="float: right">
<br><br>
<fieldset>
<legend>Project Details</legend>
<label>Project Number:</label>
<select class= "selects" id="proj_nbr" name="proj_nbr" required onchange="">
<option value="">Select a project </option>
<?php
if($rowCount>0)
{
while ($row=mysqli_fetch_assoc($result))
{
echo '<option value="'.
$row['proj_id'].'">'.
$row['proj_nbr'].
' - '.
$row['proj_desc'].
' </option>';
}
}
else
{
echo '<option value="">Project not available</option>';
}
?>
</select>
<br><br>
<label>Start Date:</label>
<input type="text" id="proj_start_date" name="proj_start_date"size="8"maxlength="8" value = "" readonly style="float: right">
<br><br>
<label>End Date:</label>
<input type="text" id="proj_end_date" name="proj_end_date"size="8"maxlength="8" value = "" readonly style="float: right">
</fieldset>
<br><br>
<button type="submit" name="submit" >Save Work Order</button>
</form>
</div>
</body>
<script type="text/javascript" src="test_ajax.js"></script>
<script>
$(document).ready(function()
{
$('#proj_nbr').change(function()
{
var id=$('#proj_nbr').val();
//alert(id); //this works ok
if (id != '')
{
$.ajax({
url: "get_proj_nbrs2.php",
method:"POST",
data: {id:id}, //data to SEND to PHP file
dataType: "JSON",
success: function(output)
{
console.log(output); //this doesn't return anything in the console??
$('#wo_nbr').val(output.wo_nbr_new);
$('#proj_start_date').val(output.proj_start_date);
$('#proj_end_date').val(output.proj_end_date);
}
});
}
else
{
alert("Please select a Project");
}
});
});
</script>
</html>
And the following is the code in the PHP file:
<?php
include 'connect_db.php';
if (isset($_POST['id']) && !empty($_POST['id']))
{
$sql2 = "SELECT p.proj_nbr as wo_proj_nbr,p.start_date as proj_start_date,p.end_date as proj_end_date, MAX(w.wo_nbr) AS wo_nbr,
CASE WHEN SUBSTRING(MAX(w.wo_nbr),7,2)+1 <= 9 THEN CONCAT(p.proj_nbr,'-0',SUBSTRING(MAX(w.wo_nbr),7,2)+1)
ELSE CONCAT(p.proj_nbr,'-',SUBSTRING(MAX(w.wo_nbr),7,2)+1) END AS wo_nbr_new
FROM workorders as w
INNER JOIN projects as p on p.proj_id = w.proj_id
WHERE w.proj_id = '".$_POST['id']."'";
$result2 = mysqli_query($connect,$sql2);
while($row=mysqli_fetch_array($result2))
{
if($result2 ==true)
{
$proj_nbr = $row['wo_proj_nbr'];
$output['proj_start_date'] = $row['proj_start_date'];
$output['proj_end_date'] = $row['proj_end_date'];
if ($row['wo_nbr_new'] != NULL)
{
$output['wo_nbr_new'] = $row['wo_nbr_new'];
echo json_encode($output);
}
elseif($row['wo_nbr_new'] == NULL)
{
$output['wo_nbr_new'] = $proj_nbr."-01";
echo json_encode($output);
}
}
}
}?>
<?php
include 'connect_db.php';
if (isset($_POST['id']) && !empty($_POST['id']))
{
$result = array();
$sql2 = "SELECT p.proj_nbr as wo_proj_nbr,p.start_date as proj_start_date,p.end_date as proj_end_date, MAX(w.wo_nbr) AS wo_nbr,
CASE WHEN SUBSTRING(MAX(w.wo_nbr),7,2)+1 <= 9 THEN CONCAT(p.proj_nbr,'-0',SUBSTRING(MAX(w.wo_nbr),7,2)+1)
ELSE CONCAT(p.proj_nbr,'-',SUBSTRING(MAX(w.wo_nbr),7,2)+1) END AS wo_nbr_new
FROM workorders as w
INNER JOIN projects as p on p.proj_id = w.proj_id
WHERE w.proj_id = '".$_POST['id']."'";
$result2 = mysqli_query($connect,$sql2);
if($result->num_rows > 0)
{
while($row=mysqli_fetch_array($result2))
{
$proj_nbr = $row['wo_proj_nbr'];
$output['proj_start_date'] = $row['proj_start_date'];
$output['proj_end_date'] = $row['proj_end_date'];
if ($row['wo_nbr_new'] != NULL)
{
$output['wo_nbr_new'] = $row['wo_nbr_new'];
}
elseif($row['wo_nbr_new'] == NULL)
{
$output['wo_nbr_new'] = $proj_nbr."-01";
}
array_push($result,$output);
}
echo json_encode($result);
}
else
{
echo "no rows found";
}
}?>
You was echo each row so you will get result from success function in ajax as each separate sting. so it can't parse. hope this method will solve your problem.
Please confirm that you id value is not empty and matches to database field values as well. if so then change the 'id' to 'theid' (might be reserved word) in both the ajax e.g.
data: {theid:id}, //data to SEND to PHP file
and in php e.g.
if (isset($_POST['theid']) && !empty($_POST['theid'])) {
$sql2 = "SELECT p.proj_nbr as wo_proj_nbr,p.start_date as proj_start_date,p.end_date as proj_end_date, MAX(w.wo_nbr) AS wo_nbr,
CASE WHEN SUBSTRING(MAX(w.wo_nbr),7,2)+1 <= 9 THEN CONCAT(p.proj_nbr,'-0',SUBSTRING(MAX(w.wo_nbr),7,2)+1)
ELSE CONCAT(p.proj_nbr,'-',SUBSTRING(MAX(w.wo_nbr),7,2)+1) END AS wo_nbr_new
FROM workorders as w
INNER JOIN projects as p on p.proj_id = w.proj_id
WHERE w.proj_id = '".$_POST['theid']."'";
// code goes here
}
use type at method. method POST depends on jquery version
$.ajax({
url: "get_proj_nbrs2.php",
type:"POST",
data: {id:id}, //data to SEND to PHP file
dataType: "JSON",
success: function(output)
{
}
});

Autocomplete return blank if the current value is not on the list

My code works fine here http://jsfiddle.net/qv94t/7/. But when the option value is came from by php the function is not working properly. I used ajax for generating the option value, but it has also the same error if I echo the option value in the same page and not using ajax.
Why is that? Help please
My ajax
getajax.php
<?php
if (isset($_POST["mainlist_id"])) {
$mysqli = new mysqli("localhost", "root", "", "2015");
$main = $mysqli->real_escape_string($_POST["mainlist_id"]);
$result1 = $mysqli->query("SELECT * FROM code WHERE cat_code='$main' GROUP BY item_code ORDER BY item");
while($row = $result1->fetch_assoc())
{
?>
<option class="eachop" value ="<?php echo $row['item'];?>"><?php echo $row['item'];?></option>';
<?php
}
}
?>
And here's my full code, I forgot to add my ajax and dropdown. Someone help please?
ajax.php
<?php
$mysqli = new mysqli("localhost", "root", "", "2015");
$combo = $mysqli->query("SELECT * FROM category GROUP BY cat_code ORDER BY id");
$option = '';
while($row = $combo->fetch_assoc())
{
$option .= '<option value = "'.$row['cat_code'].'">'.$row['category'].'</option>';
}
?>
<select id="main" name="main">
<option value="" disabled="disabled" selected="selected">Choose</option>
<?php echo $option; ?>
</select>
<input list="languages" id="none"></input>
<datalist id="languages" name="options">
<option value=""></option>
</datalist>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.13/jquery-ui.min.js"></script>
<input type="submit" name="submit" value="Submit" />
<script type="text/javascript">
$('#main').change(function(){
$.ajax({
url : 'getajax.php',
data :{mainlist_id : $(this).val()},
dataType:'html',
type:'POST',
success:function(data){
$('#languages').html(data);
}
});
});
</script>
<script>
var validOptions = [];
$("option").each(function () {
validOptions.push($(this).val())
});
previousValue = "";
console.log(validOptions)
$('#none').autocomplete({
autoFocus: true,
source: validOptions
}).keyup(function () {
var isValid = false;
for (i in validOptions) {
if (validOptions[i].toLowerCase().match(this.value.toLowerCase())) {
isValid = true;
}
}
if (!isValid) {
this.value = previousValue
} else {
previousValue = this.value;
}
});
</script>
you must echo the value then only, ajax get the value and displayed use below code....
<?php
if (isset($_POST["mainlist_id"])) {
$mysqli = new mysqli("localhost", "root", "", "2015");
$main = $mysqli->real_escape_string($_POST["mainlist_id"]);
$result1 = $mysqli->query("SELECT * FROM code WHERE cat_code='$main' GROUP BY item_code ORDER BY item");
while($row = $result1->fetch_assoc())
{
echo "<option class=\"eachop\" value =\"".$row['item']."\">".$row['item']."</option>";
}
}
?>

php mysql + ajax and jquery to dpopulate dynamic drop list

i am creating 2 dynamic drop list that the second one is based on the selection of the first but the problem is that the second one do not populate and i do not know where is the error can anyone help me ????
dbconfig.php
<?php
$host = "localhost";
$user = "*****";
$password = "****";
$db = "lam_el_chamel_db";
?>
select.php
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("select#district").attr("disabled","disabled");
$("select#governorate").change(function(){
$("select#district").attr("disabled","disabled");
$("select#district").html("<option>wait...</option>");
var id = $("select#governorate option:selected").attr('value');
$.post("select_district.php", {id:id}, function(data){
$("select#district").removeAttr("disabled");
$("select#district").html(data);
});
});
$("form#select_form").submit(function(){
var cat = $("select#governorate option:selected").attr('value');
var type = $("select#district option:selected").attr('value');
if(cat>0 && type>0)
{
var result = $("select#district option:selected").html();
$("#result").html('your choice: '+result);
}
else
{
$("#result").html("you must choose two options!");
}
return false;
});
});
</script>
</head>
<body>
<?php include "select.class.php"; ?>
<form id="select_form">
Choose a governorate:<br />
<select id="governorate">
<?php echo $opt->ShowGovernorate(); ?>
</select>
<br /><br />
choose a district:<br />
<select id="type">
<option value="0">choose...</option>
</select>
<br /><br />
<input type="submit" value="confirm" />
</form>
<div id="result"></div>
</body>
</html>
select class.php
<?php
class SelectList
{
protected $conn;
public function __construct()
{
$this->DbConnect();
}
protected function DbConnect()
{
include "dbconfig.php";
$this->conn = mysql_connect($host,$user,$password) OR die("Unable to connect to the database");
mysql_select_db($db,$this->conn) OR die("can not select the database $db");
return TRUE;
}
public function ShowGovernorate()
{
$sql = "SELECT * FROM governorate";
$res = mysql_query($sql,$this->conn);
$governorate = '<option value="0">choose...</option>';
while($row = mysql_fetch_array($res))
{
$governorate .= '<option value="' . $row['governorate_id'] . '">' . $row['governorate_name'] . '</option>';
}
return $governorate;
}
public function ShowDistrict()
{
$sql = "SELECT * FROM districts WHERE governorate_id=$_POST[id]";
$res = mysql_query($sql,$this->conn);
$district = '<option value="0">choose...</option>';
while($row = mysql_fetch_array($res))
{
$district .= '<option value="' . $row['district_id'] . '">' . $row['district_name'] . '</option>';
}
return $district;
}
}
$opt = new SelectList();
?>
select _type.php
<?php
include "select.class.php";
echo $opt->ShowDistrict();
?>
table structure
governorate :
governorate_id
governorate_name
districts:
district_id,
district_name,
governorate_id.
On select.php Page you used id for select tag is 'id="type"' which would be 'id = "district"' in select tag for choose a district : below text.
choose a district:<br />
<select id="type">
<option value="0">choose...</option>
</select>
By Below
choose a district:<br />
<select id="district">
<option value="0">choose...</option>
</select>
Rename page 'select_type.php' by 'select_district.php' Or do change in $.post ajax query. correct sending request page name by 'select_type.php'.
This should be changed in
from $sql = "SELECT * FROM districts WHERE governorate_id=$_POST[id]";
to $sql = "SELECT * FROM districts WHERE governorate_id=$_POST['governorate']";
also in select.php change
<select id='governorate'> to <select id='governorate' name='governorate'>

php mysql 3 dynamic drop list with ajax jquery

i am creating dynamic drop list using php mysql + ajax jquery that the populate of second drop list is based on the selection of the first and third is based on the selection of the second but it did not work can anyone help me ???
dbconfig.php
<?php
$host = "localhost";
$user = "****";
$password = "***";
$db = "lam_el_chamel_db";
?>
select.php
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("select#district").attr("disabled","disabled");
$("select#village").attr("disabled","disabled");
$("select#governorate").change(function(){
$("select#district").attr("disabled","disabled");
$("select#district").html("<option>wait...</option>");
$("select#village").attr("disabled","disabled");
$("select#village").html("<option>wait...</option>");
var id = $("select#governorate option:selected").attr('value');
$.post("select_district.php", {id:id}, function(data){
$("select#district").removeAttr("disabled");
$("select#district").html(data);
});
var id2 = $("select#district option:selected").attr('value');
$.post("select_village.php", {id:id}, function(data){
$("select#village").removeAttr("disabled");
$("select#village").html(data);
});
$("form#select_form").submit(function(){
var gover = $("select#governorate option:selected").attr('value');
var dist = $("select#district option:selected").attr('value');
if(gover>0 && dist>0)
{
var result = $("select#district option:selected").html();
$("#result").html('your choice: '+result);
}
else
{
$("#result").html("you must choose two options!");
}
if(dist>0 && village>0)
{
var result = $("select#village option:selected").html();
$("#result").html('your choice: '+result);
}
else
{
$("#result").html("you must choose three options!");
}
return false;
});
});
</script>
</head>
<body>
<?php include "select.class.php"; ?>
<form id="select_form">
Choose a governorate:<br />
<select id="governorate">
<?php echo $opt->ShowGovernorate(); ?>
</select>
<br /><br />
choose a district:<br />
<select id="district">
<option value="0">choose...</option>
</select>
<br /><br />
choose a village:<br />
<select id="village">
<option value="0">choose...</option>
</select>
<input type="submit" value="confirm" />
</form>
<div id="result"></div>
</body>
</html>
select_class.php
<?php
class SelectList
{
protected $conn;
public function __construct()
{
$this->DbConnect();
}
protected function DbConnect()
{
include "dbconfig.php";
$this->conn = mysql_connect($host,$user,$password) OR die("Unable to connect to the database");
mysql_select_db($db,$this->conn) OR die("can not select the database $db");
return TRUE;
}
public function ShowGovernorate()
{
$sql = "SELECT * FROM governorate";
$res = mysql_query($sql,$this->conn);
$governorate = '<option value="0">choose...</option>';
while($row = mysql_fetch_array($res))
{
$governorate .= '<option value="' . $row['governorate_id'] . '">' . $row['governorate_name'] . '</option>';
}
return $governorate;
}
public function ShowDistrict()
{
$sql = "SELECT * FROM districts WHERE governorate_id=$_POST[id]";
$res = mysql_query($sql,$this->conn);
var_dump($res);
$district = '<option value="0">choose...</option>';
while($row = mysql_fetch_array($res))
{
$district .= '<option value="' . $row['district_id'] . '">' . $row['district_name'] . '</option>';
}
return $district;
}
public function ShowVillage()
{
$sql = "SELECT village_id, village_name FROM village WHERE district_id=$_POST[id2]";
$res = mysql_query($sql,$this->conn);
$village = '<option value="0">choose...</option>';
while($row = mysql_fetch_array($res))
{
$village .='<option value="' .$row['village_id'] . '">' . $row['village_name'] . '</option>';
}
return $village;
}
}
$opt = new SelectList();
?>
select_district.php
<?php
include "select.class.php";
echo $opt->ShowDistrict();
?>
select_village.php
<?php
include "select.class.php";
echo $opt->ShowVillage();
?>
i think it has something within the select.php but i did not know what is the error
Your ajax call is done on the document.ready function. You should bind the ajax to the dropdown change function like:
$("select#district option:selected").change(function(){
id = $(this).val();
$.post("select_village.php", {id:id}, function(data){
$("select#village").removeAttr("disabled");
$("select#village").html(data);
});
Hope that helps

Categories