Get values of all selected checkboxes and add them to Query String - javascript

I will try to be as brief and objective as possible. I'm developing a shopping cart system and for some products categories I need to create checkboxes that corresponds to the additional products that can be added for a single product and the amount of it. I have one script to display the products by category, and if category id match with the specified number id, the additional products are recovered from the database table additionals and displayed in checkboxes with their price in the row of the product that belong to that category. In my page products.php I have the following code to display my products from database:
$sql = "SELECT p.product_id, p.product_name, p.product_price,
p.category_id, c.category_name FROM products p, categories c WHERE c.category_id = p.category_id ORDER BY p.category_id, p.product_name";
$stmt = $connection->prepare($sql);
$stmt->execute();
$sql2 = "SELECT additional_id, additional_name, additional_price FROM additionals ORDER BY additional_name";
$stmt2 = $connection->prepare($sql2);
$stmt2->execute();
$num = $stmt->rowCount();
$category = null;
if($num>0)
{
while ($row = $stmt->fetch(PDO::FETCH_ASSOC))
{
extract($row);
if($category != $category_id)
{
if(!is_null($category)) { echo "</table>"; }
echo "<h1>{$category_name}</h1>
<table>
<tr>
<th>NAME</th>
<th>PRICE</th>
<th>QUANTITY</th>";
if($category_id == 1) echo" <th>ADDITIONALS</th>";
echo "</tr>";
$category = $category_id;
}
echo "
<tr>
<td>
<div class='product-id' style='display: none'>{$product_id}</div>
<div class='product-name'>{$product_name}</div></td>
<td>${$product_price}
</td>
<td>
<input type='number' name='quantity' value='1' min='1' max='20'/>
</td>";
if($category_id == 1)
{
echo "<td>";
while ($row = $stmt2->fetch(PDO::FETCH_ASSOC))
{
extract($row);
echo "
<input type='checkbox' name='acr[]' value='{$additional_id}'/>{$additional_name} - ${$additional_price} <input type='number' name='quantity_acr[]' value='1' min='1' max='5'/><br/>
";
}
echo "</td>";
}
echo "<td>
<form class='add'>
<button type='submit'>Add</button>
</form>
</td>
</tr>";
}
echo "</table>";
}
With this code, my output is something like this:
http://i.imgur.com/1mEPljR.png
The category id 1 corresponds to the Food category so, the additionals column will be displayed.
I use this jQuery code to get the values and add them to a Query String:
$(document).ready(function()
{
$('.add').on('submit', function()
{
var product_id = $(this).closest('tr').find('.product-id').text();
var product_name = $(this).closest('tr').find('.product-name').text();
var quantity = $(this).closest('tr').find('input').val();
window.location.href = "add_to_cart.php?product_id=" + product_id + "&product_name=" + product_name + "&quantity=" + quantity;
return false;
});
});
And here is my problem. I have no idea of how to store the additional selected checkboxes products and their respective quantities in the Query String too! In add_to_cart.php I have the following code to get the variables from Query String, compare them in database and add the product to the SESSION:
if (isset($_GET['product_id']) && $_GET['product_id'] != "")
{
if(isset($_SESSION['cart']))
{
$count = count($_SESSION['cart']);
$product_id_session = $count++;
}
else
{
$product_id_session = 0;
}
$product_id = isset($_GET['product_id']) ? $_GET['product_id'] : "";
$product_name = isset($_GET['product_name']) ? $_GET['product_name'] : "";
$quantity = isset($_GET['quantity']) ? $_GET['quantity'] : "";
$sql = "SELECT * FROM products WHERE product_id LIKE '{$product_id}' AND product_name LIKE '{$product_name}' LIMIT 1";
$stmt = $connection->prepare($sql);
$stmt->execute();
$num = $stmt->rowCount();
if($num == 1)
{
if($quantity <= 0 || $quantity > 20)
{
header('Location: products.php?action=invalidquantity&product_name=' . $product_name);
}
else if(!isset($_SESSION['cart']))
{
$_SESSION['cart'] = array();
}
if(isset($_SESSION['cart']))
{
while ($row = $stmt->fetch(PDO::FETCH_ASSOC))
{
extract($row);
$columns = array
(
'product_id_session' => $product_id_session,
'product_id' => $product_id,
'product_name' => $product_name,
'product_price' => $product_price,
'quantity' => $quantity
);
}
$_SESSION['cart'][$product_id_session] = $columns;
header('Location: products.php?action=added&product_name=' . $product_name);
}
}
else
{
redirect_to("products.php");
}
}
I need to do the same with the selected checkboxes! Compare them in database with additional_id and insert the name and price of them in the SESSION in the respective product array, but I do not know how to do this. I hope you understood what I want to do. I'm trying this all day but my current knowledge does not allow me to pass beyond this point. I humbly ask someone to help me.

