Multiple dynamic drop down select menus not working - PHP MySQL Jquery - javascript

I am building a form that will have three related drop down menus. First one is store locations, second Equipment at this location, third is components at this location.
So when I pick a location the page sends an AJAX request to load the select values for the equipment at this location. And when I pick the equipment it should load the components that belong to that equipment.
The third drop down for components is what's not appearing.
So my first drop down goes like this off the main file with the divs where the drop downs are added via AJAX calls:
<div class="input-group">
<strong>Select A Store Location:</strong>
<select class="form-control selectDesk" name="Location_ID" id="Location_ID">
<option value=1>HT1</option>
<option value=2>HT2</option>
<option value=3>HT3</option>
<option value=4>HT4</option>
<option value=5>HT5</option>
<option value=6>HT6</option>
</select>
</div>
<div id="equipment">
</div>
<div id="component">
</div>
The second drop down is dynamic loaded off a different file and inserted in a div via Jquery and AJAX. This is the code to make that happen
<?php
include('DBConnect.php');
$locID = $_POST['loc_id'];
$equipSQL ="SELECT Equipment_ID, Equipment_Name FROM Equipment WHERE Location_ID = $locID";
$equipResult = $my_dbhandle->query($equipSQL);
$numResults = $equipResult->num_rows;
?>
<strong>Select Equipment:</strong>
<div class="input-group">
<select class="form-control" name="Equipment_ID" id="Equipment_ID" style="min-width: 375px;">
<option value="0">No Equipment Needed For This Task</option>
<?php
for ($i=0; $i < $numResults; $i++){ //this will loop through the results and print them in the drop down menu
$row = $equipResult->fetch_assoc(); //Parse result into rows
echo "<option value=" . $row['Equipment_ID'] . ">" . $row['Equipment_Name'] . "</option>\n";
}
?>
</select>
</div>
And my third drop down is also loaded off another file via Jquery and AJAX
<?php
include('DBConnect.php');
$equipID = $_POST['equip_id'];
$compSQL ="SELECT Component_ID, Component_Name FROM Components WHERE Equipment_ID = $equipID";
$compResult = $my_dbhandle->query($compSQL);
$numResults = $compResult->num_rows;
?>
<strong>Select Component:</strong>
<div class="input-group">
<select class="form-control" name="Component_ID" id="Component_ID" style="min-width: 375px;">
<option value="0">No Component Needed For This Task</option>
<?php
for ($i=0; $i < $numResults; $i++){ //this will loop through the results and print them in the drop down menu
$row = $compResult->fetch_assoc(); //Parse result into rows
echo "<option value=" . $row['Component_ID'] . ">" . $row['Component_Name'] . "</option>\n";
}
?>
</select>
</div>
The Jquery is as follows:
<script>
$("#Location_ID").change(function(){
var locID = "";
var locID = $('#Location_ID').val();
$.ajax({
type: 'post',
url: 'equipDropDownByLocRepeatingTask.php',
data: 'loc_id=' + locID,
success: function (r) {
$('#equipment').html(r);
}
});
}).change();
$("#Equipment_ID").change(function(){
var equipID = "";
var equipID = $('#Equipment_ID').val();
$.ajax({
type: 'post',
url: 'compDropDownByLocRepeatingTask.php',
data: 'equip_id=' + equipID,
success: function (r) {
$('#component').html(r);
}
});
}).change();
</script>
So again, the first AJAX request for the second equipment drop down is loaded just fine. But the third drop down for the component select is not.
Thank you in advance for your help!

Hi I have modified your code please use this.
If this will work then I will explain the script
<script>
$("#Location_ID").change(function(){
var locID = "";
var locID = $('#Location_ID').val();
$.ajax({
type: 'post',
url: 'equipDropDownByLocRepeatingTask.php',
data: 'loc_id=' + locID,
success: function (r) {
$('#equipment').html(r);
initSecond();
}
});
}).change();
function initSecond(){
$("#Equipment_ID").change(function(){
var equipID = "";
var equipID = $('#Equipment_ID').val();
$.ajax({
type: 'post',
url: 'compDropDownByLocRepeatingTask.php',
data: 'equip_id=' + equipID,
success: function (r) {
$('#component').html(r);
}
});
}).change();
}
</script>

