PHP, JAVASCRIPT inside php loop - javascript

I currently working with voting system. Everytime a voter selects a candidate the javascript should work but nothing happens. Here is my code.
<?php while ($row = $stmt->fetch()) { ?>
<div class="form-group">
<div class="row">
<label class="control-label col-md-3 col-md-push-1" id="labelpad" for="username"><?php echo $row['position']; ?></label>
<div class="col-md-6 col-md-push-0"><br>
<?php
$stmt1 = $con->prepare("SELECT * FROM candidate WHERE position = ?");
$stmt1->bindParam(1, $row['position']);
$stmt1->execute();
while ($row1 = $stmt1->fetch())
{
?>
<label>
<input id="" class="uniform_on" name="selector[]" type="checkbox" value="<?php echo $row1['candidate_id'];?>">
</label>
<?php echo "<label>".$row1['name']."</label>"; ?><br>
<script>
$(".uniform_on").change(function(){
var max= <?php $row1['vote_limit'];?>
if( $(".uniform_on:checked").length == max {
$(".uniform_on").attr('disabled', 'disabled');
alert('5 Items allowed per borrow');
$(".uniform_on:checked").removeAttr('disabled');
}else{
$(".uniform_on").removeAttr('disabled');
}
})
</script>
<?php } ?>
</div>
</div>

Related

Using jQuery to check a box generated from php

I am attempting to 'check' the the 'AC:Front' box from a button click on the below website. I tried changing the checkbox to 'checked' and I also tried changing the encompassing to class="checked".
The goal is to eventually collect the inputted VIN, run it through a decoder and use the data to fill the page.
Here is the website
HTML
<div class="stm-single-feature">
<div class="heading-font">Comfort</div>
<div class="feature-single">
<label>
<input type="checkbox" value="A/C: Front" name="stm_car_features_labels[]"/>
<span>A/C: Front</span>
</label>
</div>
CSS
div.checker span.checked {
background-position: -16px 0; }
PHP
<?php
if ($items) {
if (!empty($id)) {
$features_car = get_post_meta($id, 'additional_features', true);
$features_car = explode(',', $features_car);
} else {
$features_car = array();
}
foreach ($items as $item) { ?>
<?php if(isset($item['tab_title_single'])): ?>
<div class="stm-single-feature">
<div class="heading-font"><?php echo $item['tab_title_single']; ?></div>
<?php $features = explode(',', $item['tab_title_labels']); ?>
<?php if (!empty($features)): ?>
<?php foreach ($features as $feature): ?>
<?php
$checked = '';
if (in_array($feature, $features_car)) {
$checked = 'checked';
};
?>
<div class="feature-single">
<label>
<input type="checkbox" value="<?php echo esc_attr($feature); ?>"
name="stm_car_features_labels[]" <?php echo $checked; ?>/>
<span><?php echo esc_attr($feature); ?></span>
</label>
</div>
<?php endforeach; ?>
<?php endif; ?>
</div>
<?php endif; ?>
<?php }
}?>
JavaScript
<script type="text/javascript">
jQuery(function($) {
$("#generateVin").on("click", function() {
var $checkbox = $("input[type=checkbox]").eq(1);
$checkbox.prop("checked", true);
$checkbox.parent().addClass("checked");
});
});
</script>

unable to fetch data in multiple dropdown

I am unable to fetch the data in the second dropdown(which is depended upon the first dropdown). e.g. when we select country then the relevant state should be displayed but it doesn't. see my code.
my html
<?php
require 'dbconfig.php';
?>
<label class="control-label">Select Distict</label>
<div class="form-group">
<div class="col-lg-6">
<select class="form-control" name=dist id=dist>
<option value='' selected>Select</option>
<?Php
$ddObj = new USER($DB_con);
$table= "tbl_dist";
$sel = $ddObj->dropdowndist($table);
foreach ($sel as $val) {
echo "<option value=$val[dist_id]>$val[dist_name]</option>";
}
?>
</select>
</div>
</div>
<label class="control-label">Select Block</label>
<div class="form-group">
<div class="col-lg-6">
<select class="form-control" name=block id=block>
</select>
</div>
</div>
my jquery
<script>
$(document).ready(function() {
$('#dist').change(function(){
var dist_id=$('#dist').val();
$('#block').empty(); //remove all existing options
$.get('ddblock.php',{'dist_id':dist_id},function(return_data){
$.each(return_data.data, function(key,value){
$("#block").append("<option value='" + value.block_id +"'>"+value.block_name+"</option>");
});
}, "json");
});
});
</script>
ddblock.php
<?Php
$dist_id=$_GET['dist_id'];
if(!intval($dist_id)){
echo "Data Error";
exit;
}
require 'class.user.php';
$ddObj = new USER($DB_con);
$table = "tbl_block";
$result = $ddObj->fetch_block($table,$dist_id);
$main = array('data'=>$result);
echo json_encode($main);
}
?>
class.user.php
public function fetch_block($table,$dist_id){
try
{
$sel = $this->db->prepare("SELECT * FROM $table WHERE block_dist_id=:dist_id");
$sel->bindValue(':dist_id', $dist_id);
$sel->execute();
$rs = $sel->setFetchMode( PDO::FETCH_ASSOC );
return $sel;
}
catch(PDOException $e)
{
echo $e->getMessage();
}
}

How to disable and enable div dynamically

I'm developing a shopping site in which I'm validating the address using zipcode during the checkout. I want to disable each div which is not deliverable.
Below, is the code
<?php
if (isset($all[0])) {
for($i = 0; $i <= count($all) ; $i++) {
if (isset($all[$i])) {
?>
<div class="col-sm-5 col-md-3 col-xs-12">
<div id="addrs" class="col-sm-12 col-md-12 col-xs-12 addr-box" data-addr="<?php echo $all[$i]['id']; ?>">
<strong><?php echo $all[$i]['name']; ?></strong>
<?php echo $all[$i]['zip'] ?>
<?php
if ($all[$i]['zip'] && (in_array($all[$i]['zip'], $area['area']))) {
$availability = '<p>True</p>';
} else {
$availability = '<p>False</p>';
}
?>
</div>
<?php echo $availability ?>
</div>
<?php
}
}
}
?>
<?php
if (isset($all[0])) {
for($i = 0; $i <= count($all) ; $i++) {
if (isset($all[$i])) {
$availability = ($all[$i]['zip'] && (in_array($all[$i]['zip'], $area['area'])));
?>
<div class="col-sm-5 col-md-3 col-xs-12" <?php if(!$availability){ echo "style='pointer-events:none;'"; } ?> >
<div id="addrs" class="col-sm-12 col-md-12 col-xs-12 addr-box" data-addr="<?php echo $all[$i]['id']; ?>">
<strong><?php echo $all[$i]['name']; ?></strong>
<?php echo $all[$i]['zip']; ?>
</div>
<?php echo "<p>".($availability ? "True" : "False")."</p>"; ?>
</div>
<?php
}
}
}
?>
I'm not entirely sure if this is what you're looking for, but this adds style='pointer-events:none;' to divs which aren't available, which should prevent them from being clickable.

How do I filter for similar products using checkboxes with PHP, AJAX and JS?

Here is an image of what I'm trying to accomplish -
Example of my Database Table -
My goal is to get a similar product to the product that is currently displaying without refreshing the page. I am trying to find similar products is by using check boxes.
I first got the id using $_GET['id'] which should be equal to one of the values in my table.
I then used PDO Fetch to get the product name, brand, quanity and price of that particular id and store it as a string.
What I need help with is using JQuery/AJAX to get the checkboxes that are checked and then send the information to a PHP file that would check if filter results match with any data from the table.
How can I do this?
This is my product.php file
<?php
require ('includes/db.php');
$id = $_GET['id']; //Getting the ID in URL. ex products.php?id=12
$stmt = $handler->prepare("SELECT * FROM products WHERE id = '$id' ");
$result = $stmt->execute(array());
$products = $stmt->fetch(PDO::FETCH_ASSOC);
$prod_name = $products['prod_name']; //Product Name
$brand = $products['brand']; //Product Brand
$quantity = $products['quantity']; //Product Quantity
$calories = $products['calories']; //Product Calories
$price = $products['price']; //Product Price
?>
<!DOCTYPE html>
<html>
<head>
<title><?php echo "$brand $prod_name"; ?></title>
</head>
<body>
<h1><?php echo $prod_name; ?></h1>
<br />
<p>Brand = <?php echo " $brand"; ?></p>
<p>Quantity = <?php echo " $quantity"; ?></p>
<p>Calories = <?php echo " $calories"; ?></p>
<p>Price = <?php echo " $price"; ?></p>
<br />
<p style="text-align: center;">Find Similar Products</p>
<form>
<div class="checkboxes">
<label>
<input name="brand" type="checkbox" value="<?php echo $brand; ?>">
<span>Brand</span> <!--Brand Checkbox-->
</label>
</div>
<div class="checkboxes">
<label>
<input name="quanitity" type="checkbox" value="<?php echo $quantity; ?>">
<span>Quantity</span> <!--Quantity Checkbox-->
</label>
</div>
<div class="checkboxes">
<label>
<input name="calories" type="checkbox" value="<?php echo $calories; ?>">
<span>Calories</span> <!--Calories Checkbox-->
</label>
</div>
<div class="checkboxes">
<label>
<input name="price" type="checkbox" value="<?php echo $price; ?>">
<span>Price</span> <!--Price Checkbox-->
</label>
</div>
</form>
</body>
</html>
I managed to solve this out, glad I didn't give up.
My product.php File
<?php
require ('/db.php');
$id = $_GET['id']; //Getting the ID in URL. ex products.php?id=12
$stmt = $handler->prepare("SELECT * FROM products WHERE id = '$id' ");
$result = $stmt->execute(array());
$products = $stmt->fetch(PDO::FETCH_ASSOC);
$prod_name = $products['prod_name']; //Product Name
$brand = $products['brand']; //Product Brand
$quantity = $products['quantity']; //Product Quantity
$calories = $products['calories']; //Product Calories
$price = $products['price']; //Product Price
?>
<!DOCTYPE html>
<html>
<head>
<title><?php echo "$brand $prod_name"; ?></title>
</head>
<body>
<h1><?php echo $prod_name; ?></h1>
<br />
<p>Brand = <?php echo " $brand"; ?></p>
<p>Quantity = <?php echo " $quantity"; ?></p>
<p>Calories = <?php echo " $calories"; ?></p>
<p>Price = <?php echo " $price"; ?></p>
<br />
<p style="text-align: center;">Find Similar Products</p>
<form method="post" action="">
<div class="checkboxes">
<label>
<input name="brand" type="checkbox" value="<?php echo $brand; ?>">
<span>Brand</span> <!--Brand Checkbox-->
</label>
</div>
<div class="checkboxes">
<label>
<input name="quanitity" type="checkbox" value="<?php echo $quantity; ?>">
<span>Quantity</span> <!--Quantity Checkbox-->
</label>
</div>
<div class="checkboxes">
<label>
<input name="calories" type="checkbox" value="<?php echo $calories; ?>">
<span>Calories</span> <!--Calories Checkbox-->
</label>
</div>
<div class="checkboxes">
<label>
<input name="price" type="checkbox" value="<?php echo $price; ?>">
<span>Price</span> <!--Price Checkbox-->
</label>
</div>
</form>
<div class="filter_container">
<div style="clear:both;"></div>
</div>
<script type="text/javascript" src="/js/filter.js"></script>
<input name="prod_name" value="<?php echo $prod_name ?>" style="display:none;"/>
<!--Hidden product name-->
</body>
</html>
Here is my JS File
$(document).ready(function() {
function showValues() {
var brand;
var quantity;
var calories;
var price;
//Gets product name
var prod_name = $('input[name="prod_name"]').val();
//Gets brand
if($('input[name="brand"]').is(':checked'))
{brand = $('input[name="brand"]').val();} else {brand = ""}
//Gets quantity
if($('input[name="quantity"]').is(':checked'))
{quantity = $('input[name="quantity"]').val();} else {quantity = ""}
//Gets calories
if($('input[name="calories"]').is(':checked'))
{calories = $('input[name="calories"]').val();} else {calories = ""}
//Gets price
if($('input[name="price"]').is(':checked'))
{price = $('input[name="price"]').val();} else {price = ""}
$.ajax({
type: "POST",
url: "/query.php",
data: {'brand':brand, 'quantity':quantity, 'calories':calories, 'prod_name':prod_name},
cache: false,
success: function(data){
$('.filter_container').html(data)
}
});
}
//Call function when checkbox is clicked
$("input[type='checkbox']").on( "click", showValues );
//Remove checked when checkbox is checked
$(".checkboxes").click(function(){
$(this).removeAttr('checked');
showValues();
});
});
Here is my PHP File
<?php
include('/db.php');
$prod_name = $_POST['prod_name'];
$Cbrand = $_POST['brand'];
$Cquantity = $_POST['quantity'];
$Ccalories = $_POST['calories'];
$Cprice = $_POST['price'];
if(!empty($Cbrand))
{
$data1 = "brand = '$Cbrand' AND";
}else{
$data1 = "";
}
if(!empty($Cquantity))
{
$data2 = "quantity = '$Cquantity' AND";
}else{
$data2 = "";
}
if(!empty($Ccalories))
{
$data3 = "calories = '$Ccalories' AND";
}else{
$data3 = "";
}
if(!empty($Cprice))
{
$data4 = "price = '$Cprice'";
}else{
$data4 = "";
}
$main_string = "WHERE $data1 $data2 $data3 $data4"; //All details
$stringAnd = "AND"; //And
$main_string = trim($main_string); //Remove whitespaces from the beginning and end of the main string
$endAnd = substr($main_string, -3); //Gets the AND at the end
if($stringAnd == $endAnd)
{
$main_string = substr($main_string, 0, -3);
}else if($main_string == "WHERE"){
$main_string = "";
}
else{
$main_string = "WHERE $data1 $data2 $data3 $data4";
}
if($main_string == ""){ //Doesn't show all the products
}else{
$sql = "SELECT COUNT(*) FROM products $main_string";
if ($res = $handler->query($sql)) {
/* Check the number of rows that match the SELECT statement */
if ($res->fetchColumn() > 0) {
$sql = "SELECT * FROM products $main_string";
foreach ($handler->query($sql) as $pro) {
if(($pro['prod_name'] == $prod_name) && ($res->fetchColumn() < 2))
{
//The product currently being displayed is blank when using the filter
}
else{
?>
<!------------------------------------------------------------------------------------------------------------------------------------------------->
<div class="form-result">
<td><?=strtoupper($pro['brand']) + " " + strtoupper($pro['prod_name']); ?></td>
</div>
<!------------------------------------------------------------------------------------------------------------------------------------------------->
<?php
}
}
} /* No rows matched -- do something else */
else {
?>
<div align="center"><h2 style="font-family:'Arial Black', Gadget, sans-serif;font-size:30px;color:#0099FF;">No Results with this filter</h2></div>
<?php
}
}
}
$handler = null;
$res = null;
?>

How to do validation inside foreach

I have a form which has some text fields. Text fields may increase or decrease according to database table. If there are 3 warehouses in database it will show 3 text boxes with available quantity as place holder. Now user have to enter quantity no more than given in placeholder in each box. How can I do validation if user enter a value more than available (which will be shown as place holder) ?. Problem is validation should be according to foreach loop. My code is below,
<?php
if (!empty($ware_details)) {
foreach ($ware_details as $data) {
?>
<div class="form-group">
<label for="exampleInputEmail1"><?php echo $data->warehouse_name; ?></label>
<input type="number" id="return_pro" class="form-control" base_url="<?php echo site_url(); ?>" name="<?php echo $data->wh_warehouse_id;?>" placeholder="<?php echo $data->wh_product_qty; ?> Available">
<div class="dataDrop"></div>
<input type="hidden" id="quantity" value="<?php echo $data->wh_product_qty; ?>"/>
</div>
<?php } }?>
Here as you see text boxes number is depending upon foreach loop. So how can I validate? Javascript or Ajax is ok.
I tried something like this,
<?php foreach ($ware_details as $data) {?>
<script>
function check()
{
var stock = document.getElementById('quantity').value;
var return_stock = document.getElementById('return_pro').value;
if (parseFloat(stock) < parseFloat(return_stock))
{
alert("Return product can't be more than total stock");
document.getElementById('return_pro').focus();
return false;
}
//alert(return_stock);
return false;
}
But I know it is fully wrong. Any idea?
Try to use html5 required attribute. This set of code may help you.
<input type="number"
min="1"
max="<?php echo $data->wh_product_qty; ?>"
name="<?php echo $data->wh_warehouse_id;?>"
required="required"
placeholder="<?php echo $data->wh_product_qty; ?> Available" />
You cannot use an id multiple times in the document, it needs to be unique. Either use classes to identify/group elements, or enumerate the ids:
<?php
$i = 0;
if (!empty($ware_details)) {
foreach ($ware_details as $data) {
?>
<div class="form-group">
<label for="exampleInputEmail1"><?php echo $data->warehouse_name; ?></label>
<input type="number" id="return_pro<?php echo $i; ?>" class="form-control" base_url="<?php echo site_url(); ?>" name="<?php echo $data->wh_warehouse_id;?>" placeholder="<?php echo $data->wh_product_qty; ?> Available">
<div class="dataDrop"></div>
<input type="hidden" id="quantity<?php echo $i; ?>" value="<?php echo $data->wh_product_qty; ?>"/>
</div>
<?php
$i++;
} }?>
<script>
function check(i) {
var stock = document.getElementById('quantity'+i).value;
var return_stock = document.getElementById('return_pro'+i).value;
if (parseFloat(stock) < parseFloat(return_stock))
{
alert("Return product can't be more than total stock");
document.getElementById('return_pro'+i).focus();
return false;
}
//alert(return_stock);
return false;
}
// then in the validation trigger:
for (var i=0; i< <?php echo $i; ?>; i++)
check(i);

Categories

Resources