stuck on a PHP program. Need some idea - php

Want to make a php program, where there will be a drop down which will contain some name of brands .. after selecting the " first drop down/ brands" products of the selected brand will show on another drop down.. need help . anyone ?

What you looking for is called a dependent select. It have barely nothing to do with php (except populating select options). I've found a demo for your case. You will need to install jquery to implement it in your code.
var $city = $(".city").on('change', function() {
$city.not(this).get(0).selectedIndex = this.selectedIndex;
});

You need to read about jQuery or CSS.
Look at this example (jQuery): http://dev7studios.com/dropit/

so you have to use ajax to do this
$(document).on("change","first select box",function(){
var id = $("first select box").val();
$.ajax({
url: "path to your file where you should write db code",
type: "POST",
dataType: "HTML",
async: false,
data: {"id": id},
success: function(data) {
$("second select box").html(data);
// here directly manipulate the data in controller or get the data in success function and manipulate .
}
});
})
in the file where you write db code
$a = "";
foreach(rows fro db as $a){
$a .= "<select value='db id'><?= name ?></select>";
}
echo $a;
we are capturing $a to out normal file add making that as the value for our second select box.
Hope it hlps

Use javascript function onchange select element and fetch records according to selected first select element value.
<form name="product" method="post" >
<select id="category" name="category" onChange="relodme()">
<option value=''></option>
<?php
$qry = "select * from category order by name";
$res = mysql_query($qry) or die ("MYSQL ERROR:".mysql_error());
while ($arr = mysql_fetch_array($res))
{
?>
<option value="<?=$arr['category_id']?>" <? if($_POST['category'] == $arr['category_id']) { ?> selected="selected" <? } ?> ><?=$arr['name']?></option>
<?
}
?>
</select>
<select id="Type" name="Type" >
<option value=''></option>
<?php
$qry = "select * from subcategory where category_id = '".$_POST['category']."' order by name";
$res = mysql_query($qry) or die ("MYSQL ERROR:".mysql_error());
while ($arr = mysql_fetch_array($res))
{
?>
<option value="<?=$arr['sub_category_id']?>" <? if($_POST['Type'] == $arr['sub_category_id']) { ?> selected="selected" <? } ?> ><?=$arr['name']?></option>
<?
}
?>
</select>
</form>
Javascript function:
function relodme()
{
document.forms[0].action="test1.php"; //your page name give here....
document.forms[0].submit();
}

Related

Auto populate text fields based on dropdown selection where all values come from a MYSQL table

I'm trying to auto populate some text fields (rate1 and rate2) based on a dropdown selection (instid and instfirstname). The values are all in one mysql table called tbl_insts. I'm trying the solution found in How to Get Content in text field dynamically, based on dropdown selection in php, but can't get it to work. Does anyone have any suggestions? Thanks in advance.
This is my mysql table called tbl_insts
instid instfirstname rate1 rate2
1 john 50 45
2 eric 25 45
This is my html form. I'm able to populate the dropdown correctly but not the text fields.
<select name="instfilter" id="instfilter">
<?php
if ($stmt = $conn->prepare("select instid, instfirstname from tbl_insts order by instid")) {
$stmt->execute();
$stmt->bind_result($instid, $instfirstname);
echo '<option value="-1" selected="selected">Please select...</option>';
while ($stmt->fetch()) {
echo '<option value="'.$instid.'">'.$instfirstname.'</option>';
}
$stmt->close();
}
?>
</select>
<!-- Fields that I want to populate based on the selection on top -->
<input type="text" name="rate1" id="rate1" />
<input type="text" name="rate2" id="rate2" />
This is my code before the tag
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js">
</script>
<script>
$('#instfilter').change(function(){
var inst = $(this).val();
$.ajax({
type:'POST',
data:{inst:inst},
url:'getrates.php',
success:function(data){
$('#rate1').val(data);
$('#rate2').val(data);
}
});
});
</script>
This is my code in getrates.php in the same directory as the html file above.
<?php
if (isset($_POST['inst'])) {
$qry = "select rate1, rate2 from tbl_insts where instid = ".
$_POST['inst'];
$rec = mysql_query($qry);
if (mysql_num_rows($rec) > 0) {
while ($res = mysql_fetch_array($rec)) {
echo $res['rate1'];
echo $res['rate2'];
}
}
}
die();
?>
try change data:{inst:inst} to data:{'inst':inst}
now you returning a string from getrates.php. From you code structure, you can do like this:
if (mysql_num_rows($rec) > 0) {
while ($res = mysql_fetch_array($rec)) {
echo $res['rate1']."|".$res['rate2'];
}
}
..and
success:function(data){
var inputs = data.split('|');
$('#rate1').val(inputs[0]);
$('#rate2').val(inputs[1]);
}
hope this helps.
Untested, but I think these changes should do the job.
while ($res = mysql_fetch_array($rec)) {
$result = [
'rate1' => $res['rate1'],
'rate2' => $res['rate2']
];
}
.......
die(json_encode($result));
and
success: function(data){
data = $.parseJSON(data);
$('#rate1').val(data.rate1);
$('#rate2').val(data.rate2);
}

