I have here a dropdown select and autocomplete function. What I need to do is to pass the selected value of dropdown to autocomplete.php to use in my query. Textbox value should depending on value from dropdown. If selected value is supplies, all supplies only value in textbox (like pencil or ballpen).
I used this Ajax in Dynamic Dropdown. How I can use this to pass the value in autocomplete.php?
Note: this Ajax was not connected in my autocomplete function. How I can use this ajax to pass the value to my autocomplete.php query.
<script type="text/javascript">
$('#main').change(function(){
$.ajax({
url : 'getajax.php',
data :{mainlist_id : $(this).val()},
dataType:'html',
type:'POST',
success:function(data){
$('#sub').html(data);
}
});
});
</script>
Ajax.php
<script type="text/javascript" src="jquery.autocomplete.js"></script>
<script>
$(document).ready(function(){
$("#tag").autocomplete("autocomplete.php", {
selectFirst: true
});
});
</script>
Drop1
<?php
$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>
Auto Complete <input id="tag" type="text">
Autocomplete.php
<?php
$mysqli = new mysqli("localhost", "root", "", "2015") or die("Database Error");
$auto = $mysqli->real_escape_string($_GET["q"]);
$sql = $mysqli->query("SELECT * FROM code WHERE item LIKE '%$auto%' GROUP BY id ORDER BY item" );
if($sql)
{
while($row=mysqli_fetch_array($sql))
{
echo $row['item']."\n";
}
}
?>
$('#sub').html(data); should be $('#tag').html(data);
You have not defined #sub element in your html code, when placing this
$('#sub').html(data);
After that your name of the page must be same, while your using getajax.php, and its not you have defined us
Related
New in php and ajax, building a dropdown based on another dropdown through database.Up to now code is sucessfully running, you can check my code having two php pages, dropdown2.php and postbrand.php now just want to know how to use $brand variable value in postbrand.php to use in the sql query in second dropdown in dropdown2.php.
<?php
require 'connect.inc.php';
$query = "SELECT * FROM `brand` ";
$data = mysql_query($query);
?>
<!DOCTYPE html>
<html>
<head>
<title>Input form</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12/jquery.min.js"></script>
</head>
<body>
<form>
<label>Brand:</label>
<select name="brand" id="sb" onchange="myFunction()">
<?php
while($row=mysql_fetch_array($data))
{
?>
<option value="<?php echo $row['b_name'];?>">
<?php
echo $row['b_name'];
?>
</option>
<?php
}
?>
</select>
<br/><br/>
<label>Model:</label>
<?php
$query = "SELECT model.model, model.b_id from model inner join brand on model.b_id= brand.b_id where brand.b_name like 'sony'";
$result = mysql_query($query);
$select= '<select name="select" id="sm">';
while($rs=mysql_fetch_array($result)){ $select.='<option value="'.$rs['b_id'].'">'.$rs['model'].'</option>';
}
$select.='</select>';
echo $select;
?>
</form>
<div id="result"></div>
<script>
function myFunction() {
//alert('working!!');
var brand = $('#sb').val();
$.post('postbrand.php', {postbrand:brand},
function(data){
$('#result').html(data);
});
}
</script>
</body>
</html>
postbrand.php
<?php
$brand = $_POST['postbrand'];
echo $brand;
?>
If I get it correct you want to populate the second dropdown based on the chosen value of the first dropdown.
To steps to achieve this are:
listen to "change" event on the first dropdown (using JQ)
var selected = ""
$('select#sb').on('change', function() {
selected = $(this).val(); // get the chosen value
});
$.post("postbrand.php", selected, function(resp){ //send the selected value to postbrand.php which will return an array of elements from db based on what was selected
$.each(resp,function(key, val){ //traverse the response and
$('select#secondDropdown').append('<option>'+val+'</option>') //populate the 2nd dropdown
})
})
I'm stuck with this problem with in a week. I tried to set a onkeyup on datalist, only allow to submit within datalist autocomplete option value. I tried 2 different script but it has the same problem. When my option value is came via ajax, my textbox not allowing to type even if the value is in the option list. Why it is? Help please. I'm stuck with this :/
When I tried to echo the option list just like this
<input list="languages" id="none"></input>
<datalist id="languages" name="options">
<option value=""></option>
<?php echo $option1; ?>
</datalist>
the onkeyup works well. But when the value is came from ajax, the problem comes in. Why is that? Please help me with this.
index.php
Drop1
<?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['category'].'">'.$row['category'].'</option>';
}
?>
<select id="main" name="main">
<option value="" disabled="disabled" selected="selected">Choose</option>
<?php echo $option; ?>
</select>
<span id="result"> <input list="languages" id="none"></input>
<datalist id="languages" name="options">
<option value=""></option>
</datalist></span>
<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>
$(document).ready(function() {
var validOptions =[];
$("#languages option").each(function(){
validOptions.push($(this).val())
});
$("#none").autocomplete(validOptions, { mustMatch: true });
});
$('input#none').result(function(event, data, formatted) {
$("#result").html(!validOptions ? "No match found!" : "Selected: " + formatted);
}).keyup(function() {
$(this).search();
$(this).css("background-color", "#D6D6FF");
});
</script>
Ajax
<?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");
$option1 = '';
while($row = $result1->fetch_assoc())
{
$option1 .= '<option value = "'.$row['item'].'">'.$row['item'].'</option>';
}
echo $option1;
}
?>
Try this:
success: function (data) {
$('#languages').html(data);
$("#languages option").each(function(){
validOptions.push($(this).val())
});
}
I am attempting to make dynamic dropdown boxes a search tool to help narrow down display data from a mysql server. I am a decent php programmer but need help with the javascript and ajax.
The site currently consists of 3 pages: index_test.php, dropdown.php and dropdown2.php.
On index_test.php there are 4 dropdown menus that need to be populated with information. The first is populated with state names from a mysql table using php when the page loads. The second box is populated using .change() that references php code and and displays schools in the selected state from a mysql table.
The third box is supposed to then take the selected value from the second box and display the class names from the selected school to the user and that step is where the code is breaking. The php works when tested by submitting the form but I would like to be able to fill the last 2 boxes without a page refresh.
The format of the mysql tables are:
table schools: (school_id, schools, states)
table classes: (class_id, school_id, class_abrv, class_number)
Thank you for your help
The code for index_test.php:
<?php include_once("connect.php"); ?>
<html>
<head>
<title>ajax</title>
<script src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#state").change(function(){
var state = $("#state").val();
$.ajax({
type:"post",
url:"dropdown.php",
data:"state="+state,
success: function(data) {
$("#school").html(data);
}
});
});
$("#school").change(function(){
var state = $("#school").val();
$.ajax({
type:"post",
url:"dropdown2.php",
data:"school="+school,
success: function(data) {
$("#classname").html(data);
}
});
});
});
</script>
</head>
<body>
<h1>Get Notes:</h1>
<br/>
<form action="dropdown2.php" method="post">
State: <select id="state" name="state">
<option>--Select State--</option>
<?php
$sql = "SELECT states FROM states";
$result = mysql_query($sql);
while ($output = mysql_fetch_array($result)) {
$state_name = $output['states'];
echo "<option value=\"$state_name\">$state_name</option>";
}
?>
</select>
<br/>
School: <select id="school" name="school">
<option>--Select School--</option>
</select>
<br/>
Class Name: <select id="classname" name="classname">
<option>--Select Class Name--</option>
</select>
<br/>
Class Number: <select id="classnumber" name="classnumber">
<option>Select Class Name</option>
</select>
<br/>
<input type="submit" value="Search" />
</form>
</body>
</html>
Dropdown.php:
<?php
include_once("connect.php");
$state=$_POST["state"];
$result = mysql_query("select schools FROM schools where states='$state' ");
while($school = mysql_fetch_array($result)){
echo"<option value=".$school['schools'].">".$school['schools']."</option>";
}
?>
Dropdown2.php
<?php
include_once("connect.php");
$school=$_POST['school'];
$result = mysql_query("SELECT school_id FROM schools WHERE schools='$school' ");
$school_id = mysql_fetch_array($result);
$id = $school_id['school_id'];
$classname = mysql_query("SELECT DISTINCT class_abrv FROM classes WHERE school_id='$id' ORDER BY class_abrv asc");
while($class = mysql_fetch_array($classname)){
echo"<option value=".$class['class_abrv'].">".$class['class_abrv']."</option>";
}
?>
in second ajax function you have assigned the school drop down box value to state variable but you pass the variable school to ajax post. So there is no school variable that is why you get error.
$("#school").change(function(){
var *state* = $("#school").val();
//above variable should be school.
$.ajax({
type:"post",
url:"dropdown2.php",
data:"school="+*school*,
success: function(data) {
$("#classname").html(data);
}
});
});
I have been following This solution1 to create a drop down list the changes based on the users previous selection in another dropdown higher in the page. However I was unsure what I need to do at the Options would have been initially populated here
Thanks
<?php
mysql_connect('localhost');
mysql_select_db("test");
$result = mysql_query("SELECT * FROM `contents` WHERE `parent` = 0");
echo "<select name='name'>";
while(($data = mysql_fetch_array($result)) !== false)
echo '<option value="', $data['id'],'">', $data['name'],'</option>'
?>
<select onchange="ajaxfunction(this.value)">
<!-- Options would have been initially populated here -->
</select>
<select id="sub">
</select>
<script type="text/javascript"> function ajaxfunction(parent)
{
$.ajax({
url: 'process.php?parent=' + parent;
success: function(data) {
$('#sub option').remove(); //// here sub is the id of second select box
$('#sub').append(data)
}
});
}
</script>
**<select onchange="ajaxfunction(this.value)">
**<!-- Options would have been initially populated here -->**
</select>**
<script type="text/javascript">
function ajaxfunction(parent)
{
$.ajax({
url: 'process.php?parent=' + parent;
success: function(data) {
$('#sub option').remove(); //// here sub is the id of second select box
$('#sub').append(data)
}
});
}
</script>
/// script section may be any where on your page
<select id="sub"> ////second select box
</select>
I pull data from a MYSQL database to populate a Drop down
<td class="<?php print $Bank_ca_error;?>">Bank Name</td> <td> <select name="Bank" id="Bank" tabindex=24 style="color: <?php print $TextColour;?>"/> <option><?php print $_SESSION['Bank_ca'] ;?></option> <?php //Get Data to populate drop down $BankQuery = "SELECT BankName FROM tblbank ORDER BY BankName"; $BankResult = mysql_query ($BankQuery); While($nt=mysql_fetch_array($BankResult)) { print"<option $nt[BankName]>$nt[BankName]</option>"; } ?> </select> </td>
I would like based on the value selected populate a text input. So Basically Select the Bank from the List and have it autopopulate the Universal Branch Code in the text input.
I saw an example using Jquery, But I am a complete noob when it comes to this and I cannot get it to work properly
I added the following in the Head section
<script type="text/javascript" src="jquery-1.4.2.min.js"></script> <script type="text/javascript"> jQuery(document).ready(function(){ jQuery('#Bank').live('change', function(event) { $.ajax({ url : 'getData.php', type : 'POST', dataType: 'json', data : $('#myform').serialize(), success: function( data ) { for(var id in data) { $(id).val( data[id] ); } } }); }); }); </script>
I then Added this into the getData.php file
<?php include "../../../includes/dbinfo.inc"; //Connect to database mysql_connect($db_host, $db_username, $db_password); #mysql_select_db($db_database) or die("Unable to select database"); $BankName = $_POST['Bank']; // Selected Bank $query = "SELECT * FROM tblbank WHERE BankName ='{$BankName}'"; $result = mysql_query($query); $row = mysql_fetch_array($result) $BranchCode = $row['UniversalCode']; $arr = array( 'input#BranchCode' => $BranchCode ); echo json_encode( $arr ); ?>
and added the Following to around the inputs and dropdown concerned
<form id='myform'> </form>
I tried to use a solution elsewhere on this site but could not get it to work
Your assistance is greatly appreciated
If I understand correctly what you're trying to do, then you do not need ajax, try something like this
<?php
include "../../../includes/dbinfo.inc";
//Connect to database
mysql_connect($db_host, $db_username, $db_password); #mysql_select_db($db_database) or die("Unable to select database");
$res = mysql_query("SELECT UniversalCode, BankName FROM tblbank ORDER BY BankName");
while($row = mysql_fetch_assoc($res)) {
// associative array of banks
$banks[$row['UniversalCode']] = $row['BankName'];
}
?>
<script type="text/javascript" src="jquery-1.4.2.min.js"></script>
<script type="text/javascript">
$(document).ready( function() {
$('#Bank').change( function() {
// enter in an empty field code of the selected bank
$('#UniversalCode').val( $(this).val() );
});
});
</script>
<td class="<?php print $Bank_ca_error;?>">Bank Name</td>
<td>
<select name="Bank" id="Bank" tabindex=24 style="color: <?php print $TextColour;?>"/>
<? foreach($banks as $code=>$name) { ?>
<option value="<?=$code?>"><?=$name?></option>
<? } ?>
</select>
<input value="" id="UniversalCode">
</td>