Try to execute this javascript :
$("#Equipment_ID").change(function(){ ....
... after the first ajax call, like this:
success: function (r) {
$('#equipment').html(r);
$("#Equipment_ID").change(function(){
...
...
}
}
Also the third dropdown should be:
<select name="Component_ID" and id="Component_ID" ...

Related

After ajax rerun php

I have an select menu that submits without reloading the page as follows:
<select id="option" name="option">
<option value="15">15/option>
<option value"30">30</option>
<option value"90">90</option>
</select>
It will submit to the current page as follows, without reloading the page
<script type="text/javascript">
$('#option').change(function(){
var option_val = $(this).val();
$.ajax({
type: 'post',
url: "$_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];",
data: "option="+option_val,
success: function(data)
{
window.alert(data)
}
});
});
</script>
The result of a change in the option menu is an popup window with all the code of the page echoed back.
What i want to do on the page is use the $_POST['option'] that is submitted and recalculate a price for example
<body>
//some code and div's
<?php
if (isset($_POST['option'])) {
$option = $_POST['option'];
$price= $row_product['price'] + $option;
echo $price;
} ?>
</body>
The are several places where I would like to use the submitted option value
Any help welcome
Sorry if it is very obvious
The only way is making a PHP page that does the calculation
HTML/page1.php
<select id="option" name="option">
<option value="15">15</option>
<option value="30">30</option>
<option value="90">90</option>
</select>
<div id="dynamic">
<p>DEFAULT CONTENT</p>
</div>
HTML/page2.php
$option = 0;
if(isset($_GET["option"])){
$option = $_GET["option"];
}
//do calculations
echo "<my-html-stuff>lorem ipsum</my-html-stuff>";
JS
var dynamic = $("#dynamic");
$('#select').on("change", function() {
var selected = $(this).val();
dynamic.load("page2.php?option=" + selected, function() {
dynamic.html("<p>CONTENT OPTION "+selected+"</p>");
});
});
Fiddle ==> https://jsfiddle.net/tonysamperi/4dbwwn3g/
WITH JSON
page2.php
header('Content-Type: application/json');
$option = 0;
if(isset($_GET["option"])){
$option = $_GET["option"];
}
$response = ["result" => $option];
echo json_encode($response);
JS
$('#select').on("change", function() {
var selected = $(this).val();
$.get("page2.php?option=" + selected, function(response) {
//do stuff with data
console.debug("RESPONSE", response);
});
});

Set initial value of dropdown output constructed with ajax

I have the following dropdown list which changes the output of <div id="item"></div> with ajax when select option is changed. I'm not using select2.
<?php
$biqsQuery = "SELECT biq.biqid, biq.name FROM biq";
$biqs = $db->query($biqsQuery);
?>
<select name="itemselector" id="itemselect">
<?php foreach ($biqs ->fetchAll() as $biq): ?>
<option value="<?php echo $biq['biqid']);?>">
<?php echo e($biq['name']);?>
</option>
<?php endforeach; ?>
</select>
<div id="item"></div>
PHP File:
if(isset($_GET['itemselector'])){
$biqQuery = "SELECT biq.biqid, biq.name, biq.img
FROM biq
WHERE biq.biqid= :biqid ";
$biq= $db ->prepare($biqQuery);
$biq->execute(['biqid' => $_GET['itemselector']]);
$selectedBiq=$biq->fetch(PDO::FETCH_ASSOC);
echo '<img src="'. $selectedBiq['img']. '">';
}
Javascript File:
$('#itemselect').on('change',function(){
var self = $(this);
$.ajax({
url: '../helpers/biq.php',
type: 'GET',
data: {itemselector : self.val()},
success: function(data){
$('#item').html(data);
}
});
});
It's currently succesfully changing the output, no problem on that part.
But when the page is first loaded, it shows the first value of the table on the dropdown menu, however it doesnt output the image of that first value into <div>.
What i need is; when the page is loaded i need the first entry in the database to be outputted into the <div id="item"></div> automatically.
Any help is appreciated, thanks in advance.
you could write on body load event to accomplish this. please correct if any type mistake will there but this will help you to get it rid
$(document).ready(function(){
var first = $("#itemselect option:first").val();
$.ajax({
url: '../helpers/biq.php',
type: 'GET',
data: {itemselector : first},
success: function(data){
$('#item').html(data);
}
});
});

Append json data to HTML List box

HTML code is :
<select name="ser" id="ser" class="form-control" onchange="getPrice(this.value);">
<option value="">--Select--</option>
<option value="Value11">Value1</option>
<option value="Value2">Value2</option>
</select>
<select name="freeitem" id="freeitem" class="form-control">
</select>
Js Code :
function getPrice(val) {
$.ajax({
type: 'post',
url: 'get_sales_price.php',
data: {
get_option: val
},
dataType: 'json',
success: function(response) {
console.log(response)
$('#freeitem').html(response.fritm);
}
});
}
and Php Code is :
$option = $_POST['get_option'];
$data = array();
$prdqty = $db->execute("select product_name from master_purchase where product_code='$option' and delet='0'");
while ($tqty = $prdqty->fetch_assoc())
{
$data['fritm'] = '<option value="'.$tqty['product_name'].'">'.$tqty['product_name'].'</option>';
}
echo json_encode($data);
while we selecting first selectbox content, need to add some data to second select box from database, we almost done the things but the second select box didn't show any values ,please help us to resolve the above problem
I tried your code with some hard code value and it perfectly working fine:-
Html+Jquery (in single page with .html extension):-
<select name="ser" id="ser" class="form-control" onchange="getPrice(this.value);">
<option value="">--Select--</option>
<option value="Value11">Value1</option>
<option value="Value2">Value2</option>
</select>
<select name="freeitem" id="freeitem" class="form-control">
</select>
<script src="https://code.jquery.com/jquery-1.12.0.min.js"></script><!-- added jquery library-->
<script type="text/javascript">
function getPrice(val) {
$.ajax({
type: 'post',
url: 'get_sales_price.php',
data: {
get_option: val
},
dataType: 'json',
success: function(response) {
console.log(response)
$('#freeitem').html(response.fritm);
}
});
}
</script>
Php (with hard-coded value):-
<?php
$option = $_POST['get_option'];
$data = array();
$data['fritm'] = ''; // you need to define it as empty string first
for($i = 0;$i<10;$i++) // hard-code started
{
$data['fritm'] .= '<option value="'.$i.'">'.$i.'</option>'; // append each option to the string one-by-one and check `.=` also
}
echo json_encode($data);
Output:-
http://prntscr.com/auyn7i
http://prntscr.com/auymzf
http://prntscr.com/auynij
Note:- problem may be occuring because either you missed jquery library of concatenation inside loop or some other error in your php file.
You need to do two things:
1) concatenate results in while loop. You are re-assigning the array variable causing latest one to overwrite the old one.
This way, only old value will be appended.
Change
$data['fritm'] = '<option value="'.$tqty['product_name'].'">'.$tqty['product_name'].'</option>';
To
$data['fritm'] .= '<option value="'.$tqty['product_name'].'">'.$tqty['product_name'].'</option>';
2) Change
$('#freeitem').html(response.fritm);
To
$('#freeitem').append(response.fritm);
As you are just appending options to drop down, not changing its HTML.

Ajax with PHP same page not working

I have a dependent dropdown menu for category>subcategory without refreshing page with the help of Ajax. But currently my JavaScript code sends the Ajax request to another page and it works fine, i want to send the request to the same page. Currently using the JavaScript as below .. please anyone help me to get the request to the same page.
<script type="text/javascript">
$(document).ready(function(){
$(".category").change(function(){
var id=$(this).val();
var dataString = 'id='+ id;
$.ajax({
type: "POST",
url: "ajax-subcat.php",
data: dataString,
cache: false,
success: function(html){
$(".subcat").html(html);
}
});
});
</script>
If I empty the Ajax url, still doesn't work for one page.
HTML as below
<select name="category" class="category">
<option selected="selected">--Select Category--</option>
<?php
$sql=mysqli_query($mysqlCon, "SELECT * FROM category WHERE catid=1");
while($row=mysqli_fetch_array($sql)){
$cat_id=$row['catid'];
$data=$row['catname'];
echo '<option value="'.$cat_id.'">'.$data.'</option>';
}
?>
</select>
<label>Subcategory:</label>
<select name="subcat" class="subcat">
</select>
ajax-subcat.php contains the below
if(isset($_POST['id'])){
$id=$_POST['id'];
$sql=mysqli_query($mysqlCon, "SELECT * FROM subcategory WHERE sucat='$id'");
while($row=mysqli_fetch_array($sql)){
$id=$row['sucat'];
$data=$row['sucat_name'];
echo '<option value="'.$id.'">'.$data.'</option>';
}
}
I want to achieve this in 1 page, without sending request to other page. Please help.
Please remember to properly indent your code and make the necessary spaces for readability. Also, I advise you to separate your code, and put all the PHP part in classes provided for that purpose.
Try this :
Html file
<select id="category">
<?php
$sql = mysqli_query($mysqlCon, "SELECT * FROM category WHERE catid=1");
while($row=mysqli_fetch_array($sql)) {
$cat_id=$row['catid'];
$data=$row['catname'];
echo '<option value="'.$cat_id.'">'.$data.'</option>';
}
?>
</select>
<label>Subcategory :</label>
<select id="subcat"></select>
<!-- Suppose you call the jquery here -->
<script type="text/javascript">
$(document).ready(function() {
$('#category').change(function () {
var id = $(this).val();
$.ajax({
type: 'POST',
url: 'ajax-subcat.php',
data: json,
cache: false
}).done(function (data) {
$('#subcat').html(data);
}).fail(function (data) {
alert('You have a critic error');
});
});
});
</script>
You should call the php script with json, and have the callback with json_encode. This approach is cleaner. Also I set you the new ajax syntax. THe syntax you used with "success" is now deprecated.
Php file
<?php
if(isset($_POST['id']) && !empty($_POST['id'])) {
$id = $_POST['id'];
$sql = mysqli_query($mysqlCon, "SELECT * FROM subcategory WHERE sucat='$id'");
while($row = mysqli_fetch_array($sql)) {
$id = $row['sucat'];
$data = $row['sucat_name'];
$return[] = '<option value="'.$id.'">'.$data.'</option>';
}
echo json_encode($return);
}
?>
Code not tested, but I think it work

dynamically updating select boxes with php mysql jquery ajax

I am trying to populate an initial customer select box with results from PDO MySql via PHP. Then I would like the second contact select box to update with additional information related to what was chosen in the first box. I can't get the second script to work. I think the problem is in my ajax script because the PHP scripts work fine when ran on there own.
The Primary Script
<html>
<head>
<script type="text/javascript" src="js/jquery-1.11.0.js"></script>
<script type="text/javascript" src="js/jquery-ui-1.10.4.custom.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#contact").change(function(){
var cid = $("#cid").val();
$.ajax({
type:"post",
url:"contact.php",
data:"cid="+cid,
success: function(data) {
$("#contact").html(data);
}
});
});
});
</script>
</head>
<body>
Campaign :
<select name="customer" id="customer">
<option>-Select a Customer-</option>
<?php
include ("function.php");
include("connect.php");
$id = $_SESSION['profile']['id'];
foreach($db->query("SELECT * FROM customers WHERE pid = '$id'") as $row) {
echo "<option value=" . $row['id'] . ">" . $row['name'] . "</option>";
}
?>
</select>
<select name="contact" id="contact">
<option>-Select a Contact-</option>
</select>
</body>
</html>
The Contact script
include("connect.php");
$cid = $_POST["cid"];
foreach($db->query("SELECT * FROM contact WHERE cid = '$cid'") as $row) {
echo '<option value="'.$row['id'].'">'.$row['name'].'</option>';
Maybe your second function should start on #customer change
I see you used the contact select in ajax not customer as you described. However the code you wrote, you used the contact selector with change event, But the contact select box contain only one value, How can it change ??
<select name="contact" id="contact">
<option>-Select a Contact-</option>
</select>
The previous select should has more than option to can change. Or I think you mean the #customer instead contact as following:-
$("#customer").change(function(){
// your code;
});
Why not just encode a JSON response with the ids and names?
foreach($db->query("SELECT * FROM contact WHERE cid = '$cid'") as $row) {
$arr[] = array("id" => $row['id'], "name" => $row['name']);
}
echo json_encode($arr);
Then in your ajax response, you could do
$(document).ready(function () {
$("#customer").change(function () {
var cid = $("#customer").val();
$.ajax({
type: "post",
url: "contact.php",
data: {cid: cid},
success: function (data) {
var options = [];
$.each(data, function () {
options.push('<option value="' + this.id + '">' + this.name + '</option>');
});
$("#contact").html(options.join(""));
}
});
});
});

Categories