I am using jQuery and Ajax in php. I want to submit multiple rows at a time. but my code is not working properly due to the 'plantation_journal_no' which is a primary key of plantation_journal_details and the foreign key of past_history_species_details . I am badly stuck here. Can anyone please advice me that how can I solve this problem?? Thanks in advance guys. codes are given below :
index.php
<div class="row">
<form method="post" id="insert_form2" style="padding-right: 10px;">
<div class="table-repsonsive">
<span id="error"></span>
<table class="table table-bordered" id="item_table2">
<tr>
<th>Species</th>
<th>Product</th>
<th>Quantity</th>
<th>Value (Rs.)</th>
<th><button type="button" name="add2" class="btn btn-success btn-sm add2"><span class="glyphicon glyphicon-plus"></span></button></th>
</tr>
</table>
</div>
<br>
<div align="right">
<input type="submit" name="submit4" class="btn btn-info" value="Add" onclick="move4()">
</div>
</form>
</div>
<script>
$(document).ready(function(){
$(document).on('click', '.add2', function(){
var html = '';
html += '<tr>';
html += '<td><input type="text" name="species[]" class="form-control species" /></td>';
html += '<td><select name="product[]" class="form-control product"><option value="">---Select---</option><option value="reserved">Reserved</option><option value="protected">Protected</option><option value="Unclassed">Unclassed</option></select></td>';
html += '<td><input type="text" name="quantity[]" class="form-control quantity" /></td>';
html += '<td><input type="text" name="value[]" class="form-control value" /></td>';
html += '<td><button type="button" name="remove2" class="btn btn-danger btn-sm remove2"><span class="glyphicon glyphicon-minus"></span></button></td></tr>';
$('#item_table2').append(html);
});
$(document).on('click', '.remove2', function(){
$(this).closest('tr').remove();
});
$('#insert_form2').on('submit', function(event){
event.preventDefault();
var error = '';
$('.species').each(function(){
var count = 1;
if($(this).val() == '')
{
error += "<p>Enter Item Name at "+count+" Row</p>";
return false;
}
count = count + 1;
});
$('.product').each(function(){
var count = 1;
if($(this).val() == '')
{
error += "<p>Enter Item Quantity at "+count+" Row</p>";
return false;
}
count = count + 1;
});
$('.quantity').each(function(){
var count = 1;
if($(this).val() == '')
{
error += "<p>Select Unit at "+count+" Row</p>";
return false;
}
count = count + 1;
});
$('.value').each(function(){
var count = 1;
if($(this).val() == '')
{
error += "<p>Select Unit at "+count+" Row</p>";
return false;
}
count = count + 1;
});
var form_data = $(this).serialize();
if(error == '')
{
$.ajax({
url:"insert2.php",
method:"POST",
data:form_data,
success:function(data)
{
if(data == 'ok')
{
$('#item_table2').find("tr:gt(0)").remove();
}
}
});
}
});
});
</script>
insert2.php
<?php
//insert.php;
if(isset($_POST["species"]))
{
$connect = new PDO("mysql:host=localhost;dbname=forestdb", "root", "");
$id=uniqid();
$sql="SELECT plantation_journal_no from plantation_journal_basic_details
where plantation_journal_no=(select max(plantation_journal_no) from
plantation_journal_basic_details);";
$state=$connect->prepare($sql);
$state->execute();
$row=$state->fetch();
$plantation_journal_no = $row['plantation_journal_no'];
for($count = 0; $count < count($_POST["species"]); $count++)
{
$query = "INSERT INTO past_history_species_details
(id, plantation_journal_no, species, product, quantity, value)
VALUES (:id, :plantation_journal_no, :species, :product, :quantity,
:value) ";
$statement = $connect->prepare($query);
$statement->execute(
array(
':id' => $id,
':plantation_journal_no' => $plantation_journal_no,
':species' => $_POST["species"][$count],
':product' => $_POST["product"][$count],
':quantity' => $_POST["quantity"][$count],
':value' => $_POST["value"][$count]
)
);
}
$result = $statement->fetchAll();
if(isset($result))
{
echo 'ok';
}
}
?>
Frontend Table:
Backend Table
I'm guessing id is the primary key of the past_history_species_details table. You're using the same uniqid() for every row you try to insert. You need to get a new ID each time through the loop.
for($count = 0; $count < count($_POST["species"]); $count++)
{
$id = uniqid();
$query = "INSERT INTO past_history_species_details
(id, plantation_journal_no, species, product, quantity, value)
VALUES (:id, :plantation_journal_no, :species, :product, :quantity,
:value) ";
$statement = $connect->prepare($query);
$statement->execute(
array(
':id' => $id,
':plantation_journal_no' => $plantation_journal_no,
':species' => $_POST["species"][$count],
':product' => $_POST["product"][$count],
':quantity' => $_POST["quantity"][$count],
':value' => $_POST["value"][$count]
)
);
}
Things would be easier if you made this an auto-increment column.
Related
Hello. I have a problem with the more difficult code but here I tried to simplify it a bit just to ask a question ... I have 3 tables in database: cars(cars_id,model), customers(customer_id,name,surname), sales(sales_id,customer_id,cars_id).And I don't know how to get the ID for the selected option in the select option tag. For example, for BMW X6 I want to get to ID = 2 and put this value in the cars_id column in the SALES table to avoid data redundancy. It's about relation. cars_id in the CARS table is the same as cars_id in the SALES table. But I want to do this using PHP MySQL.
<?php
//index.php
$connect = new PDO("mysql:host=localhost;dbname=store", "root", "");
function fill_unit_select_box($connect)
{
$output = '';
$query = "SELECT * FROM cars";
$statement = $connect->prepare($query);
$statement->execute();
$result = $statement->fetchAll();
foreach($result as $row)
{
$output .= '<option value="'.$row["model"].'">'.$row["model"].'</option>';
}
return $output;
}
?>
<html>
<head>
<title>Sales form</title>
<script src="jquery-3.5.0.min.js" defer></script>
<link rel="stylesheet" href="bootstrap.min.css" />
<script src="jquery-3.5.0.min.js"></script>
</head>
<body>
<div class="container">
<h3 align="center">Sales form</h3><br />
<form method="post" id="insert_form">
<div class="table-repsonsive">
<span id="error"></span>
<table class="table table-bordered" id="item_table">
<tr>
<th >sales</th>
<th >customer</th>
<th >cars</th>
<th><button type="button" name="add" class="btn btn-success btn-sm add"><span class="glyphicon glyphicon-plus">Add</span></button></th>
</tr>
</table>
<div align="center">
<input type="submit" name="submit" class="btn btn-info" value="Send" />
</div>
</div>
</form>
</div>
</body>
</html>
<script>
$(document).ready(function(){
$(document).on('click', '.add', function(){
var html = '';
html += '<tr>';
html += '<td class="lp"></td>';
html += '<td><input type="text" name="customers_name[]"></td>';
html += '<td><select style="backbround-color:white;"name="cars_name[]" class="form-control size_id"><option value=""><?php echo fill_unit_select_box($connect); ?></option></select></td>';
html += '<td><button type="button" name="remove" class="btn btn-danger btn-sm remove"><span class="glyphicon glyphicon-minus">Usuń</span></button></td></tr>';
$('#item_table').append(html);
var count=0;
$('.lp').each(function(){
count=count+1;
$(this).text(count);
});
});
$('#insert_form').on('submit', function(event){
event.preventDefault();
var form_data = $(this).serialize();
if(error == '')
{
$.ajax({
url:"insert.php",
method:"POST",
data:form_data,
success:function(data)
{
if(data == 'ok')
{
$('#item_table').find("tr:gt(0)").remove();
$('#error').html('<div class="alert alert-success">Dane zostały wysłane</div>');
}
}
});
}
else
{
$('#error').html('<div class="alert alert-danger">'+error+'</div>');
}
});
});
</script>
<?php
//insert.php;
session_start();
if(isset($_POST["customers_name"]))
{
$connect = new PDO("mysql:host=localhost;dbname=store", "root", "");
for($count = 0; $count < count($_POST["customers_name"]); $count++)
{
$query = "INSERT INTO sales
(customer_id,cars_id)
VALUES (:customer_id,:cars_id)
";
$statement = $connect->prepare($query);
$statement->execute(
array(
':customer_id' => $_POST["customers_name"][$count],
':cars_id' => $_POST["cars_name"][$count],
)
);
}
$result = $statement->fetchAll();
if(isset($result))
{
echo 'ok';
}
}
?>
So, you just have to edit your $output like this.
value="'.$row["model"] to value="'.$row["cars_id"]
change to cars_id only for value, so the user can see the name but you get id on form submit.
I have a form where
<form method="post" id="insert_form">
<div class="table-repsonsive">
<span id="error"></span>
<table class="css-serial" class="table table-bordered" id="item_table">
<thead>
<h5>Package Name:-<input type="text" name="packname" /><input type="hidden" id="packname" name="packname" value="<?php $packname;?>" /></h5>
<tr>
<th>sl.no</th>
<th>Service Type</th>
<th>Service Name</th>
<th>Sessions</th>
<th><button type="button" name="add" class="btn btn-success btn-xs add"><span class="glyphicon glyphicon-plus"></span>Add Services</button></th>
</tr>
</thead>
<tbody></tbody>
</table>
<div align="center">
<input type="submit" name="submit" class="btn btn-info" value="Save" />
</div>
</div>
</form>
with the script
$(document).ready(function(){
var count = 0;
$(document).on('click', '.add', function(){
count++;
var html = '';
html += '<tr>';
html += '<td> </td>';
html += '<input type="hidden" name="item_name[]" class="form-control item_name" />';
html += '<td><select name="item_category[]" class="form-control item_category" data-sub_category_id="'+count+'"><option value="">Select Service Type</option><?php echo fill_select_box($connect, "0"); ?></select></td>';
html += '<td><select name="item_sub_category[]" class="form-control item_sub_category" id="item_sub_category'+count+'"><option value="">Select Service Name</option></select></td>';
html +='<td><input type="text" name="nosessions[]" class="form-control nosessions" /></td>';
html += '<td><button type="button" name="remove" class="btn btn-danger btn-xs remove"><span class="glyphicon glyphicon-minus"></span></button></td>';
$('tbody').append(html);
});
$(document).on('click', '.remove', function(){
$(this).closest('tr').remove();
});
$(document).on('change', '.item_category', function(){
var category_id = $(this).val();
var sub_category_id = $(this).data('sub_category_id');
$.ajax({
url:"fill_sub_category.php",
method:"POST",
data:{category_id:category_id},
success:function(data)
{
var html = '<option value="">Select Sub Category</option>';
html += data;
$('#item_sub_category'+sub_category_id).html(html);
}
})
});
$('#insert_form').on('submit', function(event) {
event.preventDefault();
var error = '';
$('.item_category').each(function() {
var count = 1;
if($(this).val() == '')
{
error += '<p>Select Item Category at '+count+' row</p>';
return false;
}
count = count + 1;
});
$('.item_sub_category').each(function(){
var count = 1;
if($(this).val() == '') {
error += '<p>Select Item Sub category '+count+' Row</p> ';
return false;
}
count = count + 1;
});
$('.nosessions').each(function(){
var count = 1;
if($(this).val() == '') {
error += '<p>Select no of sessions '+count+' Row</p> ';
return false;
}
count = count + 1;
});
var form_data = $(this).serialize();
if(error == '') {
$.ajax({
url:"insert.php",
method:"POST",
data:form_data,
success:function(data) {
if(data == 'ok') {
$('#item_table').find('tr:gt(0)').remove();
$('#error').html('<div class="alert alert-success">Item Details Saved</div>');
}
}
});
} else {
$('#error').html('<div class="alert alert-danger">'+error+'</div>');
}
});
});
I need to get packname to the inser table insert.php please anybody help i dont understand ajax much . how to send the packname it is the overall name given to all other services so i need to pass packname in that array for every entry.Packname is single one for all these entries done and it should enter in each row inserted .
The FormData class provides a way to easily construct a set of key/value pairs representing form fields and their values.
After using it your script would look like:
<script>
$(document).ready(function(){
var count = 0;
$(document).on('click', '.add', function(){
count++;
var html = '';
html += '<tr>';
html += '<td> </td>';
html += '<input type="hidden" name="item_name[]" class="form-control item_name" />';
html += '<td><select name="item_category[]" class="form-control item_category" data-sub_category_id="'+count+'"><option value="">Select Service Type</option><?php echo fill_select_box($connect, "0"); ?></select></td>';
html += '<td><select name="item_sub_category[]" class="form-control item_sub_category" id="item_sub_category'+count+'"><option value="">Select Service Name</option></select></td>';
html +='<td><input type="text" name="nosessions[]" class="form-control nosessions" /></td>';
html += '<td><button type="button" name="remove" class="btn btn-danger btn-xs remove"><span class="glyphicon glyphicon-minus"></span></button></td>';
$('tbody').append(html);
});
$(document).on('click', '.remove', function(){
$(this).closest('tr').remove();
});
$(document).on('change', '.item_category', function(){
var category_id = $(this).val();
var sub_category_id = $(this).data('sub_category_id');
$.ajax({
url:"fill_sub_category.php",
method:"POST",
data:{category_id:category_id},
success:function(data)
{
var html = '<option value="">Select Sub Category</option>';
html += data;
$('#item_sub_category'+sub_category_id).html(html);
}
})
});
$('#insert_form').on('submit', function(event){
event.preventDefault();
var error = '';
$('.item_category').each(function(){
var count = 1;
if($(this).val() == '')
{
error += '<p>Select Item Category at '+count+' row</p>';
return false;
}
count = count + 1;
});
$('.item_sub_category').each(function(){
var count = 1;
if($(this).val() == '')
{
error += '<p>Select Item Sub category '+count+' Row</p> ';
return false;
}
count = count + 1;
});
$('.nosessions').each(function(){
var count = 1;
if($(this).val() == '')
{
error += '<p>Select no of sessions '+count+' Row</p> ';
return false;
}
count = count + 1;
});
var form_data = new FormData($(this)[0]);
if(error == '')
{
$.ajax({
url:"insert.php",
method:"POST",
data:form_data,
success:function(data)
{
if(data == 'ok')
{
$('#item_table').find('tr:gt(0)').remove();
$('#error').html('<div class="alert alert-success">Item Details Saved</div>');
}
}
});
}
else
{
$('#error').html('<div class="alert alert-danger">'+error+'</div>');
}
});
});
</script>
In addition, you may need to change:
<h5>Package Name:-<input type="text" name="packname" /><input type="hidden" id="packname" name="packname" value="<?php $packname;?>" /></h5>
Into:
<h5>Package Name:-<input type="text" name="packname" value="<?php $packname;?>" disabled="disabled" /></h5>
<input type="hidden" id="packname" name="packname" value="<?php $packname;?>" />
I downloaded the following code from internet. This code will add extra inputs from the user but it will create a new row in the database. I want this to be inserted in different columns of a row. How do I do it?
I have created fields for insertion in the Column.
<form name="add_name" id="add_name">
<div class="table-responsive">
<table class="table table-bordered" id="dynamic_field">
<tr>
<td><input type="text" name="name[]" placeholder="Enter your Name"
class="form-control name_list" /></td>
<td><button type="button" name="add" id="add" class="btn btn-success">Add
More</button>
</td></tr>
</table>
<input type="button" name="submit" id="submit" class="btn btn-info"
value="Submit" />
</form>
<script>
$(document).ready(function(){
var i=1;
$('#add').click(function(){
i++;
$('#dynamic_field').append('<tr id="row'+i+'"><td><input type="text" name="name[]" placeholder="Enter your Name" class="form-control name_list" /></td><td><button type="button" name="remove" id="'+i+'" class="btn btn-danger btn_remove">X</button></td></tr>');
});
$(document).on('click', '.btn_remove', function(){
var button_id = $(this).attr("id");
$('#row'+button_id+'').remove();
});
$('#submit').click(function(){
$.ajax({
url:"name.php",
method:"POST",
data:$('#add_name').serialize(),
success:function(data)
{
alert(data);
$('#add_name')[0].reset();
}
});
});
});
</script>
And this is the name.php
<?php
$connect = mysqli_connect("localhost", "root", "", "testing");
$number = count($_POST["name"]);
if($number > 1)
{
for($i=0; $i<$number; $i++)
{
if(trim($_POST["name"][$i] != ''))
{
$sql = "INSERT INTO tbl_name(namec) VALUES('".mysqli_real_escape_string($connect, $_POST["name"][$i])."')";
mysqli_query($connect, $sql);
}
}
echo "Data Inserted";
}
else
{
echo "Please Enter Name";
}
?>
As per your comments, I am assuming that there will be 4 names max. You can do the work as below:-
<?php
$connect = mysqli_connect("localhost", "root", "", "testing");
$number = count($_POST["name"]);
$db_col_names = array('namea','nameb','namec','named');
$names = array();
if($number > 1)
{
for($i=0; $i<$number; $i++)
{
if(trim($_POST["name"][$i]) != '')
{
$names[] = mysqli_real_escape_string($connect, $_POST["name"][$i]); //get all the values from from in an array
}
}
$names = implode("','", $names); //make all the values as string to pass in insert query
$db_col_names = array_slice($db_col_names, 0, $number); //slice the DB columns to the names length entered
$db_col_names = implode("`,`", $db_col_names ); //make all the values as string to pass in insert query
$sql = "INSERT INTO tbl_name(`".$db_col_names."`) VALUES('".$names."')";
mysqli_query($connect, $sql);
echo "Data Inserted";
}
else
{
echo "Please Enter Name";
}
?>
Hope this will do the work which you need. If any more modifications needed or any issue, do let me know in comments
This question already has answers here:
Syntax error due to using a reserved word as a table or column name in MySQL
(1 answer)
Why does this PDO statement silently fail?
(2 answers)
Reference - What does this error mean in PHP?
(38 answers)
Closed 4 years ago.
<?php
//index.php
$connect = new PDO("mysql:host=localhost;dbname=sales", "root", "");
function e_type($connect) {
$output1 = '';
$query = "SELECT * FROM elimo_type ORDER BY type ASC";
$statement = $connect->prepare($query);
$statement->execute();
$result = $statement->fetchAll();
foreach ($result as $row) {
$output1 .= '<option value="' . $row["type"] . '">' . $row["type"] . '</option>';
}
return $output1;
}
function hw_type($connect) {
$output2 = '';
$query = "SELECT * FROM hw_version ORDER BY type ASC";
$statement = $connect->prepare($query);
$statement->execute();
$result = $statement->fetchAll();
foreach ($result as $row) {
$output2 .= '<option value="' . $row["type"] . '">' . $row["type"] . '</option>';
}
return $output2;
}
function sw_type($connect) {
$output3 = '';
$query = "SELECT * FROM sw_version ORDER BY type ASC";
$statement = $connect->prepare($query);
$statement->execute();
$result = $statement->fetchAll();
foreach ($result as $row) {
$output3 .= '<option value="' . $row["type"] . '">' . $row["type"] . '</option>';
}
return $output3;
}
?>
<?php
include 'header.php';
?>
<div class="container">
<h3 align="center">Purchase</h3>
<br />
<h4 align="center">Enter Purchase Details</h4>
<br />
<form method="post" id="insert_form">
<div class="table-repsonsive">
<span id="error"></span>
<table class="table table-bordered" id="item_table">
<tr>
<th>Serial No</th>
<th>Type</th>
<th>Hardware Version</th>
<th>Software Version</th>
<th>Key</th>
<th><button type="button" name="add" class="btn btn-success btn-sm add"><span class="glyphicon glyphicon-plus"></span></button></th>
</tr>
</table>
<div align="center">
<input type="submit" name="submit" class="btn btn-info" value="Insert" />
</div>
</div>
</form>
</div>
</body>
</html>
<script>
$(document).ready(function () {
$(document).on('click', '.add', function () {
var html = '';
html += '<tr>';
html += '<td><input type="text" name="serial_no[]" class="form-control serial_no" /></td>';
html += '<td><select name="e_type[]" class="form-control e_type"><option value="">Select Type</option><?php echo e_type($connect); ?></select></td>';
html += '<td><select name="hw_type[]" class="form-control hw_type"><option value="">Select Hardware Version</option><?php echo hw_type($connect); ?></select></td>';
html += '<td><select name="sw_type[]" class="form-control sw_type"><option value="">Select Software Version</option><?php echo sw_type($connect); ?></select></td>';
html += '<td><input type="text" name="key[]" class="form-control key" /></td>';
html += '<td><button type="button" name="remove" class="btn btn-danger btn-sm remove"><span class="glyphicon glyphicon-minus"></span></button></td></tr>';
$('#item_table').append(html);
});
$(document).on('click', '.remove', function () {
$(this).closest('tr').remove();
});
$('#insert_form').on('submit', function (event) {
event.preventDefault();
var error = '';
$('.serial_no').each(function () {
var count = 1;
if ($(this).val() == '')
{
error += "<p>Enter Serial no at " + count + " Row</p>";
return false;
}
count = count + 1;
});
$('.e_type').each(function () {
var count = 1;
if ($(this).val() == '')
{
error += "<p>Select Type at " + count + " Row</p>";
return false;
}
count = count + 1;
});
$('.hw_type').each(function () {
var count = 1;
if ($(this).val() == '')
{
error += "<p>Select Hardware Version at " + count + " Row</p>";
return false;
}
count = count + 1;
});
$('.sw_type').each(function () {
var count = 1;
if ($(this).val() == '')
{
error += "<p>Select Software Version at " + count + " Row</p>";
return false;
}
count = count + 1;
});
$('.key').each(function () {
var count = 1;
if ($(this).val() == '')
{
error += "<p>Enter Key at " + count + " Row</p>";
return false;
}
count = count + 1;
});
var form_data = $(this).serialize();
if (error == '')
{
$.ajax({
url: "insert.php",
method: "POST",
data: form_data,
success: function (data)
{
if (data == 'ok')
{
$('#item_table').find("tr:gt(0)").remove();
$('#error').html('<div class="alert alert-success">Purchase Details Saved</div>');
}
}
});
} else
{
$('#error').html('<div class="alert alert-danger">' + error + '</div>');
}
});
});
</script>
<?php
//insert.php;
if (isset($_POST["serial_no"])) {
$connect = new PDO("mysql:host=localhost;dbname=sales", "root", "");
$id = uniqid();
for ($count = 0; $count < count($_POST["serial_no"]); $count++) {
$query = "INSERT INTO elimo_purchase
(id,serial_no, e_type, hw_type, sw_type,key)
VALUES (:id,:serial_no, :e_type, :hw_type, :sw_type,:key)";
$statement = $connect->prepare($query);
$statement->execute(
array(
':id' => $id,
':serial_no' => $_POST["serial_no"][$count],
':e_type' => $_POST["e_type"][$count],
':hw_type' => $_POST["hw_type"][$count],
':sw_type' => $_POST["sw_type"][$count],
':key' => $_POST["key"][$count]
)
);
}
$result = $statement->fetchAll();
if (isset($result)) {
echo 'ok';
}
}
?>
I'm getting output as purchase details saved but result is not stored into database.
You need to debug as per below,
Check all the values which you pass in insert query print all and check values.
Then print the query and fire the same query manually and check it was inserted or not
When you're doing an INSERT query, you can't use a fetch function, because it doesn't return any data. That can only be used with SELECT. You need to check the result of $statement->execute().
if(isset($_POST["serial_no"]))
{
$connect = new PDO("mysql:host=localhost;dbname=sales", "root", "");
$id = uniqid();
$query = "INSERT INTO elimo_purchase (id,serial_no, e_type, hw_type, sw_type,key)
VALUES (:id,:serial_no, :e_type, :hw_type, :sw_type,:key)";
$statement = $connect->prepare($query);
for($count = 0; $count < count($_POST["serial_no"]); $count++)
{
if (!$statement->execute(
array(
':id' => $id,
':serial_no' => $_POST["serial_no"][$count],
':e_type' => $_POST["e_type"][$count],
':hw_type' => $_POST["hw_type"][$count],
':sw_type' => $_POST["sw_type"][$count],
':key' => $_POST["key"][$count]
)
)) {
die('not ok');
}
}
echo 'ok';
}
I got two dropdowns for my product in my cart.
All products are stored in sessions inside of a foreach loop.
But my dropdowns only work for the first product from loop.
Exemple: if i have 2 products in my cart the fisrt product row gets the cost based on both dorpdowns.
but the second product is getting the same cost from the first dropdown.
can someone please tell me how to fix this.
my script in checkout.php
$(document).ready(function() {
$('.fabric, .size').on('change', sendData);
function sendData() {
var fabricID = $('.fabric').val();
var sizeID = $('.size').val();
var cost = $(this).attr('data-id');
if ( fabricID !== "" && sizeID !== "") {
$.ajax({
type : 'GET',
url : 'calculates.php',
dataType : 'json',
data : {
prod_id:cost,
fabric_id: fabricID,
size_id: sizeID
}
}).done(function(data) {
$('.icms' + cost).text(data.val);
});
}
}
});
My php foreach loop in cart.php
function cart(){
global $conn;
$fabric_options = '<option>Select Fabric</option>';
$query2 = "SELECT * FROM almofadas";
$result = mysqli_query($conn,$query2);
while($rows = mysqli_fetch_assoc($result)){
$tecido=$rows['tecido'];
$id_price=$rows['id_price'];
$t50='50';
$t45='45';
$fabric_options .= '<option value="'.$id_price.'">'.$tecido.'</option>';
}
if(!isset($_SESSION['icms'])) {
$_SESSION['icms']='0';
}else{
$_SESSION['icms'];
}
foreach ($_SESSION as $name => $value) {
if($value > 0){
if(substr($name, 0, 8 ) == "product_"){
$length = strlen($name) -8;
$item_id = substr($name,8 , $length);
$query = "SELECT *
FROM gallery2
WHERE gallery2.id =".escape_string($item_id). "";
$run_item = mysqli_query($conn,$query);
while($rows = mysqli_fetch_assoc($run_item)){
$vari = $rows['variante'];
$num = $rows['title'];
$id = $rows['id'];
$btn_add ='<button type="button" class="btn btn-success actions plus" data-action="plus" product_id="'.$id.'"><i class="fa fa-plus fa-lg" aria-hidden="true" add_btn></i></button>';
$btn_remove ='<button type="button" class="btn btn-warning actions less" data-action="remove" product_id="'.$id.'"><i class="fa fa-minus fa-lg" aria-hidden="true" remove_btn></i></button>';
$btn_delete ='<button type="button" class="btn btn-default actions" data-action="delete" product_id="'.$id.'" onclick="deleteRow(this)"><i class="fa fa-times fa-lg" aria-hidden="true"></i></button>';
if($rows['variante'] < 1){
$vari="";
}else{
$vari = "-".$rows['variante'];
}
$product = '
<tr>
<td style="width:100px; "><img src="../'.$rows['image'].'" style="width:90%;border: 1px solid black;"></td>
<td>'.$num.''.$vari.'</td>
<td style="width:15%;">
<select name="fabric" class="fabric select form-control selectpicker" required="" data-id="'.$id.'">
'. $fabric_options . '
</select>
</td>
<td>
<select data-id="'.$id.'" class="select size form-control selectpicker" required style="width:80%;" >
<option>Select size</option>
<option value="'.$t50.'">50x'.$t50.'</option>
<option value="'.$t45.'">45x'.$t45.'</option>
</select>
</td>
<td class="product'.$id.'">'.$value.'</td>
<td class="icms">R$: '.$_SESSION['icms'].'</td>
<td class="total'.$id.'" data-id="'.$id.'">R$: '.$value * $_SESSION['icms'] .' </td>
<td>
'.$btn_add.' '.$btn_remove.' '.$btn_delete.'
</td>
</tr>';
echo $product;
}
}
}
}
}
and this is where my calculations are made..
calculates.php
<?php header('Content-Type: application/json');
include_once '../incluedes/conn_cms.php'; //session allways start here
if(isset($_GET["size_id"],$_GET["fabric_id"],$_GET['prod_id'])){
$size_id=$_GET["size_id"] ;
$fabric_id=$_GET["fabric_id"] ;
$prod = $_GET['prod_id'];
$prodname = 'product_'.$prod;
$query3 =" SELECT * FROM valores_almofadas WHERE size='$size_id' AND price_id ='$fabric_id'";
$result = mysqli_query($conn,$query3);
while($rows = mysqli_fetch_assoc($result)){
if($_SESSION['estado'] == 'SP'){
$ICMS = $rows['icms_7'];
}else{
$ICMS = $rows['icms_12'];
}
$_SESSION['icms']=$ICMS;
}
echo json_encode( $_SESSION['icms']);
}
how can i make my dropdown work foreach product?
The problem is that var fabricID = $(".fabric").val() is selecting the value from the first element it finds with the fabric class. This will be the same element (the first one) every time, no matter how many elements exist on the page with that class.
You need to select the value from the correct elements. This is made slightly trickier by the fact that you need to send both the fabric and size values simultaneously. Luckily you have got the row ID as a data attribute on both the <select> elements, so we can use this to match them up.
$(document).ready(function() {
$('.fabric, .size').on('change', sendData);
function sendData() {
//use the data-id attribute of the selected element to match the correct elements
var id = $(this).data("id");
var fabricID = $('.fabric[data-id=' + id + ']').val();
var sizeID = $('.size[data-id=' + id + ']').val();
if ( fabricID !== "" && sizeID !== "") {
$.ajax({
type : 'GET',
url : 'calculates.php',
dataType : 'json',
data : {
prod_id:id,
fabric_id: fabricID,
size_id: sizeID
}
}).done(function(data) {
$('.icms' + id).text(data.val);
});
}
}
});