Chosen Plugin Not Updated Select Box based on Ajax Result - javascript

I am working on two select box. One Select Box contain "Product Categories" and Second Select Box Contain Products. As Showing in the following image.
I can search both box either using product or using category. In the start if search using only products it shows all the products, that is fine. But problem is with category.
When i select any category then it should cleared all the products and show only category related products. but it is not updating the result.
Here is my Js
$("#pcategories").chosen().change(function(){
var val = $(this).val();
var info = 'id=' + val;
$.ajax({
type: "GET",
url: "getproduct.php",
data: info,
success: function(response){
var len = response.length;
$("#selectedproducts").empty();
for( var i = 0; i<len; i++){
var product_id = response[i]['product_id'];
var product_name = response[i]['product_name'];
$("#selectedproducts").append("<option value='"+product_id+"'>"+product_name+"</option>");
}
}
});
});
Here is my HTML
<select name="productcategories" style="width:600px; "class="chzn-select" id="pcategories" required>
<option>Select Category</option>
<?php
$result = $db->prepare("SELECT * FROM categories");
$result->bindParam(':userid', $res);
$result->execute();
for($i=0; $row = $result->fetch(); $i++){
?>
<option value="<?php echo $row['category_name'];?>"><?php echo $row['category_name']; ?></option>
<?php
}
?>
Here is HTML for Products
<select name="product" style="width:600px; "class="chzn-select" id="selectedproducts" required>
<option></option>
<?php
$result = $db->prepare("SELECT * FROM products");
$result->bindParam(':userid', $res);
$result->execute();
for($i=0; $row = $result->fetch(); $i++){
?>
<option value="<?php echo $row['product_id'];?>"><?php echo $row['product_code']; ?> - <?php echo $row['product_name']; ?> | Price: <?php echo $row['price']; ?></option>
<?php
}
?>
Where is the error? How can i update the products based on the category ?

Related

Multiple ajax returns and sum values

I have a group of dropdowns with a list of players. When a player is selected, their 'Value' should appear next to the drop down and the Total should update to be the sum of all selected players values.
php code below is for two players but I have ten, will likely have ten different similar functions for each of the dropdowns
select-player.php
<!--player1-->
<tr>
<td style="width:50%;">
<select name="player1" id="player1" onchange="showvalue1()">
<option disabled selected value></option>
<?php
$sql = "SELECT * FROM players ORDER BY value DESC";
$result = mysqli_query($conn, $sql);
$resultCheck = mysqli_num_rows($result);
if ($resultCheck > 0) {
while ($row = mysqli_fetch_assoc($result)) {
echo "<option value='". $row['playername'] ."'>" .$row['playername'] ."</option>";
}
}
?>
</select>
</td>
<td style="width:50%;" id="value1">
</td>
</tr>
<!--player2-->
<tr>
<td style="width:50%;">
<select name="player2" id="player2" onchange="showvalue2()">
<option disabled selected value></option>
<?php
$sql = "SELECT * FROM players ORDER BY value DESC";
$result = mysqli_query($conn, $sql);
$resultCheck = mysqli_num_rows($result);
if ($resultCheck > 0) {
while ($row = mysqli_fetch_assoc($result)) {
echo "<option value='". $row['playername'] ."'>" .$row['playername'] ."</option>";
}
}
?>
</select>
</td>
<td style="width:50%;" id="value2">
</td>
</tr>
<tr>
<th style="width:50%";>Total</th>
<th style="width:50%;" id="total"></th>
</tr>
ajax.js
function showvalue1(){
var x = document.getElementById("player1").value;
var t = document.getElementById("total").value;
$.ajax({
url:"../showvalue.php",
method: "GET",
datatype: 'json',
data:{
id : x,
total : t
},
success:function(data){
$("#value1").html(data.price);
$("#total").html(data.newtotal);
}
})
}
function showvalue2(){
var x = document.getElementById("player2").value;
var t = document.getElementById("total").value;
$.ajax({
url:"../showvalue.php",
method: "GET",
datatype: 'json',
data:{
id : x,
total : t
},
success:function(data){
$("#value2").html(data.price);
$("#total").html(data.newtotal);
}
})
}
I've read that jsonencode is used to send arrays back that I can then assign to IDs in js.
showvalue.php
<?php
include_once 'includes/dbh.inc.php';
$pl = $_POST['id'];
$pl = trim($pl);
$total = 0;
$total = $_POST['total'];
$sql = "SELECT value FROM players WHERE playername='{$pl}'";
$result = mysqli_query($conn, $sql);
while($rows = mysqli_fetch_array($result)){
$newtotal = 0;
$value = $rows['value'];
$newtotal = $total + $value;
$ret = array('price'=>$value, 'newtotal'=>$newtotal);
echo json_encode($ret);
}
?>
Not getting any errors or console returns but also no values are being returned.
What am I missing?
Checking your HTML source, #total is a table cell:
<th id="total"></th>
And you are retrieving it using .value:
var t = document.getElementById("total").value;
But .value is for inputs, not text in a table cell, so that won't work.
To get the text, using jQuery instead of vanilla JS (since the rest of your code is jQuery):
var t = $('#total').text();

