passing variable in ajax from one page to another - php

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;?>" />

Related

Get values from dynamic dropdown values and show them in a delimited text box on each new dynamic row that is generated in php and jquery

I have a table in which there is a row. The first cell of the row contains a drop-down list, and other rows are generated dynamically in case of an argument. The drop-down list contains an option with two fields from the database, one of which is text and the other is a number. The two are linked to each other. The problem that I am stuck with is that in the table The text and its associated number from the database appear only in the first row in the table, I want to repeat this in the table in the rest of the dynamically generated rows, that each text and its associated value appear in the drop down list
The problem in the image
php code:
`
<td class="td"><select class="form-control select_acount" name="account[]"required>
<option value="">--الحساب--</option>
<?php
$query = "select * from sah7atmain_acouts WHERE company like '".$multi."'";
$result = mysqli_query($con,$query);
$data = array();
if($result)
{
while($row = mysqli_fetch_assoc($result)){
$data[] = $row;
?>
<?php echo '<option value="'.$row['acount_mounte'].'">'.$row['acount_name'].'</option>'?>;
<?php
}
} else{
}
?>
</select>
</td>
jquery code:
$('.select_acount').on('change', function() {
$(this).closest('tr').find('.mount').val($(this).val());
});
var data = <?php echo json_encode($data); ?>;
var product_dd = "";
product_dd += '<select class="form-control select_acount" name="account[]"required>';
product_dd += '<option value="">--الحساب--</option>';
if(data.length > 0){
for(let i = 0; i < data.length; i ++) {
product_dd += `<option value="${data[i]['acount_mounte']}">${data[i]['acount_name']}</option>`;
}
}
product_dd += "</select>";
var i = 0;
$("#add-btn").click(function() {
++i;
$("#dynamicAddRemove").append('<tr><td class="td">'+product_dd+'</td> <td class="td"><input type="number" name="debtor[' + i + ']" id="fname"class="form-control debtor arabicNumbers" onkeydown="return event.keyCode !== 69" required></td> <td class="td"><input type="number" name="creditor[' + i + ']" id="james" class="form-control creditor arabicNumbers" onkeydown="return event.keyCode !== 69" required></td> <td class="td"><input type="text" name="description[' + i + ']" class="form-control" required></td> <td> <input type="text" name="mount[' + i + ']" class="form-control mount"required></td><td class="td2"><button type="button" name="add" class="btn btn-danger remove-tr"><i class="fas fa-trash" ></i></button></td></tr>');
});
$(document).on('click', '.remove-tr', function() {
$(this).parents('tr').remove();
});
`

A problem with fetching data from the database in dynamically generated drop-down lists

I have a table that contains a row with the ability to generate other dynamic rows. The drop-down list works now in every new row that is created. I have the first row. The drop-down list that carries data from the database works well and the data is shown in it well, but when adding a new dynamic row and when Clicking on the drop down list the values written on it all show with the word Undefined all the values of the drop down list written on it show up with the word : Undefined I am really stuck any suggestions would be appreciated and thanks
php code:
`
<td class="td"><select class="form-control select_acount" name="account[]"required>
<option value="">--الحساب--</option>
<?php
$query = "select * from sah7atmain_acouts WHERE company like '".$multi."'";
$result = mysqli_query($con,$query);
$data = array();
if($result)
{
while($row = mysqli_fetch_assoc($result)){
$data[] = $row;
?>
<?php echo '<option value="'.$row['acount_mounte'].'">'.$row['acount_name'].'</option>'?>;
<?php
}
} else{
}
?>
</select>
</td>
jquery code:
var data = '<?php echo $data; ?>';
var product_dd = "";
product_dd += '<select class="form-control select_acount" name="account[]"required>';
product_dd += '<option value="">--الحساب--</option>';
if(data.length > 0){
for(let i = 0; i < data.length; i ++) {
product_dd += `<option value="${data[i]['acount_mounte']}">${data[i]['acount_name']}</option>`;
}
}
product_dd += "</select>";
var i = 0;
$("#add-btn").click(function() {
++i;
$("#dynamicAddRemove").append('<tr><td class="td">'+product_dd+'</td> <td class="td"><input type="number" name="debtor[' + i + ']" id="fname"class="form-control debtor arabicNumbers" onkeydown="return event.keyCode !== 69" required></td> <td class="td"><input type="number" name="creditor[' + i + ']" id="james" class="form-control creditor arabicNumbers" onkeydown="return event.keyCode !== 69" required></td> <td class="td"><input type="text" name="description[' + i + ']" class="form-control" required></td> <td> <input type="text" name="mount[' + i + ']" class="form-control mount" required> </td><button type="button" name="add" class="btn btn-danger remove-tr"><i class="fas fa-trash-alt"></i></button></td></tr>');
});
$(document).on('click', '.remove-tr', function() {
$(this).parents('tr').remove();
});
`

