I'm having trouble getting my variable to post in my form. I use jquery to load a box if the user wants to enter a new sub category.
Here is the select in the form
<select id="sub_cat1" name="sub_cat1">
<option value=""></option>
<option value="new">New Sub Cat</option>
<?php
$query = "SELECT sub_category FROM blog_posts GROUP BY sub_category";
$data = mysqli_query($dbc, $query);
if (mysqli_num_rows($data) > 0) {
while ($row = mysqli_fetch_array($data)) {
$sub_category = $row['sub_category'];
echo '<option value="' . $sub_category . '">' . $sub_category . '</option>';
}
}
?>
</select>
<div id="load_sub_cat_box"></div>
This is the jquery
$(document).ready(function(){
$("#sub_cat1").on("keyup change", function() {
var prod = $("#sub_cat1").val();
if(prod == 'new'){
$("#load_sub_cat_box").append('<div style="padding-top:15px;">Enter New Sub Category</div><input type="text" name="sub_cat2" />');
}
});
});
And here is the form validate code
if($_POST['sub_cat1'] == "new"){
$sub_cat = mysqli_real_escape_string($dbc, trim($_POST['sub_cat2']));
}
else{
$sub_cat = mysqli_real_escape_string($dbc, trim($_POST['sub_cat1']));
}
If I select new, the box does load on the page but for some reason when form is submitted it will not load a variable for $sub_cat1. Is there something I don't know about jquery and forms?
You have two select elements with id="sub_cat1".
ids must be unique per page.
It is also invalid HTML, with a select inside a select.
Related
I have a table on my database called "measurements", and another for "units";
The "measurements" table has a column for id and name. The "units" table has a column for id, name and measurement_id.
The idea is that, when the user selects a measurement from the dropdown, it will display then, another dropdown with the units found for that measurement.
I guess I have to do it with "ajax". I have done some basics, retrieving information from a html file, but I don't know how to link that with retrieving information from a database.
On measurement.php:
public function display_measurements() {
include 'includes/db_connection.php';
try {
$sql = "SELECT id, name FROM measurements";
$results = $conn->prepare($sql);
$results->execute();
} catch(PDOException $e) {
echo 'Error: ' . $e->getMessage() . '<br />';
return array();
}
return $results->fetchAll(PDO::FETCH_ASSOC);
}
public function get_units_for_measurement($measurement_id = ':measurement_id') {
include 'includes/db_connection.php';
try {
$sql = "SELECT measurements.id, units.id, units.name "
. "FROM measurements "
. "JOIN units "
. "ON measurements.id=units.measurement_id WHERE measurements.id=:measurement_id";
$result = $conn->prepare($sql);
$result->bindParam(':measurement_id', $measurement_id, PDO::PARAM_INT);
$result->execute();
} catch(PDOException $e) {
echo 'Error: ' . $e->getMessage() . '<br />';
return array();
}
return $result->fetchAll(PDO::FETCH_ASSOC);
}
Select to display the measurements: (it is part of a bigger form, but the rest is irrelevant, so I have added the form tag just to place you on my code):
<form id="newRecipe" method="POST" action="new_recipe.php">
.......
<label for="measurements" class="required">Measurements</label>
<select name="measurements" class="selectMeasurement">
<option disabled selected value> -- select a measurement -- </option>
<?php
$measurements = $measurementObj->display_measurements();
foreach ($measurements as $measurement) {
echo '<option value="' . $measurement['id'] . '" ';
echo '>' . $measurement['name'] . '</option>';
}
?>
</select>
//display select values based on measurement_id
<label for="units" class="required">Units</label>
<select name="units">
<option disabled selected value> -- select a unit -- </option>
<?php
$units = $measurementObj->get_units_for_measurement($measurement['id']);
foreach ($units as $unit) {
echo '<option value="' . $unit['id'] . '" ';
echo '>' . $unit['name'] . '</option>';
}
?>
</select>
.....
</form>
Then, on my scripts I have this to retrieve the selected value:
$(document).ready(function() {
$('#newRecipe').on('change','.selectMeasurement', function(){
var selectedMeasurementId = this.value;
return selectedMeasurementId;
});
});
But now..... I don't know how to proceed. At the moment, I am returning the value of the measurement_id selected, but how can I "send" that value to mysql query? So, what I don't want is to have to send the form or reload the page to show the select with the units id; so.... that's why I think it must be done with ajax.... right?
Anyone can give me a hint about how to proceed?
Thank you
I have another suggestion: fully populate everything with PHP, then use javascript to listen for changes to the selected dropdowns and update the options appropriately.
I'm printing a select list from my database.
Here's a part of my code:
<form action="" method="post">
<div class="form-item">
<select name="specialties">
<?php
$query = "SELECT * FROM specialties";
$result = mysqli_query($connection, $query);
echo '<option value="All">' . $filterTitle . '</option>';
while($row = mysqli_fetch_assoc($result)) {
$id = $row['id'];
$title = $row['title_'. $lang];
if($_POST['specialties'] == $id) {
$selected = 'selected';
}
echo '<option value="' . $id . ' "' . $selected . '>' . $title . '</option>';
}
?>
</select>
</div>
<div class="form-item">
<input class="form-submit" type="submit" name="submit" value="<?php echo $filterSubmit; ?>">
</div>
</form>
In this form when I choose some of the options, it filters the content. That's working properly and I don't need to post that part of the code.
First when I choose some option from the select list and after submit, it filter the content, but the select option shows the All value, instead of the selected option. After that I've tried with the code above and now when I submit the form, the select value shows the last option and all the options has selected attribute.
How can I change that logic, so when I select let's say the second option, after submitting the form, the selected attribute will appear only on the second option, so the text will be the second option?
CONCLUSION:
Thank you guys for your answers. You're all correct. I gave you all +1 and I choose the Hassaan's answer, because it's very well explained.
Currently you are checking/comparing values and generating variable. You need to use else condition because you must change/reset the value of generated variable. See the example below.
if($_POST['specialties'] == $id) {
$selected = 'selected';
}
else
$selected = '';
Add an else clause to reset the selected attribute to an empty string.
if($_POST['specialties'] == $id) {
$selected = 'selected';
}
else{
$selected = '';
}
You need to make empty selected variable every time like below
while($row = mysqli_fetch_assoc($result)) {
$selected = '';
$id = $row['id'];
$title = $row['title_'. $lang];
if($_POST['specialties'] == $id) {
$selected = 'selected';
}
echo '<option value="' . $id . ' "' . $selected . '>' . $title . '</option>';
}
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
I'm trying to pass select option value through url.selection value come from mysql table.i want to pass that driver name to another page.
<?php
//another select query goes here.
$query1= "SELECT * FROM driver WHERE status='Available'" ;
echo '<td>'.'<select name="driver">';
$result1= mysql_query($query1);
while($row1 = mysql_fetch_assoc($result1))
{
echo '<option value="'.$row1["name"].'">'.$row1["name"].'</option>';
}
echo '</select>'.'</td>';
echo'<a rel="facebox" href=db_confirm_booking.php?id='.$row["id"].'&driver='.$_POST['driver'].'>' . 'Confirm' . '</a>';
?>
Use jQuery.
Call change event of the drop down.
$(function(){
$("[name=driver]").die('change').live('change', function(){
var driver = $(this).val();
if (typeof driver !== 'undefined') {
window.location.href = 'YOUR_FILE.php?driver='+driver;
}
});
});
And
in your YOUR_FILE.php, get driver using $_GET['driver']
Or if you want the form to be more secure, take a hidden variable.
On change of driver, assign it the value of driver drop down.
And post the form.
In your PHP file, get it as $_POST['hid_driver'].
U can add onclick function for the select field, try this way
<?php
//another select query goes here.
$query1= "SELECT * FROM driver WHERE status='Available'" ;
echo '<td>'.'<select name="driver" onchange="window.location.href=\'db_confirm_booking.php?driver=' . $_POST['driver'] . '&id=\'+this.value">';
$result1= mysql_query($query1);
while($row1 = mysql_fetch_assoc($result1))
{
echo '<option value="'.$row1["name"].'">'.$row1["name"].'</option>';
}
echo '</select>'.'</td>';
echo'<a rel="facebox" href=db_confirm_booking.php?id='.$row["id"].'&driver='.$_POST['driver'].'>' . 'Confirm' . '</a>';
?>
try this code
<?php
//another select query goes here.
$query1= "SELECT * FROM driver WHERE status='Available'" ;
echo '<td>'.'<select name="driver"
onChange="window.location.href=this.value">';
$result1= mysql_query($query1);
while($row1 = mysql_fetch_assoc($result1))
{
echo '<option value="db_confirm_booking.php?id='.$row["id"].'&driver='.$_POST['driver'].'">"'.$row1["name"].'">'.$row1["name"].'</option>';
}
echo '</select>'.'</td>';
echo'<a rel="facebox" href=db_confirm_booking.php?id='.$row["id"].'&driver='.$_POST['driver'].'>
' . 'Confirm' . '</a>';
?>
example code
<select onChange="window.location.href=this.value">
<option value="www.google.com">A</option>
<option value="www.aol.com">B</option>
</select>
<select name="sel" id="sel" onchange="seturl(this.value)">
<option value=""></option>
</select>
<script>
function seturl(id)
{
document.forms[0].action="test.php?driver="+id;
document.forms[0].submit();
}
</script>
It will reload the page with driver name in url.
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>\';';