please i need help
i need to do specail command
when some value selected then show another dropdown box
my first dropdown box is in php
and he is my code :
$conn = mysqli_connect("localhost", "root",
"", "phoneunlock" )
or die("Cannot connect to database:" .
mysqli_connect_error($conn));
echo "<select name='selectedValue' class= 'dropdown' >";
echo '<option value="">'.'Please Select Service'.'</option>';
$sql = "SELECT id, manufacter FROM product";
$result = $conn->query($sql);
while($row = $result->fetch_assoc())
{ echo "<option value='" . $row['manufacter']. "'>" . $row['manufacter'] . '</option>';
}
echo '</select>';
and know i need some command like this :
if dropdown box selected = value then
do this
end if
sow please can any one help me
if you mean like chained combobox. try using jQuery like this :
$('#yourcomboid').on('change', function() {
var id = $(this).val();
$('#youranothercombo').empty();
$.ajax({
url: 'your-route-to-get-data/' + id,
success: function(data) {
$('#youranothercombo').empty();
for(var i = 0; i < data.length; i++) {
var item = data[i];
$('#youranothercombo').append($('<option></option>').val(item.column-name).text(item.column-name));
}
}
});
});
Hope this code works.
Related
Here I have one drop down menu on which selection other dropdown changes result the id of other dropdown is "style_code". Now I also want to change image on dropdown selection, it is like when I select color from dropdown it changes sizes which is other dropdown, but I also want to change image on color selection.
<script>
function getState(val) {
$.ajax({
type: "POST",
url: "check.php",
data:'id='+val,
success: function(data){
$("#style_code").html(data);
}
});
}
</script>
Here is check.php
<?php
$con=mysqli_connect("localhost","root","","db") or die(mysql_error());
if(!empty($_POST["id"])) {
$query ="SELECT * FROM stylecolor WHERE color_code = '" . $_POST["id"] . "'";
$results = mysqli_query($con,$query);
while ( ($row=mysqli_fetch_array($results))){?>
<option value="<?php echo $row["color_name"]; ?>">
<?php echo $row['size'] ; ?>
</option>
<?php
}
}
?>
Your difficulty comes from the fact that you are returning HTML code from the PHP script. My advice is to return JSON data then generate style_code children with jQuery.
It would be something like that :
check.php
<?php
$con = mysqli_connect("localhost", "root", "", "db") or die(mysql_error());
if(!empty($_POST["id"])) {
$query = "SELECT * FROM stylecolor WHERE color_code = '" . $_POST["id"] . "'";
$results = mysqli_query($con, $query);
$data = new stdClass(); // This object will carry the results
while (($row = mysqli_fetch_object($results))) {
$data->option[] = $row;
}
// Another query to get the image name
$query = "SELECT name FROM image_name WHERE color_code = '" . $_POST["id"] . "'";
$results = mysqli_query($con, $query);
if ($row = mysqli_fetch_object($results)) {
$data->image_name = $row->name;
}
header('Content-Type: application/json');
echo json_encode($data);
}
HTML & Javascript:
...
<div class="thumb-image" id="style_image" >
<img src="images/<?php echo $productimg1?>" data-imagezoom="true" class="img-responsive" alt="" />
</div>
...
<script language="javascript">
function getState(val) {
$.ajax({
type: "POST",
url: "check.php",
data: {id: val},
dataType:'json',
success: function(data) {
$("#style_code").children().remove(); // empty the dropdown
// Add new options in the dropdown from the result data
data.option.forEach(function (item) {
$("#style_code").append('<option value="' + item.color_name + '">' + item.size + '</option>');
});
// Change the 'src' attribute of the <img>
$("#style_image").find('img').attr('src', 'images/' + data.image_name + '?d=' + Date.now().toString());
}
});
}
</script>
I have two drop down list in the main page, when the user clicks on the country drop down(on change) another drop down list would be shown with the product list. This I accomplish using an ajax call (getproduts.php) from the country drop down list. The screen shots, the ajax call and the programs are attached .
The dropdown list works well and I can select the item too. The drop down list has the both the product description and the price in it.
I would like to get the price in a variable to be used in the main program when ever the user selects the option.
The sub total value(attached screen) in the main program should change with the price from the dropdown box when ever the user selects the product.
How can I achieve this?.
Ajax call
<script type="text/javascript">
function get_products()`enter code here`
{
var country = $("#country").val();
var type = $("#type").val();
var dataString = 'country='+ country + '&type=' + type;
$.ajax({
type: "POST",`enter code here`
url: "getproducts.php",
data: dataString,
success: function(html)
{
$("#get_products").html(html);
}
});
}
</script>
getproducts.php
<?php
error_reporting(1);
//print_r($_POST);
include('function/db_connect.php');
//session_start();
$price = Null;
//$items = Null;
if($_POST)
{
$var1 = $_POST['country'];
$var2 = $_POST['type'];
if ($var1 != '') {
echo "<label>Item<span style='color:red'>*</span></label><span style='color:red'></span></label><span class='address'>";
echo "<select id='items' name='items' style = 'width: 546px;' onChange='get_price(this.value)'>";
$sql = "SELECT * FROM tbl_product WHERE country_id = '$var1' AND type_id = '$var2'";
$db = new DB_CONNECT();
$result = mysql_query($sql);
$myarray = array();
echo "<option value=''>Select</option>";
while ($row = mysql_fetch_array($result)) {
$idp = $row["product_id"];
$iddes = $row["product_desc"];
$selp = $row["product_sell"];
$costp = $row["product_cost"];
echo "<option value='" . $idp . "'>" . $iddes . "==>".$selp ."</option>";
}
echo "</select><label>Item</label></span><span class='address'>";
}
echo "</div>";
echo "<br>";
echo "<div><label></label><span class='name'><button name = 'data' type ='button' onclick= 'valprice('items')'>Validate value</button></span></div>";
}
?>
Right now in your select html element, you're using onChange='get_price(this.value), this line of code only get the option value in this case only $idp = $row["product_id"];. If you want to select others field, then you need to attach those values into option itself during looping process occured. Here is the example usage.
In your option tag, change into this :
echo "<option value='" . $idp . "' data-price='" . $selp . "'>" . $iddes . "==>".$selp ."</option>";
You see i adding data-price='" . $selp . "' as a user defined attribute. This later on we fetch at onchange event.
After that, change your select HTML element onchange into this :
echo "<select id='items' name='items' style = 'width: 546px;' onChange='get_price(this)'>";
Finally, in your get_price() function tweak into this below code :
<script>
// array variable to store product details[id and price in this case]
var myProduct = [];
function getPrice(e) {
// set to empty for initial
myProduct.length = 0;
// fetch price
var price = $('option:selected', $(e)).data('price');
// fetch val ID
var valID = $(e).val();
// insert into array variable as a javascript object
myProduct.push({
ID : valID,
price : price
});
console.log(myProduct);
}
</script>
To fetch another fields, put another data-attributes like example above.
DEMO - check console to see the output
So I'm currently in the process of trying to populate a select option list with some SQL using ajax and php. I've tried various different pieces of code however I still can't seem to crack it. Here is the ajax from the actual page its self...
$.ajax ({
url:'orderentry_ajax.php',
cache:false,
data: {'request': 'getCounty', 'County': County},
dataType: 'json',
async: false,
success: function(data)
{
$('#errMsg').html(data.errMsg);
if(data.numRecs>0)
{
//divStr = divStr + data.custName + data.contactName + data.contactNumber + data.contactEmail;
countyStr = countyStr + "<select>";
for (var i=0; i<data.dataArray.length; i++)
{
countyStr = countyStr +
"<option value='data.dataArray[i].County'>" +
"Please Select" + data.dataArray[i].County + "</option>";
}
countyStr = countyStr + "</select>";
$('#Countys').html(countyStr);
}
}
//countyStr = countyStr + data.dataArray[i].County +
});
As far as I'm concerned I did a similar exercise except I was populating the options list with another table, I've made the two pieces of ajax and php identical and it still doesnt seem to want to work. Here is the php from the ajax page....
if (trim($request) =='getCounty')
{
//product update
$County = $_REQUEST['County'];
$errMsg = "";
$con = mysqli_connect('127.0.0.1', 'root', 'c0mplex', 'HRDatabase');
//Check if connect..
if (mysqli_connect_errno($con))
{
$errMsg = 'Could not connect to Database.' . mysqli_connect_error();
}
else
{
// passed record for submit
$qryStr = "SELECT * FROM county WHERE `county` = $County";
//echo $qryStr;
$result = mysqli_query($con, $qryStr);
if (mysqli_error($con))
{
//echo (mysqli_error($con));
$errFlg=1;
$errMsg="Error during update, please try again. " . mysqli_error($con);
}
else
{
while ($row = mysqli_fetch_array($result))
{
$County = $row['county'];
$rowing = array();
$rowing['county'] = $County;
$dataArray[] = $rowing;
}
$numRecs = mysqli_num_rows($result);
}
}
mysqli_close($con);
//to test error :
// $errMsg="testing error";
$info ->dataArray = $dataArray;
$info ->numRecs = $numRecs;
$info ->errMsg = $errMsg;
$info ->County = $County;
echo json_encode($info);
//echo $msg;
}
The select option list has an ID on it of 'Countys' just to give a heads up. Any help would be greatly appreciated guys.
Cheers
Replace below line in your ajax code for adding html dymically
countyStr = countyStr + "<option value='" + data.dataArray[i].County + "'>" + "Please Select" + data.dataArray[i].County + "</option>";
I have created a main drop down list and with jquery I can choose the number of drop down menus to display. Done very simply by a for loop. The main dropdown list to choose how many drop downs to display is statically populated and I am trying to dynamically populate the drop downs being displayed with data in mysql database. In the php side I am using a while loop to populate each select box. I am not getting any results being displayed. SITE
<script type="text/javascript">
$(document).ready(function () {
$('select').change(function() {
var option = $(this).val();
showFields(option);
return false;
});
function showFields(option){
var content = '';
for (var i = 1; i <= option; i++){
content += '<div id="course_'+i+'"><label>Course # '+i+'</label><br /><label>Course Name:</label> <select id="coursename_'+i+'"><option value="">--- Select ---</option>"'
<?php
$mysqli = new mysqli(DB_SERVER, DB_USERNAME, DB_PASSWORD, DB_DATABASE);
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$course_query = "SELECT course_id, course_name FROM course ";
if($result = mysqli_query($mysqli, $course_query)) {
while ($idresult = mysqli_fetch_row($result))
{
$course_id = $idresult[0];
$course_name = $idresult[1];
echo'<option value="' . $course_id . '">' . $course_name . '</option>';
}
}
?>
'"';
content += '</select><br /><div><br />';
}
$('#course_catalog').html(content);
}
});
</script>
You need to echo a javascript line to start with, instead of echoing directly...
echo 'content += \'<option value="' . $course_id . '">' . $course_name . '</option>\';';
i have one textbox and one dropdown box in each row.
now i want to enter some date in text box and select some value in dropdown.
when i click it should get saved into database.
How can i do this?
here is my code
php insert code:
When i click submit this php code should
<?php
mysql_connect("localhost", "tiger", "tiger") or die(mysql_error());
mysql_select_db("theaterdb") or die(mysql_error());
$query = mysql_query("INSERT INTO movie (movie_name,language) VALUES('$_POST[Fname]','$_POST[language]') ") or die(mysql_error());
?>
drop down is generated dynamically
code:
function create(param) {
'use strict';
var i, target = document.getElementById('screens');
target.innerHTML = '';
for(i = 0; i < param; i += 1) {
target.innerHTML +='</br>';
target.innerHTML +='New Movie '+i+' ';
target.innerHTML += '<input type="text" name="Fname">';
target.innerHTML +=' '+'Language '+' ';
target.innerHTML += "<?php
try {
$dbh = new PDO('mysql:dbname=theaterdb;host=localhost','tiger','tiger');
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
$sql = 'SELECT language FROM languages;';
$sth = $dbh->prepare($sql);
$sth->execute();
echo "<select name='language' id='course'>";
echo "<option>----Select Language----</option>";
while($row = $sth->fetch(PDO::FETCH_ASSOC)) {
echo "<option value='" . $row['language'] ."'>" . $row['language']. "</option>";
}
echo "</select>";
?>";
target.innerHTML +='</br>';
target.innerHTML +='</br>';
}
}
the ui looks something like this...
Add name
for text box and select box like this
name="text_box"+i and name="select_box"+i. "i"
is value from counter in loop, for example if you have 100 New Moview you will have name for each text box like this text_box1, text_box2. ..... text_box100. You should on submit remeber the numbers of "New MovieS" and that is "i" and in php code just loop for each element and save them. In first iteration you will have $_POST[Fname1] and $_POST[language1], etc..
Add a line in your js which makes the inputs to print something along the lines of target.innerHTML = '<input name="RowCount" value="' + param + '" hidden />' then in your PHP use:
for ($i=0; $i < $_POST["RowCount"]; $i++) {
$query = sprintf("INSERT INTO movie ('movie_name', 'language') VALUES ('%s', '%s')",
mysqli_real_escape_string($_POST["Fname"]), // Escaping values before inserting.
mysqli_real_escape_string($_POST["language"]));
mysqli_query($con, $query);
}
in HTML Form: Set textbox and dropdown element name as same algorithm ElementName+RowNumber;
insert element for RowCount: <input type="hidden" name="RowCount" value="3">
in PHP: get values:
for($iRow=0;$iRow less $_POST['RowCount'];$iRow++) {
mysql_query("INSERT INTO movie (movie_name,language) VALUES('".$_POST['Fname'.$iRow]."','".$_POST['language'.$iRow]."');
}