$data[] = $row array give undefined in php

I used an array to print the data in several dynamically generated drop-down lists, but the result is very disappointing and does not bring the expected values from the database in the drop-down lists that I generate when needed, noting that the first drop-down list, which is outside the dynamic generation context, works well and brings the expected data, but the problem is Any new list generated dynamically, the values will only appear with the word "undefined" Any solution will be greatly appreciated...
here problem as GIF amage
php code:
`
<td class="td"><select class="form-control select_acount" name="account[]"required>
<option value="">--الحساب--</option>
<?php
$query = "select * from sah7atmain_acouts WHERE company like '".$multi."'";
$result = mysqli_query($con,$query);
$data = array();
if($result)
{
while($row = mysqli_fetch_assoc($result)){
$data[] = $row;
?>
<?php echo '<option value="'.$row['acount_mounte'].'">'.$row['acount_name'].'</option>'?>;
<?php
}
} else{
}
?>
</select>
</td>
jquery dynamic genaration code:
var data = '<?php echo $data; ?>';
var product_dd = "";
product_dd += '<select class="form-control select_acount" name="account[]"required>';
product_dd += '<option value="">--الحساب--</option>';
if(data.length > 0){
for(let i = 0; i < data.length; i ++) {
product_dd += `<option value="${data[i]['acount_mounte']}">${data[i]['acount_name']}</option>`;
}
}
product_dd += "</select>";
var i = 0;
$("#add-btn").click(function() {
++i;
$("#dynamicAddRemove").append('<tr><td class="td">'+product_dd+'</td> <td class="td"><input type="number" name="debtor[' + i + ']" id="fname"class="form-control debtor arabicNumbers" onkeydown="return event.keyCode !== 69" required></td> <td class="td"><input type="number" name="creditor[' + i + ']" id="james" class="form-control creditor arabicNumbers" onkeydown="return event.keyCode !== 69" required></td> <td class="td"><input type="text" name="description[' + i + ']" class="form-control" required></td> <td> <input type="text" name="mount[' + i + ']" class="form-control mount" required> </td><button type="button" name="add" class="btn btn-danger remove-tr"><i class="fas fa-trash-alt"></i></button></td></tr>');
});
$(document).on('click', '.remove-tr', function() {
$(this).parents('tr').remove();
});
`

multiple rows are not stored in database

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.

JSON values from dropdown showing ID numbers instead of strings in database