How to populate one drop-down based on the selection of another drop-down from database in php and javascript/jquery

I want to populate the drop-down based on the selection of other. Here's how the database looks like. Tried the following code but it isn't giving me any results.
make
id maker
2 Apple
3 Samsung
model
id make_id model
1 3 Galaxy S III
2 3 Galaxy S IV
3 2 iphone 5s
4 2 iphone 5
Queries.php
class Queries{
public static function getMaker() {
$conn = DB::databaseConnection();
$sql = "SELECT * from make" ;
$stmt = $conn->prepare($sql);
if ($stmt->execute()) {
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
return $result;
} else {
return null;
}
}
public static function getModel($make_id) {
$conn = DB::databaseConnection();
$sql = "SELECT * from model WHERE make_id = :make_id" ;
$stmt = $conn->prepare($sql);
$stmt->bindParam(':make_id', $make_id);
if ($stmt->execute()) {
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
return $result;
} else {
return null;
}
}
}
mobilereg.php
$make_id = filter_input(INPUT_GET, "make_id");
require_once './pages/header.php';
require_once './functions/queries.php';
$maker = Queries::getMaker();
$model = Queries::getModel($make_id);
<div class="control-group form-group">
<div class="controls">
<label>Make</label>
<select class="form-control"name="maker"id="maker"onchange="get_models();">
<option selected disabled></option>
<?php
for ($i = 0; $i < count($maker); $i++) {
echo '<option value="' . $maker[$i]['id'] . '">' . $maker[$i]['maker'] . '</option>';
}
?>
</select>
</div>
</div>
<div class="control-group form-group">
<div class="controls">
<label>Model</label>
<select class="form-control" name="get_models" id="get_models">
<option selected disabled></option>
</select>
</div>
</div>
main.js
function get_models(){
var maker = $('#maker').val();
var dataString = "maker="+maker;
$.ajax({
type: "POST",
url: "functions.php",
data: dataString,
success: function(html)
{
$("#get_models").html(html);
}
});
}
functions.php
require_once './queries.php';
$make_id = filter_input(INPUT_POST, "make_id");
if($_POST){
$maker = $_POST['maker'];
if($maker!=''){
echo Queries::getModel($make_id);
echo "<select name='get_models'>";
echo "<option value='" . $row['make_id'] . "'>" . $row['model'] . "
</option>";
echo '</select>';
}
}
So maker and model are the two drop-downs. The options in the model should result on the basis of the selection we make in the maker drop-down.
I've referred the code from one the questions here but it doesn't work at all. The problem is in the functions.php I guess. I'm very new to php and js, any help would be appreciated. TIA

How to get multiple data from select item in jquery

