如何使用jquery ajax和php将PostgreSQL的数据填充到组合框中
问题描述:
I want to fetch data from PostgreSQL into my Combobox using query Ajax in html page.
Here is the code of popup box where I want to fetch the data:
<html>
<body>
<script src="../webmap/jquery-1.11.2.min.js"></script>
<script type="text/javascript">
function dropdown(){
$('#a1_title').empty();
$('#a1_title').append("<option>loading....</option>");
$.ajax({
type: "POST",
url: "drpdwn.php",
contentype: "application/json; charset=utf-8",
dataType: "json",
sucess:function(data){
$('#a1_title').empty();
$('#a1_title').append("<option value='0' >----select name-</option>");
$.each(data,function(i,item){
$('#a1_title').append('<option value="'+ data[i].id +'" >'+ data[i].name +'</option>');
});
},
complete: function(){
}
});
}
$(document).ready(function(){
dropdown();
});
</script>
<select id="a1_title">
</select>
</body>
</html>
This is drpdwn.php
file:
<?php
$host = "localhost";
$user = "postgres";
$pass = "admin";
$db = "Querybuilderdb";
$con = pg_connect("host=$host dbname=$db user=$user password=$pass")
or die ("Could not connect to server
");
$query = "SELECT id, name FROM tab";
$result = pg_query($con, $query);
if(pg_num_rows($result)){
$data=array();
while($row=pg_fetch_array($result))
{ $data[] = array(
'id'=>$row['id'],
'name' =>$row['name']
);
}
echo json_encode($data);
}
?>
I have update my code here Can anyone please tell me where i'm doing wrong?
答
Its working now by using getJSON
<html><body>
<select id="a1_title">
</select>
<select id="a2_title">
</select>
<script src="jquery-2.0.3.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$.getJSON("drpdwn.php", success = function(data){
var items="";
for(var i = 0; i< data.length; i++){
items +="<option value='"+ data[i].toLowerCase() +"'>" + data[i] +"</option>";
}
$("#a1_title").append(items);
$("#a1_title").change();
});
$("#a1_title").change(function(){
$("#a2_title").html("");
$.getJSON("second_dropdown.php?tabs="+ $(this).val(),success = function(data){
alert("okay");
var items="";
for(var i = 0; i< data.length; i++){
items+="<option value='"+data[i].toLowerCase()+"'>"+data[i]+"</option>";
}
$("#a2_title").append(items);
});
});
});
</script>
</body>
</html>
答
Why don't you simply echo out the results?
<?php
$query = "select distinct levelone as Name from tab limit 1";
$res = pg_query($con, $query)
?>
<select name="dbname" id="dbname" >
<?php
while $row = pg_fetch_assoc($res) {
echo "<option>" . $row['levelone'] . "</option>";
}
?>
<select>
答
Usually what I do is rather than using two files why not echo the entire file from the PHP script thus the page loads when the result is returned from your query?