The name of the input field is acr[]. This means you will have a numerical array inside $_GET['acr'] assuming the submit method is GET.
So you'll have $_GET['acr'][0], $_GET['acr'][1], etc.
You can always use var_dump($_GET) to see all the input values.
It might make more sense for you to use a unique identifier inside the brackets for each product type.
For example use name acr[garlic] or acr[01234] signifying a product ID.

try this : http://jsfiddle.net/zkky5c0f/
$(document).ready(function(){
var allCheckbox = '';
$('input[type=\"checkbox\"]').each(function(){
if(allCheckbox !== ''){
allCheckbox += '-' + $(this).val();
}else{
allCheckbox += $(this).val();
}
});
alert(allCheckbox);
});
In your code it would be like:
$(document).ready(function()
{
$('.add').on('submit', function()
{
var product_id = $(this).closest('tr').find('.product-id').text();
var product_name = $(this).closest('tr').find('.product-name').text();
var quantity = $(this).closest('tr').find('input').val();
var allCheckbox = '';
$('input[type=\"checkbox\"]').each(function(){
if(allCheckbox !== ''){
allCheckbox += '-' + $(this).val();
}else{
allCheckbox += $(this).val();
}
});
window.location.href = "add_to_cart.php?product_id=" + product_id + "&product_name=" + product_name + "&quantity=" + quantity + "&checkbox=" + allCheckbox;
return false;
});
});
Then in PHP you can simply explode the string over -
example :
$checkbox = explode($_GET['checkbox']);
hope this helps :)

Related

Displaying checkbox dynamically in PHP/JavaScript

A benefit can be assigned to an employee but firstly the code below shows the dynamic dropdown of employee and dynamic benefit checkboxes
<?php
$ctr = 0;
$employee = mysqli_query($conn, "SELECT * FROM housekeeping_employee") or DIE("Could not Select");
echo "<select class='indent' name = 'Employee'>";
while($listEmployee = mysqli_fetch_array($employee))
{
echo "<option value = ".$listEmployee['employeeid'].">".$listEmployee['firstname']."</option>";
}
echo "</select>";
echo "<br><be>";
echo "<div class='indent'>";
$benefits = mysqli_query($conn, "SELECT * FROM housekeeping_benefit")or DIE("SELECT Query not working.");
if(mysqli_num_rows($benefits))
{
while($row = mysqli_fetch_array($benefits))
{
$ctr++;
echo "<h6><input type = 'checkbox' name = 'benefits".$ctr."' value ='".$row['benefitid']."' >".$row['benefitname']." </input></h6> <be>";
if($ctr == 5){
echo"<br>";
$ctr=0;
}
}
echo "<br><input type='submit' class='btn btn-info' name='insert' value='Submit'/>";
}
echo "<input type='hidden' name='ctr' value='".$ctr."'/>";
echo "</form>";
?>
This is what the insert code of assigning benefits to employee looks like.
$employeeid = $_POST['Employee'];
for($a = 1; $a <= $_POST['ctr'] ; $a++)
{
if(isset($_POST['benefits'.$a]))
{
$benefitid = $_POST['benefits'.$a];
//echo "INSERT INTO `housekeeping_employeebenefits`(`employeeid`,`benefitid`) VALUES('$employeeid','$benefitid')";
mysqli_query($conn, "INSERT INTO `housekeeping_employeebenefits`(`employeeid`,`benefitid`) VALUES('$employeeid','$benefitid')") or DIE("Insert query is not working");
echo "Employee to Benefits successful!";
}
}
My main problem is how will I display checked checkboxes if the employee already has that benefit? I'm really lost

Drag and Drop using jQuery Save the new order