I am trying to get multiple value from multiple select textbox and use the same value in PHP for adding the SUM.
My code is:
function get_amount() {
var x = $('#work').val();;
alert(x);
$.ajax({
type: "POST",
url: "get-sum.php",
data: 'id=' + x,
success: function(data) {
alert(data);
//$('#html').load(document.URL + ' #html');
}
});
}
<select class="select2 select2-multiple" multiple="multiple" data-placeholder="Choose" name="work[]" id="work" onchange="get_amount()">
<option value="1" >option 1</option>
<option value="2"> OPtion 2 </option>
<option value="3"> OPtion 3</option>
</select>
And My php file as :
$id = $_POST['id'];
function getAmount($id){
global $mysqli;
$stmt = $mysqli->prepare("SELECT
(amount)
FROM work
WHERE id = ?
");
$stmt->bind_param("s",$id);
$stmt->execute();
$stmt->bind_result($amount);
$stmt->store_result();
$stmt->fetch();
$stmt->close();
return $amount;
}
$sql = getAmount($id);
echo $sql;
Error which i am getting is the data which i am getting from multiple select is like 5,6,7 and its always hitting the php file at id 5. And the second problem how i will be able to add all $sql data.
I have done some changes in my PHP code :
$id = $_POST['id'];
$sum = 0;
for($i = 0; $i<count($id); $i++) {
$sum = $sum + getAmount($id[$i]);
}
echo $sum;
function getAmount(&$id){
global $mysqli;
$stmt = $mysqli->prepare("SELECT SUM(amount) AS total FROM work WHERE id = (?)");
$stmt->bind_param("s",$id);
$stmt->execute();
$stmt->bind_result($amount);
$stmt->fetch();
return $amount['total'];
}

PHP populated dropdown, onchange populate different dropdown based on value

Hi so the here is my question,
I have a Database containing Categories and Subcategories.
I have two dropdown boxes (select). I want them both to be populated by using PHP/MYSQL.
My Categories have been generated:
<select name="prod_cat">
<?php
include("php/dbconnect.php");
$sql = "SELECT * FROM categories";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0){
while ($row = mysqli_fetch_array($result))
{
echo '<option value="'. $row["cat_name"] .'">'. $row["cat_name"] .'</option>';
}
}
else{echo "No categories were found!";}
mysqli_close($conn);
?>
</select>
I want the subcategories to load when the category has changed.
My SQL will look something like this:
SELECT subcat_name FROM subcategories WHERE cat_name = '$prod_cat'
I need to get the value from the categories dropdown and store it as a variable.
In the past I have done something similar in javascript:
var subcat=document.forms["form"]['subcat'].value;
and then changed the value of another dropdown by calling an onChange(); function like:
document.getElementById('subcat').innerHTML='<option value=""></option>';
I hope someone can point me in the right direction! Should I be looking into AJAX, JavaScript or can it all be done with PHP?
Thank you.
add an id on category select box , like this -
<select name="prod_cat" id="prod_cat">
<?php
include("php/dbconnect.php");
$sql = "SELECT * FROM categories";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0){
while ($row = mysqli_fetch_array($result))
{
echo '<option value="'. $row["cat_name"] .'">'. $row["cat_name"] .'</option>';
}
}
else{echo "No categories were found!";}
mysqli_close($conn);
?>
</select>
for subcategory -
<select id='sub_cat' name='sub_cat'></select>
write your script something like this -
<script>
$("#prod_cat").change(function(){
//get category value
var cat_val = $("#prod_cat").val();
// put your ajax url here to fetch subcategory
var url = 'www.example/fetch_subcategory.php';
// call subcategory ajax here
$.ajax({
type:"POST",
url:url,
data:{
cat_val : cat_val
},
success:function(data)
{
$("#sub_cat").html(data);
}
});
});
</script>
add code in ajax calling page -'www.example/fetch_subcategory.php'
<?php
$prod_cat = $_POST['cat_val'];
$sql = "SELECT subcat_name FROM subcategories WHERE cat_name = '$prod_cat'";
$result = mysqli_query($conn, $sql);
$msg ='';
if (mysqli_num_rows($result) > 0){
while ($row = mysqli_fetch_array($result))
{
$msg =.'<option value="'. $row["sub_cat_name"] .'">'. $row["sub_cat_name"] .'</option>';
}
}
else{$msg .="No categories were found!";}
echo $msg;
mysqli_close($conn);
?>
Do something like this, and hope it will work for you.