Using JQuery Append From AJAX

I want to create a dropdown list that populated by another dropdown list. I'm using AJAX and PHP.
I have created my AJAX file like this:
<?php
if(isset($_POST['selname']))
{
include('config.php');
$clientId = $_POST['selname'];
$query = "SELECT tv.*, v.* FROM t_vorder tv LEFT JOIN m_vehicle v ON tv.tv_vehicleid = v.v_id WHERE tv_orderid = '$clientId'";
$result = mysqli_query($conn, $query);
while($row = mysqli_fetch_array($result, MYSQLI_ASSOC))
{
$namek = "";
$namek .= $row['v_id'];
if($row['v_jenis'] != "" || !empty($row['v_jenis']))
{
$namek .= ' - '.$row['v_jenis'];
}
if($row['v_platno'] != "" || !empty($row['v_platno']))
{
$namek .= ' - '.$row['v_platno'];
}
if($row['v_merk'] != "" || !empty($row['v_merk']))
{
$namek .= ' - '.$row['v_merk'];
}
$xx .= "<option value='$row[v_id]'>$namek</option>";
}
return $xx;
exit;
}
?>
After that, I called this AJAX file to my main program, here's my JQuery code:
function getVehicle()
{
var selname = $("select[name=noorder]").val();
$('#combobox2').html('');
$.ajax({ url: "getVehicle.php",
data: {"selname":selname},
type: 'post',
dataType: "json",
success: function(output) {
console.log(output);
$('#combobox2').append(output);
}
});
}
And last is my HTML code:
<select name="noorder" id="combobox" class="form-control">
//get my vehicle from database
<?php
$querycon = mysqli_query($conn, "SELECT * FROM m_order WHERE o_status='1' ORDER BY o_id");
while($rowcon = mysqli_fetch_array($querycon, MYSQLI_ASSOC))
{
$invoice = sprintf("%s%"."04d", $rowcon['o_code'], $rowcon['o_id']);
?>
<option value="<?php echo $rowcon['o_id']; ?>"><?php echo $invoice; ?></option>
<?php
}
?>
</select>
<select name="kendaraan" class="form-control" id="combobox2" onclick="getVechile();">
</select>
My Ajax works fine, my console log return that the file finished load. But my dropdown list not appended by Jquery. Anyone know where's my mistakes?
You did't request for json obj/data into ajax success callback, then no need for dataType: "json", inside ajax properties. Remove that and change return $xx; into echo $xx;
AJAX request gets data from PHP file only when its printed out on the page.
Returning and data from PHP (AJAX backend) to jQuery/Javascript does not mean anything.
Change
return $xx;
to
echo $xx;
You use the dataType: "json" in your ajax call, so it get response in JSON. First remove dataType: "json" line from ajax call. Then replace return $xx; with echo $xx; in your php script.
Hope this solution may works for you, Thanks!

How to update dynamically populated content with AJAX