i'm using drag and drop to order a list with jquery ....
and i want to save the new order to Database by clicking a button for exemple
this is my methode to get list element
public function test() {
$choice = Database::getInstance()->query("SELECT * FROM choix WHERE condidat_concour_id = ".$this->data()->ID." ORDER BY ordre ASC");
foreach($choice->results() as $choi){
$cs_code = $choi->cs_code;
$cs = Database::getInstance()->query("SELECT code,designation,site
FROM cs
WHERE code = '{$cs_code}' ");
echo "<li id=".$choi->id.">";
echo "<span class='handle'><i class='fa fa-ellipsis-v'></i><i class='fa fa-ellipsis-v'></i></span>";
echo "<span class='text'>".$choi->cs_code."</span>";
echo "</li>";
}
}
I'm looking to use this Script to save order
function saveOrder() {
var articleorder="";
$("#sortable li").each(function(i) {
if (articleorder=='')
articleorder = $(this).attr('id');
else
articleorder += "," + $(this).attr('id');
});
//articleorder now contains a comma separated list of the ID's of the articles in the correct order.
$.post('set_order.php', { order: articleorder })
.success(function(data) {
alert('saved');
})
.error(function(data) {
alert('Error: ' + data);
});
but i don't know what i should use in set_order.php ??
i'm trying with this code but i didn't get any result !!
$i = 1 ;
$orderlist = explode(',', $_POST['ordre']);
foreach ($orderlist as $k=>$order) {
$sql = 'UPDATE choix SET ordre = :ordre WHERE id = :id' ;
$query = $pdo->prepare($sql);
$query->bindParam(':ordre', $i, PDO::PARAM_INT);
$query->bindParam(':id', $id, PDO::PARAM_INT);
$query->execute();
$i++ ;
}
you can check my Database classe here

Dynamic Forms Won't Correctly Insert Into MySQL Database

<body>
<?php
$con = mysqli_connect('localhost','root','','cash');
$query = "SELECT DISTINCT category FROM cash";
$result = mysqli_query($con,$query);
$dropDownList = '<select name="names[]"><option value = "">---Select---</option>';
while ( $d=mysqli_fetch_assoc($result)) {
$dropDownList .= "<option value='" . $d['category'] . "'>" . $d['category'] . "</option>";
}
$dropDownList .= '</select>';
?>
<script type="text/javascript">
$(document).ready(function() {
var InputsWrapper = $("#InputsWrapper");
var AddButton = $("#AddMoreFileBox");
var dropOption = <?php echo json_encode($dropDownList) ?>;
var x = InputsWrapper.length;
var FieldCount = 1;
$(AddButton).click(function(e)//on add input button click
{
FieldCount++;
$(InputsWrapper).append('<tr><td>'+dropOption+'<td><input type="text" name="cate[]" id="categ"/></td><td><input type="number" name="money[]" id="amount"/></td></tr>');
x++;
return false;
});
});
</script>
<form action="selectxpprocess.php" method="post">
<table id="InputsWrapper" >
<tr>
<span class="small">Add More Field</span>
</tr>
<tr>
<td><label for='names[]'>Category:</label></td>
<td><label for='cate[]'>New Category:</label></td>
<td><label for='money[]'>Amount:</label></td>
</tr>
<tr>
<td><?php echo $dropDownList?></td>
<td><input type="text" name="cate[]" id="categ"/></td>
<td><input type="number" name="money[]" id="amount"/></td>
</tr>
</table>
<input type="submit" />
</form>
</body>
Here's my first page. I have a button that when you click it another Dropdown, text box, and number input will pop up. The condition I want is if nothing is selected in the dropdown then get data from the textbox. After that pass the corresponding amount value to the database.
<?php
$con = mysqli_connect('localhost','root','','cash');
if($_POST['names'] != '' && $_POST['cate'] == '') {
foreach($_POST['names'] as $catego) {
foreach($_POST['money'] as $amo){
mysqli_query($con,"INSERT INTO cash (category, amount) VALUES ('".$catego."','".$amo."')");
}
}
}else {
foreach($_POST['cate'] as $categ) {
foreach($_POST['money'] as $amo){
mysqli_query($con,"INSERT INTO cash (category, amount) VALUES ('".$categ."','".$amo."')");
}
}
}
$_POST=array();
mysqli_close($con);
header("Location: selectxp.php");
exit;
?>
Since your $_POST['names'] & $_POST['cate'] are arrays you can't check them as a string, ie. if($_POST['names'] != '' && $_POST['cate'] == ''). Also, you are nesting your loops, where instead you need to link them by the array keys. Something like -
foreach($_POST['names'] as $key => $val){
if($_POST['names'][$key] != '' && $_POST['cate'][$key] == '') {
$catego = mysqli_real_escape_string($con,$_POST['names'][$key]);
$amo = mysqli_real_escape_string($con,$_POST['money'][$key]);
mysqli_query($con,"INSERT INTO cash (category, amount) VALUES ('".$catego."','".$amo."')");
}
else {
$catego = mysqli_real_escape_string($con,$_POST['cate'][$key]);
$amo = mysqli_real_escape_string($con,$_POST['money'][$key]);
mysqli_query($con,"INSERT INTO cash (category, amount) VALUES ('".$catego."','".$amo."')");
}
}

Displaying existing content in editable textarea

Hi I am trying to make editable page with javascript and php and I want to display whats already stored in the area however it does not work. Its meant to be a blog page meaning that there are multiple posts. And I am unsure whether the problem is within the js or php.
This is the javascript I am using. The console.log() writes that post_id is unassigned.
$(document).on('click', '.editButton', function () {
var post_id = $(this).parent().data('id');
var self = this;
$.getJSON(settings.server, {post_id: post_id}, function(data){
var editableText = '<textarea class="editPostBody">' + data.body + '</textarea>';
console.log(post_id);
$(".post").parent().replaceWith(editableText);
});
});
var formatPost = function(d) {
var s = '';
s = '<div class="post" data-id="' + d.post_id + '"><h2 class="postHeading">' + d.title +'</h2>';
s += d.body;
s += '<p> Posted on: ' + d.date + '</p>';
s += '<div class="btn editButton">Edit Post</div>'
s += '</div>'
return s;
};
And this is the PHP file
connection to db established prior
if(count($_GET)) {
if(isset($_GET['post_id'])){
get_post_id( $_GET['post_id']);
}
}
else{
get_posts();
}
function get_posts() {
global $link;
// $sql = "SELECT COUNT(1) FROM posts";
// $result = mysqli_query($link, $sql);
// $total = mysqli_fetch_array($result);
$sql = "SELECT * FROM post ORDER BY date DESC LIMIT 0, 5";
$result = mysqli_query($link, $sql);
$rows = array();
while ($row = mysqli_fetch_assoc($result)) {
$rows[] = $row;
}
// $json = '{"total":"' . $total[0] . '","posts":';
$json = json_encode($rows);
// $json .= "}";
print($json);
}
function get_post_id($postId){
global $link;
$sql = "SELECT * FROM post WHERE id = $postId";
$result = mysqli_query($link, $sql);
$toSend = mysqli_fetch_assoc($result);
print json_encode($toSend);
}
Thank you
I modified the code like this
function get_post_id($postId){
global $link;
$sql = "SELECT * FROM post WHERE post_id = $postId";
$result = mysqli_query($link, $sql);
$toSend = mysqli_fetch_assoc($result);
print json_encode($toSend);
}
and JS
$(document).on('click', '.editButton', function () {
var post_id = $(this).parent().data('id');
// console.log(post_id);
var self = this;
$.getJSON(settings.server, {post_id: post_id}, function(data){
var editableText = $('<textarea class="editPostBody">' + data.body + '</textarea>');
console.log(post_id);
$(".post").parent().replaceWith(editableText);
});

I created a dropdown list and how to display the other columns data of selected item?

this is my code for dropdown list
<?php
$sql = "SELECT * FROM parts";
$result = mysql_query($sql);
echo "<select name='name' class='ed'>";
echo "<option id='0'> --Select Part Name-- </option>";
while ($row = mysql_fetch_array($result)) {
$op1=$row['part_description'];
$op2=$op1.$row['price'];
$op3=$op2.$row['weight'];
echo "<option value='" . $row['part_description'] ."'>" .$op3 ."</option>";
echo $op3;
}
echo "</select>";
?>
I have 3 columns for my database
part_description, price and weight. In the dropdownlist i created, you can select stored items at part_description. What I want to do is if I select that item in drop down list it will also display also the price and weight. But the display should be out of the box.
Please help me thanks
<?php
$sql = "SELECT part_description FROM parts";
$result = mysql_query($sql);
echo "<select name='name' class='ed'>";
echo "<option id='0'> --Select Part Name--</option>";
while ($row = mysql_fetch_array($result)) {
$op1=$row['part_description'];
$op2=$op1.$row['price'];
$op3=$op2.$row['weight'];
echo "<option value='" . $row['part_description'] ."'>" .$op3 ."</option>";
}
echo "</select>";
?>
This is for print three value in single option tag.
And let me know Is this your expectation.
You can do it in Javascript.
<?php
$parts = mysqli_query($conn, "SELECT part_description, price, weight FROM parts");
$theParts = [];
while ($row = mysqli_fetch_assoc($parts)) {
$part = [];
$part['description'] = $row['part_description'];
$part['price'] = $row['price'];
$part['weight'] = $row['weight'];
$theParts[] = $part;
}
?>
<script type="text/javascript">
var theParts = <?php echo(json_encode($theParts));?>;
function createDropDown() {
var theDropdown = "<select name='name' id='theDropDown' class='ed' onchange='didChange()'>";
theDropdown += "<option value='0'>--Select Part Name--</option>";
theParts.forEach(function(entry) {
theDropdown += "<option value='" + entry['description'] + "'>" + entry['description'] + "</option>";
});
theDropdown += "</select>";
return theDropdown;
}
function didChange() {
var e = document.getElementById("theDropDown");
var str = e.options[e.selectedIndex].value;
var price = null;
var weight = null;
theParts.forEach(function(entry) {
if (entry['description']==str) {
price = entry['price'];
weight = entry['weight'];
}
});
}
</script>
(I typed this code directly into StackOverflow and haven't tested it but it should work)
EDIT:
Here's how to do it using MySQL, although I don't recommend using it.
$conn = mysql_connect('localhost', 'username', 'password');
mysql_select_db('database', $conn);
$results = mysql_query("SELECT part_description, price, weight FROM parts");
while ($row = mysql_fetch_assoc($results)) {
//Same as above.
}

Categories