Sending two values to PHP via ajax POST to query SQL db

I'm trying to send two values from a form to another PHP using ajax post method. One value is the value that's already entered in an input box, and the other is a value that is being typed into another input box. It acts like a search box. I tried executing the SQL query in my SQL workbench and it returns the value properly. What am I doing wrong in my code?
function searchq6(){
var searchstate = $("input[name='region']").val();
var searchTxt = $("input[name='suburb']").val();
$.post("search-suburb.php", {searchVal: searchTxt, st:searchstate},function(sbb){
$("#sbb").html(sbb);
//searchq7();
});
}
This is the input box where I search and get the value from:
<input type="text" name="region" list="state" value="<?php echo $region; ?>" placeholder="Select State" id="output">
Suburb:
<input type="text" name="suburb" list="sbb" value="<?php echo $suburb; ?>" onkeyup="searchq6()" id="output">
<datalist id="sbb" name="taskoption6" >
<option> </option>
</datalist>
This is the search-suburb.php file:
$output = '' ;
if (isset($_POST['searchVal'])){
$searchq = $_POST['searchVal'];
$st = $_POST['st'];
$query = mysqli_query($link, "SELECT DISTINCT title FROM `wp_locations` WHERE state="'.$st.'" AND `title` LIKE '%".$searchq."%' ")or die("Could not search!");
$count = mysqli_num_rows($query);
if($count == 0){
$output = '<option>No results!</option>';
}else{
while($row = mysqli_fetch_array($query)){
$suburb = $row['title'];
?>
<option value="<?php echo $suburb; ?>"><?php echo $suburb; ?> </option>
<?php
} // while
} // else
} // main if
<input type="text" name="region" list="state" value="<?=(isset($_POST['region'])?$_POST['region']:'');?>" placeholder="Select State" id="output">
Suburb:
<input type="text" name="suburb" onkeyup="searchq6()" list="sbb" value="<?=(isset($_POST['suburb'])?$_POST['suburb']:'');?>" onkeyup="searchq6()" id="output">
<datalist id="sbb" name="taskoption6"></datalist>
Javascript:
function searchq6(){
var searchstate = $("input[name='region']").val();
var searchTxt = $("input[name='suburb']").val();
$.post("search-suburb.php", {searchVal: searchTxt, st:searchstate},function(sbb){
var decode = jQuery.parseJSON(sbb); // parse the json returned array
var str = ""; // initialize a stringbuilder
$.each(decode, function (x, y) {
str+="<option value='" + y.title +"'>";
});
$("#sbb").html(str);
}); // end of post
}// end of searchq6 function
Php:
$output = '' ;
if (isset($_POST['searchVal'])){
$searchq = $_POST['searchVal'];
$st = $_POST['st'];
$query = mysqli_query($link, "SELECT DISTINCT title FROM `wp_locations` WHERE state='{$st}' AND `title` LIKE '%{$searchq}%' ")or die("Could not search!");
$count = mysqli_num_rows($query);
if($count == 0){
$output = '<option>No results!</option>';
} else{
$data = array();
while($row = mysqli_fetch_array($query))
$data[] = $row;
echo json_encode($data);
}
} // main if
Got the answer from small snippets gathered through the comments
Changed the query to:
$query = mysqli_query($link, "SELECT DISTINCT title FROM `wp_locations` WHERE state='".$st."' AND `title` LIKE '%".$searchq."%' LIMIT 10")or die("Could not search!");
And the ajax to:
function searchq6(){
var searchstate = $("input[name='region']").val();
var searchTxt = $("input[name='suburb']").val();
$.post("search-suburb.php", {searchVal: searchTxt, st:searchstate})
.done(function(sbb) {
$("#sbb").html(sbb);
});
//searchq7();
}
Thanks for all the comments guys

Categories