I am trying to submit two dropdown lists with JSON data into my database table. I can get as far as the data inserted into the table but the 'date' and 'time' columns show the ID and parent ID instead of the date and times that are available in the dropdowns. Can anyone tell me why this is? (Main relevant code showing)
<?php
session_start();
include('includes/config.php');
error_reporting(0);
if (isset($_POST['submit'])) {
$arenadate = $_POST['date'];
$arenatime = $_POST['time'];
$useremail = $_SESSION['login'];
$sql = "INSERT INTO tblbooking(userEmail,ArenaDate,ArenaTime) VALUES(:useremail,:date, :time)";
$query = $dbh->prepare($sql);
$query->bindParam(':useremail', $useremail, PDO::PARAM_STR);
$query->bindParam(':date', $arenadate, PDO::PARAM_STR);
$query->bindParam(':time', $arenatime, PDO::PARAM_STR);
$query->execute();
$lastInsertId = $dbh->lastInsertId();
if ($lastInsertId) {
echo "<script>alert('Booking successful.');</script>";
}
else {
echo "<script>alert('Something went wrong. Please try again');</script>";
}
}
?>
<form action="" method="post">
<div class="contact_form gray-bg">
<div class="form-group">
<label for="" class="control-label">Select Date</label>
<select name="date" id="date" class="form-control white_bg"
data-width="120px" style="color:black" required>
<option value="">Select Date</option>
</select>
</div>
<div class="form-group">
<label for="" class="control-label">Select Time</label>
<select name="time" id="time" class="form-control white_bg"
data-width="120px" style="color:black" required>
<option value="">Select Time</option>
</select>
</div>
<?php if ($_SESSION['login']) {
?>
<div class="modal-footer text-center">
<input type="submit" name="submit" value="Confirm Booking"
class="btn btn-xs uppercase">
</div>
<?php } else { ?>
<a href="#loginform" class="btn btn-xs uppercase" data-toggle="modal"
data-dismiss="modal">Login To Book Seat</a>
<?php } ?>
</div>
</div>
</div>
</form>
</div>
</div>
</section>
<script>
$(document).ready(function (e) {
function get_json_data(id, parent_id) {
var html_code = '';
$.getJSON('date_list.json', function (data) {
ListName = id.substr(0, 1).toUpperCase() + id.substr(1);
html_code += '<option value="">Select ' + ListName + '</option>';
$.each(data, function (key, value) {
if (value.parent_id == parent_id) {
html_code += '<option value="' + value.id + '">' + value.avail + '</option>';
}
});
$('#' + id).html(html_code);
});
}
get_json_data('date', 0);
$(document).on('change', '#date', function () {
var date_id = $(this).val();
if (date_id != '') {
get_json_data('time', date_id);
} else {
$('#time').html('<option value="">Select Time</option>');
}
});
});
</script>
You are overwriting the empty option in #date so that isn't really needed in the html. You can change the following line from:
html_code += '<option value="' + value.id + '">' + value.avail + '</option>';
to:
html_code += '<option value="' + value.avail + '" data-id="'+value.id+'">' + value.avail + '</option>';
The posted value for 'date' and 'time' will be the selected options value attribute, but this will break selecting the date and getting the time based on that id. In this case you could add a data-id attribute and use that to get the time which means the following code would change from:
var date_id = $(this).val();
to:
var date_id = $(this).data('id');
Don't set the value attribute of an <option> tag unless you want the form to receive that value instead of the visible text.
If you write an option like this inside of a <select name="date">:
<option value="">Select an option</option>
Then the POSTing form will deliver $_POST['date'] = ''.
If you write:
<option>Select an option</option>
Then the POSTing form will deliver $_POST['date'] = 'Select an option'.
In terms of form delivery, there is never a need to duplicate the option text as a value.
If you want to store data inside of each <option> tag, I'll give the same advice as aCMoFoCord because data- attributes are clean and flexible regarding the values that they can hold.
Specifically, I'm saying:
function get_json_data(id, parent_id) {
var html_code = '';
$.getJSON('date_list.json', function (data) {
ListName = id.substr(0, 1).toUpperCase() + id.substr(1);
html_code += '<option value="">Select ' + ListName + '</option>';
$.each(data, function (key, value) {
if (value.parent_id == parent_id) {
html_code += '<option data-id="' + value.id + '">' + value.avail + '</option>';
}
});
$('#' + id).html(html_code);
});
}
Then:
$(document).on('change', '#date', function () {
if ($(this).val() != '') {
get_json_data('time', $(this).data('id'));
} else {
$('#time').html('<option value="">Select Time</option>');
}
});

Categories