I have some code which populates like so:
<select class="form-control" name="accommodation_ID" id="accommodation_ID">
<option value="-1">-- Please Select --</option>
<?php
$AccomodationID = 13; //For testing purposes
$accommodation_query = mysqli_query($conn,"SELECT ENTITIES.LastName,
ACCOMMODATION.AccomodationID, ACCOMMODATION.PUPoint
FROM ACCOMMODATION, ENTITIES WHERE ENTITIES.Entity_ID =
ACCOMMODATION.Entity_ID")
or die("Error: ".mysqli_error($conn));
while($accommodation_Results = mysqli_fetch_array($accommodation_query)){
if($accommodation_Results['AccomodationID'] == $AccomodationID){
echo '<option selected value="'.$AccomodationID.'">'.$accommodation_Results['LastName'].'</option>';
$PUPoint = $accommodation_Results['PUPoint'];
}
else{
echo '<option value="'.$AccomodationID.'">'.$accommodation_Results['LastName'].'</option>';
}
}
?>
</select>
<label>Pick Up Point</label>
<input type="text" name="PUPoint" readonly value="<?php echo $PUPoint; ?>">
This code works no problem, it checks the database and looks for a match, if it does, set is as the selected option, grab the PUPoint (Pickup point) variable and store it in the input field.
My problem now, is when I go to select a different option from the dropdown list, the pickup point input field doesn't update anymore. This is what I had, working before I implemented the above:
j$('select[name=accommodation_ID]').change(function(event) {
event.preventDefault();
var accommodationID = j$(this).val();
post_data = {'accommodation_ID':accommodationID};
var data = {
"action": "Accommodation_Details"
};
data = j$(this).serialize() + "&" + j$.param(data);
j$.ajax({
type: "POST",
dataType: "json",
url: "../include/booking_Modify.php",
data: data,
success: function(data) {
j$('input[name=PUPoint]').val( data["PUPoint"] );
},
error: function (request) {
console.log(request.responseText);
}
});
});
booking_Modify.php
//checks and switch statement related code
$return = $_POST;
$return["accommodation_ID"] = $_POST["accommodation_ID"];
$return["SQL"] = "SELECT * FROM ACCOMMODATION WHERE AccommodationID = ".$_POST["accommodation_ID"]."";
$query = mysqli_query($conn,"SELECT * FROM ACCOMMODATION WHERE AccomodationID = ".$_POST["accommodation_ID"]."")
or die("Error: ".mysqli_error($conn));
$row = mysqli_fetch_array($query);
$return["PUPoint"] = $row["PUPoint"];
$return["json"] = json_encode($return);
echo json_encode($return);
I've done some echoing/console.log and noticed that it's always passing the same Accommodation ID number (13) into booking_Modify.php. It doesn't change when I select a different option now. I don't know if it's because of the "selected" attribute applied to the option element now. Any ideas would be greatly appreciated
You have defined your $AccomodationID = 13; //For testing purposes before which is printed in every iteration of the while loop instead of the current ID. Probably you want to write $accommodation_Results['AccomodationID'] as the option value.

Getting value from dynamically created pop up menu

I have a menu that is dynamically created. When the user selects a value, I need to get that value and use it for a query statement. This is not a form, just a menu on the page.
I have:
<select name="topic" id="topic">
<option value="optiont" selected="selected">Select topic...</option>
<?php
while ($row = mysqli_fetch_array($sql))
{
echo "<option value=\"optiont$count\" name=\topic[]\">" . $row['topic'] . "</option>";
$count++;
}
?>
</select>
I want to know which option is selected. How can I do this??
This will get the value when you change the DDL:
$('#topic option').on("change", function () {
var opt_ID = $(this).val();
//Do something here using opt_ID as the value e.g.
window.location = '/URL/file.php?' + opt_ID;
});
Try this:
jquery:
var selvalue = $("#topic option:selected").val();
$.get( "demo.php?value="+selvalue, function(data) {
alert(data);
});
Demo.php:
<?php
$sel = $_GET['value'];
// write your query here
?>

jQuery sending the name of the selected value as empty? AJAX

$.post(
"ajax",
{
addItem : username.val(),
price : price.val(),
desc : desc.val(),
thumb : thumb.val(),
cat : cat.find(":selected").text(),
id : id.val()
},
function(data) {
error.html(data);
}
);
$_POST['cat'] will be empty
That means cat.find(":selected").text() doesn't function in this case.
echo '<select class="field2" name="category">
<option>Select Category</option>';
echo $shop->loadAlLCategories();
echo '</select>';
What did I do wrong in this case? Why is POST cat always empty no matter what I select?
public function loadAlLCategories()
{
$this->items = $this->pdo->prepare("SELECT * FROM categories");
$this->items->execute();
while ($row = $this->items->fetch(PDO::FETCH_ASSOC))
{
echo '<option value="'.$row['category_name'].'">'.$row['category_name'].'</option>';
}
}
you can use :
jQuery('.field2 option:selected').text();
you should take the value of the select
$('.field2').val()

Categories