I have multiple checkboxes displayed from MySQL table. I'm trying to pass all checked values to <div> using ajax. Currently, my code only passes one checked value to <div>. I want to display all checked values in a <div>.
What I have thus far:
<?php
$sql="SELECT * FROM options WHERE cat_id='".$id."' AND opg_id='".$group."'";
$result = mysql_query($sql);
while($row = mysql_fetch_array($result)){ ?>
<input type="checkbox" name="<?php echo $row['op_id']; ?>" onClick="showPrice(this.name)" value="<?php echo $row['price']; ?>"/>
<!-- Display all prices from mysql table in checkbox. Pass `id` to ajax from name attribute. -->
<?php
} ?>
ajax
<script>
function showPrice(name) {
$.ajax({
url: 'ajax_price.php',
type: 'GET',
data: {option : name},
success: function(data) {
document.getElementById('c').innerHTML =data;
}
});
}
</script>
ajax_price.php
<?php
include ("../supplier/DB/db.php");
$id = $_REQUEST['option'];
<?php
$sql="SELECT * FROM options WHERE op_id='".$id."'";
$result = mysql_query($sql);
while($row = mysql_fetch_array($result)){
?>
<div class="oder">
<div class="odercol2"><?php echo $row['opt']; ?></div>
<div class="odercol3"><?php echo $row['price']; ?></div>
</div>
<?php
}
?>
This is the display with only one checked value in the <div>. I want to display all the checked values in my <div>.
checkboxes
Results display in this div (div id is "c")
Just change your AJAX function to concat the innerHTML of DIV, like this:
<script>
function showPrice(name) {
$.ajax({
url: 'ajax_price.php',
type: 'GET',
data: {option : name},
success: function(data) {
document.getElementById('c').innerHTML += data;
}
});
}
</script>
Notice this line document.getElementById('c').innerHTML += data;
Hope it works. Thanks
Add a class value in the checkbox
<?php
$sql="SELECT * FROM options WHERE cat_id='".$id."' AND opg_id='".$group."'";
$result = mysql_query($sql);
while($row = mysql_fetch_array($result)){ ?>
<input type="checkbox" class="sundarCheckBox" name="<?php echo $row['op_id']; ?>" onClick="showPrice(this.name)" value="<?php echo $row['price']; ?>"/>
<!-- Display all prices from mysql table in checkbox. Pass `id` to ajax from name attribute. -->
<?php
} ?>
Loop using the class name input elements
<script>
$(document).ready(function(){
function showPrice(value){
$.each($('.sundarCheckBox'), function(index, element){
if($(element).is(':checked')){
alert($(element).prop('value'));
}
});
}
});
</script>
Related
I have fetched some car brand names in a while loop and then for each brand name I make a select menu for the car names in another while loop by using the "brand id" as foreign key. And then I want to show the car names in a box each time someone changes the dropdown select options. Here's my code below :
$query = "SELECT * FROM brands";
$result = $db->query($query);
// Outer while loop
while($row = $result->fetch(PDO::FETCH_OBJ)){
$brand_id = $row->id;
?>
<div id="result"></div> <!-- The Ajax result will be shown here -->
<div><?php echo $row->brand_name ?></div>
<?php
$query2 = "SELECT * FROM cars WHERE brand_id = ?";
$result2 = $db->prepare($query);
$result2->execute(array($brand_id));
<select name="car" id="car">
// Inner while loop
while($row2 = $result2->fetch(PDO::FETCH_OBJ)){
?>
<option value="<?php echo $row2->id ?>"><?php echo $row2->car_name ?></option>
<?php
} // Closing Inner while loop
?>
</select>
<!-- Ajax -->
<script>
$(document).ready(function(){
$('#car').change(function(e){
e.preventDefault();
var car = $(this).val();
$.ajax({
url: "ajax.php",
type: "post",
data: {car: car},
success: function(data){
$('#result').html(data);
}
});
});
});
</script>
<?php
} // Closing outer while loop
In the ajax.php I have written the following code to echo the car name
$carName = $_POST['car'];
echo $carName;
But the issue is - it is just executed for the first option selected inside first inner loop of the first outer loop. I mean the ajax code only runs for the first iteration of the both loops.
I also tried to make the select menu and the result div unique by adding the "brand id" as follow :
<div id="result<?php echo $brand_id ?>"></div>
and
<select name="car" id="car<?php echo $brand_id ?>">
<option value="<?php echo $row2->id ?>"><?php echo $row2->car_name ?></option>
</select>
and also the ajax as following :
$('#car<?php echo $brand_id ?>').change(function(e){
e.preventDefault();
var car = $(this).val();
$.ajax({
url: "ajax.php",
type: "post",
data: {car: car},
success: function(data){
$('#result<?php echo $brand_id ?>').html(data);
}
});
But it didn't work. Please suggest your best possible solutions. Thank you.
Try my code
$query = "SELECT * FROM brands";
$result = $db->query($query);
// Outer while loop
while($row = $result->fetch(PDO::FETCH_OBJ)){
$brand_id = $row->id;
?>
<div id="result<?php echo $brand_id;?>"></div> <!-- The Ajax result will be shown here -->
<div><?php echo $row->brand_name ?></div>
<?php
$query2 = "SELECT * FROM cars WHERE brand_id = ?";
$result2 = $db->prepare($query);
$result2->execute(array($brand_id));
// Inner while loop
while($row2 = $result2->fetch(PDO::FETCH_OBJ)){
?>
<select name="car[]" id="car<?php echo $row2->id ?>">
<option value="<?php echo $row2->id ?>"><?php echo $row2->car_name ?></option>
</select>
<!-- Ajax -->
<script>
$(document).ready(function(){
$('#car<?php echo $row2->id ?>').change(function(e){
e.preventDefault();
var car = $(this).val();
$.ajax({
url: "ajax.php",
type: "post",
data: {car: car},
success: function(data){
console.log(data);
$('#result<?php echo $brand_id;?>').html(data);
}
});
});
});
</script>
<?php
}
}
The select and ajax code should be out of while loop. just check the code below
<?php $query = "SELECT * FROM brands";
$result = $db->query($query);
// Outer while loop
while($row = $result->fetch(PDO::FETCH_OBJ)){
$brand_id = $row->id;
?>
<div id="result"></div> <!-- The Ajax result will be shown here -->
<div><?php echo $row->brand_name ?></div>
<?php
$query2 = "SELECT * FROM cars WHERE brand_id = ?";
$result2 = $db->prepare($query);
$result2->execute(array($brand_id)); ?>
<select name="car" id="car">
<?
// Inner while loop
while($row2 = $result2->fetch(PDO::FETCH_OBJ)){
?>
<option value="<?php echo $row2->id ?>"><?php echo $row2->car_name ?></option>
<?php
} // Closing Inner while loop
?>
</select>
<!-- Ajax -->
<script>
$(document).ready(function(){
$('#car').change(function(e){
e.preventDefault();
var car = $(this).val();
$.ajax({
url: "ajax.php",
type: "post",
data: {car: car},
success: function(data){
$('#result').html(data);
}
});
});
});
</script>
<?php
} // Closing outer while loop
?>
``
You need not call ajax() in a while loop.
Simply you can call .change() on
<select name="car" onchange="getCar(this.value)">
<script type="text/javascript">
function getCar(car) {
$.ajax({
url: "ajax.php",
type: "post",
data: {car: car},
success: function(data){
$('#result').html('');
$('#result').html(data);
}
});
}
</script>
<div id="result"></div>
I have a form where there are select option and a textbox. All I want to do is when I select specific option, it will pass the id to query the same table to get another column's value based on ID of selected option and then display the value in a textbox before insert/update the table.
This code will works if both field in my form using select field. So in my opinion, maybe my script for storing value in input text field is totally wrong. Please correct me if I do wrong.
My form code :
<form name="inserform" method="POST">
<label>Existing Customer Name : </label>
<select name="existCustName" id="existCustName">
<option value="">None</option>
<?php
$custName = $conn->query("SELECT * FROM customers");
while ($row = $custName->fetch_assoc())
{
?><option id="<?php echo $row['customerID']; ?>" value="<?php echo $row['customerID']; ?>"><?php echo $row['customerName']; ?></option><?php
}
?>
</select>br>
<label>Current Bottle Balance : </label>
<input type="int" id="currentBal" name="currentBal"></input><br>
<input name="insert" type="submit" value="INSERT"></input>
</form>
My script code :
<script type="text/javascript">
$(document).on("change", 'select#existCustName', function(e) {
var existCustID = $(this).children(":selected").attr("id");
$.ajax({
type: "POST",
data: {existCustID: existCustID},
url: 'existingcustomerlist.php',
dataType: 'json',
success: function(json) {
var $el = $("input#currentBal");
$el.empty();
$.each(json, function(k, v) {
$el.append("'input[value='" + v.currentBal + "']").val();
});
}
});
});
</script>
existingcustomerlist.php code:
<?php
include 'config/config.php';
$result = $conn->query("SELECT * FROM customers WHERE customerID = '" .$_POST['existCustID'] . "'");
$results = [];
while ($row = $result->fetch_assoc()) {
$results[] = $row;
}
header('Content-Type: application/json');
echo json_encode($results);
?>
I need help to solve this.
I assume you are trying to show the results as input text element next to the #currentBal element. Try by changing the script tag inside the success callback as shown below.
$.each(json, function (k, v) {
$el.after("<input type='text' class="currentBalTemp" value='" + v.currentBal + "' />");
});
Make sure to remove the .currentBalTemp elements on change event of select otherwise duplication will be shown. Add the below code on change event.
$('.currentBalTemp').remove();
I am banging my head against a wall with this now so any help will go a long way with this one.
I am trying to get some data from a drop down list and update a database with the data selected.
This is my drop down list:
<form method="post" data-remote="true">
<select class="selectpicker" data-live-search="true" name="status[]">
<?php while($test3 = sqlsrv_fetch_array($test2, SQLSRV_FETCH_ASSOC)) : ?>
<option data-tokens="<?php echo $test3['Name']; ?>" value="<?php echo $test3['Name']; ?>">
</option
<?php endwhile; ?>
</select>
View Area
This is my ajax:
$(document).on('click', '#sim-area', function() {
$.ajax({
type: "POST",
url: 'sim-area.php',
data: {changeStatus: status},
success: function() {
"area switched"
}
});
});
and this is my page that is updating the databse (sim-area.php):
<?php
$userID = $user['userID'];
$selectedArea = $_GET['changeStatus'];
$queryAreaName = "
SELECT UserID, Name, U_NB, U_RTN
FROM Table
WHERE UserID = '$userID' AND Name = '$selectedArea'";
$getAreaname = sqlsrv_query($sapconn2, $queryAreaName);
$areaSwitch = sqlsrv_fetch_array($getAreaname, SQLSRV_FETCH_ASSOC);
$areaNB = $test2['U_NB'];
$areaRTN = $test2['U_RTN'];
//UPDATE TABLE
?>
No matter what I try I get an undefined error, I have changed it to hard code the values and in inserts fine, so I know everything is working fine, It just isn't passing the data through
Looks you are not passing data correctly to ajax call.
Below is updated code for dropdown (changed name of select and added id attribute):
<form method="post" data-remote="true">
<select class="selectpicker" data-live-search="true" name="status" id="changeStatus">
<?php while($test3 = sqlsrv_fetch_array($test2, SQLSRV_FETCH_ASSOC)) : ?>
<option data-tokens="<?php echo $test3['Name']; ?>" value="<?php echo $test3['Name']; ?>">
</option
<?php endwhile; ?>
</select>
Updated code for jquery (changed code for passing value of data):
$(document).on('click', '#sim-area', function() {
$.ajax({
type: "POST",
url: 'sim-area.php',
data: {changeStatus: $('#changeStatus').val()},
success: function() {
"area switched"
}
});
});
Actually I am developing one website where i want to assign orders to delivery staff and area or bakers from where he will pick up the delivery material.
Above picture shows area name and bakers from where delivery staff will pickup the delivery material. So for each order (row) i want to create 2 List Boxes and depending on selection of 1st listbox i want to change the content of 2nd listbox.
<select name="<?phpecho $CurrentOrders->comment_ID; ?>" id="courseid" style="width:100%;">
<option value="">-----Select Pick Up Area----</option>
<?php
$Area = DB::table('area')
->get();
foreach ($Area as $Area) {
?>
<option id="<?php echo $Area->area_id; ?>" value="<?php echo $Area->area_name; ?>"><?php $Area->area_name; ?></option>
<?php } ?>
</select>
</td>
Above code is to create dynamically listboxes.
</script>
<script type="text/javascript">
$(document).ready(function () {
$("#1").change(function () {
var id = $(this).val();
var dataString = 'id=' + id;
//alert(dataString);
$.ajax({
type: "POST",
url: "ajax_section.php",
//data: dataString,
data: {'id': id},
success: function (html){
$("#sectionid").html(html);
},
error: function () {
alert('Error');
}
});
});
});
</script>
Above script is to create the content of 2nd listboc based on selection of 1st listbox.
<?php
if($_POST['id']) {
$id=$_POST['id'];
$sql=DB::table('vendors')
->where('vendors_area','=',$id)
->get();
$count=0;
foreach($sql as $sql) {
$count++;
}
if ($count > 0) {
echo "<option selected='selected'>---- Select Section Name ---- </option>";
foreach($sql as $sql) {
$id=$sql->vendors_id;
$data=$sql->vendors_name;
echo '<option value="'.$id.'">'.$data.'</option>';
}
}
}
?>
And above code is to create and show the content of 2nd listbox based on selection of 1st.
But all this codes are working for only 1 listbox. It is not working dynamically Even if have changed written scripts for all listboxws as i written for 1st listbox(as #1).
please help me out.
You need to change
$("#1").change(function ()
to
$(document).on('change',"#1",function()
in your javascript code
I am trying to populate drop down lists one after the other. These drop down lists contain categories and subcategories. I would like to continue creating drop down lists until there are not more subcategories for a particular category.
I am populating my drop down lists with results from MySQL.
I have searched all over and could not find any references to cascading drop down lists using more than two lists.
My code works for two lists, but not for more.
partRequest.php
<HTML>
<HEAD>
<script type="text/javascript" src="..\jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#1").change(function(e) {
e.preventDefault();
getNextCategory("1");
});
$("#2").change(function(e) {
e.preventDefault();
getNextCategory("2");
});
$("#3").change(function(e) {
e.preventDefault();
getNextCategory("3");
});
});
function getNextCategory(htmlID) {
var categoryID = ""
var newHTMLID = 0
var newCategory = ""
categoryID = $("#" + htmlID ).val();
newHTMLID = Number(htmlID) + Number(1)
newCategory = "category" + newHTMLID
$.ajax({
type: "POST",
url: "findNextCategory.php",
data: "ID=" + categoryID + "&Number=" + newHTMLID,
success: function(output){
$("#" + newCategory).html(output);
}
});
}
</script>
</HEAD>
<BODY>
<form name="partSubmissionForm" id="partSubmissionForm" action="" method="POST">
<table width=147 cellpadding=0 cellspacing=0>
<tr><td><select id="1">
<?PHP
$query = "SELECT Name, ID FROM categories WHERE ParentID = 0";
$result = mysql_query($query);
while ($row=mysql_fetch_array($result)){
?>
<option value="<? echo $row['ID'];?>"> <? echo $row['Name'];?></option>
<?}?>
</select>
</td>
<td>
<div id="category2">
test2
</div>
</td>
<td>
<div id="category3">
test3
</div>
</td>
</tr>
<tr><td><input type="submit" name="submit" id="submit" value="GO"></td></tr>
</table>
</form>
</BODY>
</HTML>
findNextCategory.php
<?PHP
define('INCLUDE_CHECK',true);
include ('..\db.php');
$categoryID = $_POST['ID'];
$categoryFieldNum = $_POST['Number'];
echo $categoryID;
echo $categoryFieldNum;
$query = "SELECT Name, ID FROM categories WHERE ParentID = $categoryID";
echo $query;
echo "<select id=$categoryFieldNum>";
$query = "SELECT Name, ID FROM categories WHERE ParentID = $categoryID";
$result = mysql_query($query);
while ($row=mysql_fetch_array($result)){
$optionValue = $row['ID'];
$optionText = $row['Name'];
echo "<option value='$optionValue'> $optionText </option>";
}
echo "</select>";
?>
The problem is that your click function definitions only apply to items that are already on the page at page load. Because you do not yet have a select object on the page with an id of "2", your $("#2").change function does not ever get attached.
What you need to do to get around this is to apply that click definition after you add the select to the page. Try changing your success function to this:
success: function(output){
$("#" + newCategory).html(output);
$("#" + newHTMLID).change(function(e) {
e.preventDefault();
getNextCategory(newHTMLID);
});
}