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

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>');
}
});

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();
});
`

How can I populate a drop down with the value retrieved from mysql database?

I have two forms, one that adds data(addData.php) and one that retrieved and edit the added data(editData.php). In addData.php I have three drop down list (Country, State, and City) that is dynamic and dependent from one another. Each have their own tables in a database in which they get their data(country_table, state_table and city_table). The country_table has two fields, which is country_id and country_name, the other two tables has three fields: state_id, country_id and state_name. The city_table has a similar set up. The Country drop down list is populated by data from database using the following PHP code:
<div class="form-group required">
<label class="control-label col-md-4 requiredField">Country<span class="asteriskField">*</span> </label>
<div class="controls col-md-6">
<?php
$stmt = $country->readCountry();
$num = $stmt->rowCount();
if($num>0){
echo "<select name='country' id='country-list' class='form-control style='margin-bottom: 10px'>";
echo "<option value='0'>Select Country...</option>";
while($row = $stmt->fetch(PDO::FETCH_ASSOC)){
extract($row);
echo '<option value="'.$row["country_name"].'"data-country_id="'.$row["country_id"].'">'.$row["country_name"].'</option>';
}
echo "</select>";
}
?>
</div>
</div>
<div class="form-group required">
<label class="control-label col-md-4 requiredField">State<span class="asteriskField">*</span> </label>
<div class="controls col-md-6">
<select name='state' id='state-list' class='form-control' style='margin-bottom: 10px'>
<option value='0'>Select State</option>
</select>
</div>
</div>
<div class="form-group required">
<label class="control-label col-md-4 requiredField">City<span class="asteriskField">*</span> </label>
<div class="controls col-md-6">
<select name='city' id='city-list' class='form-control' style='margin-bottom: 10px'>
<option value="0">Select City</option>
</select>
</div>
</div>
The other two drop down list is also populated by data from MySQL database, but this time using the following jQuery code:
<script>
$(document).ready(function(){
$("#country-list").change(function(){
var country_id=$(this).find(':selected').data('country_id');
var json_url="state_json.php?country_id=" + country_id;
jQuery.getJSON(json_url, function(data){
$("#state-list").html("");
$("#state-list").append("<option value='0'>Select State</option>");
$("#city-list").html("");
$("#city-list").append("<option value='0'>Select City</option>");
jQuery.each(data, function(key, val){
$("#state-list").append('<option value="' + val.state_name + '"data-state_id="' + val.state_id + ' ">' + val.state_name + '</option>')
});
});
});
$("#state-list").change(function(){
var state_id=$(this).find(':selected').data('state_id');
var json_url="city_json.php?city_id=" + city_id;
jQuery.getJSON(json_url, function(data){
$("#city-list").html("");
$("#city-list").append("<option value='0'>Select City</option>");
jQuery.each(data, function(key, val){
$("#city-list").append("<option value='" + val.city_name + "'>" + val.city_name + "</option>")
});
});
});
});
</script>
The above code, though not perfect, works for me.
Now, the problem is with editData.php. Supposed I added new record on database with the data I collected from addData.php and I wanted to update or edit that data using edit.php. In editData.php there is also three drop down list similar to addData.php. The first problem is I cannot make it work similar to addData.php i.e. dependent, dynamic and populated with data from database. Second I wanted to pre-populate the drop down list with the data from previously added data using addData.php. In the first drop down list which is the Country I am able to make it work using the code below:
<div class="form-group required input-group">
<label class="control-label col-md-4 requiredField">Country<span class="asteriskField">*</span> </label>
<div class="controls col-md-6">
<?php
$stmt = $country->readCountry();
$num = $stmt->rowCount();
if($num>0){
?>
<select name="country" id="country-list" class="form-control" style='margin-bottom: 10px'>
<option value='0'>Select Country...</option>
<?php while($row = $stmt->fetch(PDO::FETCH_ASSOC)){
extract($row); ?>
<option value="<?php echo $row['country_name'];?>" data-country_id="<?php $row['country_id'];?>"
<?php
if($record->country==$row['country_name']) echo 'selected';?>>
<?php echo $row["country_name"];?> </option>
<?php } ?>
</select>
<?php } ?>
</div>
This it what the state_json.php looks like.. similar to city_json.php.
<?php
header("Access-Control-Allow-Methods: GET");
header('Content-Type: application/json');
$country_id=isset($_GET['country_id']) ? $_GET['country_id'] : die('Country ID not found.');
include_once 'config/database.php';
include_once 'objects/state.php';
$database = new Database();
$db = $database->getConnection();
$state = new State($db);
$state->country_id=$country_id;
$stmt = $state->readState();
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
echo json_encode($results);
?>
And this is what state.php looks like
<?php
class State{
private $conn;
private $table_name = "state_table";
public $state_id;
public $country_id;
public $state_name;
public function __construct($db){
$this->conn = $db;
}
public function readState(){
$query = "SELECT state_id, country_id, state_name
FROM " . $this->table_name . "
WHERE country_id=:country_id
ORDER BY state_name";
$stmt = $this->conn->prepare($query);
$this->country_id=htmlspecialchars(strip_tags($this->country_id));
$stmt->bindParam(":country_id", $this->country_id);
$stmt->execute();
return $stmt;
}
}
?>
Any help would be appreciated.
You have the country_id, state_id and city_id
Not sure if this line is correct as you are passing city_id to api
var state_id=$(this).find(':selected').data('state_id');
var json_url="city_json.php?city_id=" + city_id;
In edit page load your php state_id and city_id to js as the following
<script>
var state_id = <?php echo $state_id ; ?>
var city_id= <?php echo $city_id; ?>
</script>
Then call your api when JavaScript is loaded and if state_id = your state_id make it selected
if(data-state_id == state_id){
$("#state-list").append('<option value="' + val.state_name + '"data-state_id="' + val.state_id + ' " selected>' + val.state_name + '</option>');
}
else
{
$("#state-list").append('<option value="' + val.state_name + '"data-state_id="' + val.state_id + ' ">' + val.state_name + '</option>');
}

Save values of multiple text boxes using jquery and mysql

How to insert dynamically generated field values to backend using mysql.
Im trying to add rows with text box and drop down using jquery and auto saving
the field values at regular intervals.
So i need to fetch the ids of the textboxes and drop down, but currently i get the id of only the first text box and drop down.
$(function() {
$("#btnAdd").bind("click", function() {
AddControl();
});
$("#btnGet").bind("click", function() {
var values = "";
$("input[name=DynamicTextBox]").each(function() {
values += $(this).val() + "\n";
});
alert(values);
});
$("body").on("click", ".remove", function() {
$(this).closest("div").remove();
var i = 1;
var Ids = [];
$('[id*=ddl]').each(function() {
$(this).attr("id", "ddl" + i);
Ids.push(i);
i++;
});
$('[id*=hfDDLId]').val(parseInt($('[id*=hfDDLId]').val()) - 1);
var resultIds = Ids.join(',');
$('[id*=hfDropDownIds]').val(resultIds);
});
});
function AddControl() {
var Id = parseInt($('[id*=hfDDLId]').val()) + 1;
var ddlId = "ddl" + (Id);
var div = $("<div />");
div.html(getDropDownList(ddlId, ddlId));
div.append(GetDynamicTextBox(''));
$("#TextBoxContainer").append(div);
$('[id*=hfDDLId]').val(Id);
var previousDropDownId = $('[id*=hfDropDownIds]').val();
if (previousDropDownId != '') {
$('[id*=hfDropDownIds]').val(previousDropDownId + ',' + Id);
} else {
$('[id*=hfDropDownIds]').val(Id);
}
return false;
}
function getDropDownList(name, id) {
var combo = $("<select></select>").attr("id", id).attr("name", name).attr("runat", "server").attr("class", "class").attr("required", "required");
combo.append("<option value=" + "" + ">" + "Select Category" + "</option>");
combo.append("<option value=" + "1" + ">" + "1" + "</option>");
combo.append("<option value=" + "2" + ">" + "2" + "</option>");
combo.append("<option value=" + "3" + ">" + "3" + "</option>");
return combo;
}
function GetDynamicTextBox(value) {
return '<input name = "DynamicTextBox" id="ingr_name" type="text" value = "' + value + '" required/>&nbsp' + '<input name = "DynamicTextBox" type="text" value="' + value + '" required/>&nbsp' + '<input type="button" value="Remove" class="remove" />'
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="form1" runat="server">
<div>
<input id="btnAdd" type="button" value="Add" />
<br/>
<br/>
<div id="TextBoxContainer">
<!--Textboxes will be added here -->
</div>
<br/>
<input type="hidden" id="hfSelectedValue" runat="server" />
<input type="hidden" id="hfDropDownIds" value="" runat="server" />
<input id="btnGet" type="button" value="Get Values" />
<input type="hidden" id="hfDDLId" value="0" />
</div>
</form>
Code for inserting in the backend
Assunimg i have given the id for the text box as 'ingr_name' im posting the same as :
<?php
$con=mysqli_connect("localhost","root","pass","DB");
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
if (isset($_POST['txt_area']) && $_POST['txt_area'] != '') {
$ingr_name = mysqli_real_escape_string($con,$_POST['ingr_name']);
$qry = "Select count(*) as cnt from table";
$res = mysqli_query($con,$qry);
$row = mysqli_fetch_array($res);
if ($row['cnt'] == 0) {
$qry_ins = 'my insert query';
}
?>
#SachinSachin if you want to insert only one text box value try the below code
function insert_data(){
var url = "insert.php";
$.ajax({
url : url,
type: "POST",
data: $('#formid').serialize(),
success: function(data)
{
alert(data);
}
});
}
call this function on submit button and in insert.php you get the values using post method as usual and insert them in mysql. if it is success print echo "inserted"; else print echo "failed"; you will get this status in alert message in above insert_data() function. Here i assumed you are using php as backend if not use your language with same process.

Categories