Fetch data from msql into selectpickers for editing - javascript

I have a code which inserts data from a modal form into two related tables, namely inventory_order table and inventory_order_product table. That code is working fine but my problem comes when I want to fetch the same data back into the modal form for editing. The code for fetch single is only retrieving data for the first line in the selectpicker while the remaining are not retrieved. Please if my question is not clear refer to the image below and please bear with me I'm a novice in php, ajax and mysql.
$(document).on('click', '.update', function(){
var inventory_order_id = $(this).attr("id");
var btn_action = 'fetch_single';
$.ajax({
url:"order_action.php",
method:"POST",
data:{inventory_order_id:inventory_order_id, btn_action:btn_action},
dataType:"json",
success:function(data)
{
$('#orderModal').modal('show');
$('#inventory_order_name').val(data.inventory_order_name);
$('#inventory_order_date').val(data.inventory_order_date);
$('#inventory_order_address').val(data.inventory_order_address);
$('#span_product_details').html(data.product_details);
$('#payment_status').val(data.payment_status);
$('.modal-title').html("<i class='fa fa-pencil-square-o'></i> Edit Order");
$('#inventory_order_id').val(inventory_order_id);
$('#action').val('Edit');
$('#btn_action').val('Edit');
}
})
});
if($_POST['btn_action'] == 'fetch_single')
{
$query = "
SELECT * FROM inventory_order WHERE inventory_order_id = :inventory_order_id
";
$statement = $connect->prepare($query);
$statement->execute(
array(
':inventory_order_id' => $_POST["inventory_order_id"]
)
);
$result = $statement->fetchAll();
$output = array();
foreach($result as $row)
{
$output['inventory_order_name'] = $row['inventory_order_name'];
$output['inventory_order_date'] = $row['inventory_order_date'];
$output['inventory_order_address'] = $row['inventory_order_address'];
$output['payment_status'] = $row['payment_status'];
}
$sub_query = "
SELECT * FROM inventory_order_product
WHERE inventory_order_id = '".$_POST["inventory_order_id"]."'
";
$statement = $connect->prepare($sub_query);
$statement->execute();
$sub_result = $statement->fetchAll();
$product_details = '';
$count = '';
$count = $count++;
foreach($sub_result as $sub_row)
{
$product_details .= '
<script>
$(document).ready(function(){
$("#product_id'.$count.'").selectpicker("val", '.$sub_row["product_id"].');
$(".selectpicker").selectpicker();
});
</script>
<span id="row'.$count.'">
<div class="row">
<div class="col-md-8">
<select name="product_id[]" id="product_id'.$count.'" class="form-control selectpicker" data-live-search="true" required>
'.fill_product_list($connect).'
</select>
<input type="hidden" name="hidden_product_id[]" value="'.$sub_row["product_id"].'" />
</div>
<div class="col-md-3">
<input type="text" name="quantity[]" class="form-control" value="'.$sub_row["quantity"].'" required />
</div>
<div class="col-md-1">
';
if($count == '')
{
$product_details .= '<button type="button" name="add_more" id="add_more" class="btn btn-success btn-xs">+</button>';
}
else
{
$product_details .= '<button type="button" name="remove" id="'.$count.'" class="btn btn-danger btn-xs remove">-</button>';
}
$product_details .= '
</div>
</div>
</div><br />
</span>
';
}
$output['product_details'] = $product_details;
echo json_encode($output);
}

Problem in your code is with variable $count.As in your backend code this is declare outside your foreach.. loop so when first time your loop will run it will have correct value i.e : 0 but you never increment it that's why it is only giving correct value for first selectpicker. Instead you need to increment its value to set value for second value ,third and so on. i.e :
foreach($sub_result as $sub_row)
{
//you code html and jquery
$count = $count++;//add this inside for loop
}
Also, i don't why you have given $count = ''; . Instead , it should be $count = 0;

Related

Need help creating add rows function with MySQL dependent dropdowns

Single Hardware Modification
Mulitple Hardware Modifications
I am trying to set up an equipment log using MySQL, PHP, and JavaScript. I have been trying to teach myself over the past 3 months. A lot of what I have is from code I have found here or on other forums.
I have a page dedicated to inputting hardware changes on our equipment. The Subsystem and Component dropdowns are set to pull the subsystem list from the database, and the component list is populated based off subsystem selection. I have not gotten that far into JavaScript, so I do not fully understand some of what this code means.
I have the page set up to input one modification, then after submitting, there is a link to return to the page to add another modification. This option is working as expected. My dropdowns work and my data is input into my database as expected.
I am trying to set up a page so that if there are multiple modifications, they can be added on one page. All of my text input fields on the form work as expected. I am able to create the first dropdown for the subsystem and populate it with my table data, but the component dropdown does not populate. I have been following this tutorial from webslesson.com. In it he uses 1 table. I have been trying to adapt it for the 2 tables that I am using, but I am getting some of the functions wrong.
Would anyone be able to point me in the right direction of where I can learn where my code is going off track? I am trying to learn, but at this point I am not exactly sure how to phrase what I am looking for.
I appreciate you taking a look at this. Please do not be too harsh on my poor code. I am working to make it better as I learn.
Above are links to my CodePen.io and repl.it for the 2 versions of my page. I had to
This is my table setup:
lu_subsystem
|id|subsystem_name|
|--|--------------|
lu_component
|component_id|subsystem_id|component_name|
|------------|------------|--------------|
<?php
//index.php
include('database_connection.php');
?>
<!DOCTYPE html>
<html>
<head>
<title>Add Remove Dynamic Dependent Select Box using Ajax jQuery with PHP</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<br />
<div class="container">
<h3 align="center">Add Remove Dynamic Dependent Select Box using Ajax jQuery with PHP</h3>
<br />
<h4 align="center">Enter Item Details</h4>
<br />
<form method="post" id="insert_form">
<div class="table-responsive">
<span id="error"></span>
<table class="table table-bordered" id="item_table">
<thead>
<tr>
<th>Enter Item Name</th>
<th>Subsystem</th>
<th>Component</th>
<th><button type="button" name="add" class="btn btn-success btn-xs add"><span class="glyphicon glyphicon-plus"></span></button></th>
</tr>
</thead>
<tbody></tbody>
</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(){
var count = 0;
$(document).on('click', '.add', function(){
count++;
var html = '';
html += '<tr>';
html += '<td><input type="text" name="item_name[]" class="form-control item_name" /></td>';
html += '<td><select name="subsystem_id[]" class="form-control subsystem_id" data-subsystem_id="'+count+'"><option value="">Select Subsystem</option><?php echo fill_select_box($connect, "0"); ?></select></td>';
html += '<td><select name="item_component_id[]" class="form-control item_component_id" id="item_component_id'+count+'"><option value="">Select Component</option></select></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', '.subsystem_id', function(){
var id = $(this).val();
var component_id = $(this).data('component_id');
$.ajax({
url:"fill_sub_category.php",
method:"POST",
data:{subsystem_id:subsystem_id},
success:function(data)
{
var html = '<option value="">Select Component</option>';
html += data;
$('#item_component_id'+component_id).html(html);
}
})
});
$('#insert_form').on('submit', function(event){
event.preventDefault();
var error = '';
$('.item_name').each(function(){
var count = 1;
if($(this).val() == '')
{
error += '<p>Enter Item name at '+count+' Row</p>';
return false;
}
count = count + 1;
});
$('.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_component_id').each(function(){
var count = 1;
if($(this).val() == '')
{
error += '<p>Select Item Sub category '+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>');
}
});
});
</script>
<?php
//database_connection.php
$connect = new PDO("mysql:host=localhost; dbname=bunker_logs;", "root", "");
function fill_select_box($connect, $id)
{
$query = "
SELECT * FROM lu_subsystem
";
$statement = $connect->prepare($query);
$statement->execute();
$result = $statement->fetchAll();
$output = '';
foreach($result as $row)
{
$output .= '<option value="'.$row["id"].'">'.$row["subsystem_name"].'</option>';
}
return $output;
}
function fill_component_box($connect, $component_id)
{
$query = "
SELECT * FROM lu_component
WHERE component_id ='".$id."'
";
$statement = $connect->prepare($query);
$statement->execute();
$result = $statement->fetchAll();
$output = '';
foreach($result as $row)
{
$output .= '<option value="'.$row["component_id"].'">'.$row["component_name"].'</option>';
}
return $output;
}
?>
<?php
//fill_component.php
include('database_connection.php');
echo fill_component_box($connect, $_POST["subsystem_id"]);
?>
I have been looking into your code, and to be honest, I haven't done much in jQuery. However, I still want to give you an example on how you can implement the information on your page from my experience:
You can either pull the information directly from the database with PHP without using JavaScript. If you use PDO for this, you get a muldimension array.
You can then "walk" through the array with a foreach loop
$select ='<select id='yourChoice'>';
foreach($array as $component){
$name = component['name'];
$select.="<option value='$name'> $name </option>;
};
$select.='</select>';
In this case the $array is the full printout from the database, and goes through each row ( $component)
It then selects the column name, and fills it in.
If you want to do the same thing with JavaScript, you can do it with JSON, walking through that array.
Unfortunately, I don't have an example ready for that one at the moment.

How to delete a complete row on button click in javascript?

I have a html/php code as shown below. The below html/php code is working in a way that on adding rows, we can select date from every row and can save it as well.
Two things need to be done.
On clicking Delete button, it should remove the value from the JSON array because everything is pulled from the JSON after saving the form.
Also, on clicking Delete button it should delete the complete row from the DOM.
you should give each added row an id corresponding to its rank:
row.id=i.toString();
then use the following code to remove the row:
var row = document.getElementById(rowrankid);
row.parentNode.removeChild(row);
I have prepared a code sample for you using your example that does exactly what you say.
It is using a javascript fetch post request to post to the script you have provided to remove the dom elements and update the json file.
I have changed some of your paths slightly so you will need to change those back (add in the ../feeds/ parent directory)
Once the user has pressed the button the page will reload, showing the updated interface that is loaded from the json file.
There are some improvements that could be made, for example the javascript is not checking to make sure the request was successful before reloading, but as the input is date select it should be ok.
<?php
if(file_exists('./ptp-ess_landing_house.json')){
$data = json_decode(file_get_contents('./ptp-ess_landing_house.json'));
}
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$_POST = json_decode(file_get_contents('php://input'), true);
if(isset($_POST['requestType']) && in_array($_POST['requestType'], ['remove'])) {
switch ($_POST['requestType']) {
case 'remove' :
//Unset the values
unset($data->row_delete[$_POST['data'] -1]);
unset($data->house_sitting_date[$_POST['data'] -1]);
//We are reindexing the arrays as we have deleted some rows, note that we are using +1 array indexes
$data->row_delete = array_values($data->row_delete);
$data->house_sitting_date = array_values($data->house_sitting_date);
foreach($data->row_delete as $key=>$value) {
$data->row_delete[$key] = strval($key+1);
}
//Write the file back
$fp = fopen('./ptp-ess_landing_house.json', 'w');
fwrite($fp, json_encode($data));
fclose($fp);
header("HTTP/1.1 200 OK");
echo 'ok';
die;
break;
default:
}
}
}
?>
<script>
function rowDelete(row) {
//Make a request to your entry file (index.php here) to do the removal
fetch('/index.php', {
method: 'post',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({requestType: 'remove', data: row})
}).then(function(response) {
location.reload();
return response;
});
}
</script>
<?php if($data) { ?>
<form method="post">
<div id="rows" style="display:flex; justify-content: center;"><!-- Big div START -->
<!-- Remove Button START -->
<div class="rows-delete">
<h4 style="text-align:center;">Delete Rows</h4>
<?php if (empty($data->row_delete)) { ?>
<div class="row-delete" style="margin-right:30px; margin-top:22.5px;">
<button type="button" id="delete" onclick="rowDelete()">Remove</button>
<input type="hidden" name="row_delete[]" value="1" />
</div>
<?php } else { ?>
<?php foreach ($data->row_delete as $row_delete){ ?>
<div class="row-delete" style="margin-right:30px; margin-top:22.5px;">
<button id="delete" type="button" onclick="rowDelete(<?php echo $row_delete;?>)">Remove</button>
<input type="hidden" name="row_delete[]" value="<?php echo $row_delete;?>" />
</div>
<?php }} ?>
</div>
<!-- Remove Button END -->
<!-- Sitting Date START -->
<div class="sitting-days">
<h4 style="text-align:center;">Select Date</h4>
<?php if (empty($data->house_sitting_date)) { ?>
<!-- Select Date START -->
<div class="select-date" style="margin-right:30px; margin-top:20px;">
<input type="date" class="house-sitting-date" name="house_sitting_date[]" value="">
</div>
<?php } else { ?>
<?php foreach ($data->house_sitting_date as $date){ ?>
<!-- Select Date START -->
<div class="select-date" style="margin-right:30px; margin-top:20px;">
<input type="date" class="house-sitting-date" name="house_sitting_date[]" value="<?php if($date) {echo $date;}?>">
</div>
<!-- Select Date END -->
<?php }} ?>
</div>
<!-- Sitting Date END -->
</div><!-- Big div END -->
</form>
<?php } else {
echo 'Cannot read JSON settings file';
}
?>
If your json is known at the front-end (which I think you are implying, since your rowDelete is a JS-function), you can pass this with the call to rowDelete. Then you can traverse the DOM to get to value the corresponding sibling input-field (perhaps something like this.parentNode.childNodes[1]).
Once you have that value, you can easily remove it from the corrsponding array in your json:
let d = '2020-01-30'
let idx = arr.indexOf(d)
let newdates = ([...arr.slice(0,idx), ...arr.slice(idx+1)])
data.house_sitting_date = newdates
(with some additional index bounds checking, of course).
After that, you can perform a similar DOM traversal to remove the corresponding element from the DOM.
Flash, unfortunately, the desing of the code itself is not much professional... there are separate loops for rows (in php), which instead should be only 1 loop, like (with example simple Javascript binding on click):
<?php
for ($i=0; $i<count($data["house_sitting_date"]); $i++)
{
echo '<div class="remove"><a id="'.$data["row_delete"][$i].'" onclick="deleteRow(this);">Remove</a></div>';
echo '<div class="date">....</div>';
...
}
?>
<script> function deleteRow(el) { el.remove(); } </script>
also, lots of embedded style="".. codes, instead you might use 1 style file.
This is how I did in past, and it works perfectly
Prerequisite for this answer to work is each button and input field should be in DIV with unique id and there should be container for all these div in my case its .
On Add button(if you have one) you need clone node, and paste it under or above the element where it was clicked,
// Create a clone of element with id ddl_1:
let clone = document.querySelector('#row'+rownumber).cloneNode( true );
// Append the newly created element on element p
document.querySelector('p').appendChild( clone );
Then every time you add a new row or delete a row you need to append ids on these row, to do this you would a common class for all these rows in my case I used, rows
function changeids()
{
let rows =document.getElementsByClassName('rows');
for(let i=0; i<rows.length; i++)
{
let thisid="row"+i;
rows[i].setAttribute("id", thisid);
let thisAddButton = rows[i].getElementsByClassName("add")[0];
let thisDeleteButton = rows[i].getElementsByClassName("delete")[0];
let onclickaddfunction = "addrow("+i+")";
thisAddButton.setAttribute("onclick", onclickaddfunction);
let onclickDeletefunction = "removerow("+i+")";
thisDeleteButton.setAttribute("onclick", onclickDeletefunction);
}
}
Then when you remove you need to remove node and call changeids again
function removerow(rownumber){
document.getElementById('row'+rownumber).remove();
changeids();
}
This would give you whole working idea of add and delete rows, whole code below please ignore my messy code, just did it to give you and idea
<p>
<div id="row1" class="rows">
<button class="add" onclick="addrow(1)">add</button>
<button class="delete" onclick="removerow(1)"> remove </button>
<input type="text">
</div>
</p>
<script>
function addrow(rownumber)
{
// Create a clone of element with id ddl_1:
let clone = document.querySelector('#row'+rownumber).cloneNode( true );
// Append the newly created element on element p
document.querySelector('p').appendChild( clone );
changeids();
}
function removerow(rownumber)
{
document.getElementById('row'+rownumber).remove();
changeids();
}
function changeids()
{
let rows =document.getElementsByClassName('rows')
for(let i=0; i<rows.length; i++)
{
let thisid="row"+i;
rows[i].setAttribute("id", thisid);
let thisAddButton = rows[i].getElementsByClassName("add")[0];
let thisDeleteButton = rows[i].getElementsByClassName("delete")[0];
let onclickaddfunction = "addrow("+i+")";
thisAddButton.setAttribute("onclick", onclickaddfunction);
let onclickDeletefunction = "removerow("+i+")";
thisDeleteButton.setAttribute("onclick", onclickDeletefunction);
}
}
</script>
To delete row from dom, you have to specify unique id for main element of row and you can use [ElementObject].remove() method to delete, So everything inside that will be removed.
Also You should simplify and change JSON data, so that it will delete from json also using ajax with using single id(key) as parameter.
Here is the working code:
<?php
if (!empty($_GET)) {
if (!empty($_GET['action']) && $_GET['action'] == 'delete') {
if(file_exists('ptp-ess_landing_house.json')) {
$data = json_decode(file_get_contents('ptp-ess_landing_house.json'), true);
if (!empty($_GET['row_number'])) {
unset($data[$_GET['row_number']]);
$fp = fopen('ptp-ess_landing_house.json', 'w');
fwrite($fp, json_encode($data));
fclose($fp);
echo 1;
exit;
}
}
echo 0;
exit;
}
}
if (!empty($_POST)) {
$output = array();
if (!empty($_POST['row_item'])) {
$output = $_POST['row_item'];
}
$fp = fopen('ptp-ess_landing_house.json', 'w');
fwrite($fp, json_encode($output));
fclose($fp);
}
$data = array();
if(file_exists('ptp-ess_landing_house.json')) {
$data = json_decode(file_get_contents('ptp-ess_landing_house.json'), true);
}
?><form method="post">
<!-- Add New Row Button START -->
<div class="plus-minus-button" style="text-align:center;">
<button type="button" id="addRow" onclick="rowAdd()">+</button>
</div>
<!-- Add New Row Button END -->
<div id="maindiv">
<div style="display:flex; justify-content: center;">
<div class="rows-delete" style="text-align:center;">
<div class="row-delete" style="margin-right:30px;">
<h4 style="text-align:center;">Delete Rows</h4>
</div>
</div>
<div class="sitting-days" style="text-align:center;">
<div class="select-date" style="margin-right:30px;">
<h4 style="text-align:center;">Select Date</h4>
</div>
</div>
<div class="choose-options" style="text-align:center;">
<div class="yes-no-option" style="display:inline-grid;">
<h4 style="text-align:center;">Yes/No</h4>
</div>
</div>
</div>
<!-- Big div START --><?php
$totalrow = 0;
foreach ($data AS $key => $row) {
?><div id="row-<?php echo $key; ?>" style="display:flex; justify-content: center; margin-top:20px;"><?php
?><div class="rows-delete" style="text-align:center;">
<div class="row-delete" style="margin-right:30px;">
<button type="button" class="delete" onClick="delete_row(this.value)" value="<?php echo $key; ?>">Remove</button>
<input type="hidden" name="row_item[<?php echo $key; ?>][row_delete]" value="<?php echo $row['row_delete'];?>" />
</div>
</div>
<!-- Remove Button END -->
<!-- This is what I have tried to add a button (END) -->
<!-- Sitting Date START -->
<div class="sitting-days" style="text-align:center;">
<div class="select-date" style="margin-right:30px;">
<input type="date" class="house-sitting-date" name="row_item[<?php echo $key; ?>][house_sitting_date]" value="<?php echo $row['house_sitting_date']; ?>">
</div>
</div>
<!-- Sitting Date END -->
<!-- YES/NO START --><?php
?><div class="choose-options">
<div class="yes-no-option" style="display:inline-grid;">
<select name="row_item[<?php echo $key; ?>][house_sitting_date_yes_no]" class="house-yes-no" style="height:24px; ">
<option value="<?php echo $row['house_sitting_date_yes_no']; ?>" <?php if($row['house_sitting_date_yes_no'] == "nada" ) echo "selected";?>>Please choose an option</option>
<option value="<?php echo $row['house_sitting_date_yes_no']; ?>" <?php if($row['house_sitting_date_yes_no'] == "yes" ) echo "selected";?>>Yes</option>
<option value="<?php echo $row['house_sitting_date_yes_no']; ?>" <?php if($row['house_sitting_date_yes_no'] == "no" ) echo "selected";?>>No</option>
</select>
</div>
</div>
<!-- YES/NO END -->
</div><?php
if ($key > $totalrow) $totalrow = $key;
else $totalrow++;
}
?>
<input type="hidden" name="totalrow" id="totalrow" value="<?php echo $totalrow; ?>">
</div>
<!-- Big div END -->
<hr />
<div style="text-align:center;">
<input type="submit" value="submit" />
</div>
</form>
<script>
function delete_row(row_number) {
var data = '<?php echo json_encode($data) ?>';
data = JSON.parse(data);
if (typeof(data[row_number]) != undefined) {
var request = new XMLHttpRequest();
request.open("GET", "index.php?action=delete&row_number=" + row_number);
request.onreadystatechange = function() {
if (this.readyState === 4 && this.status === 200) {
var row = document.getElementById('row-'+row_number);
row.remove();
}
}
request.send();
}
else {
var row = document.getElementById('row-'+row_number);
row.remove();
}
}
function rowAdd(event) {
var totalrow = document.getElementById("totalrow").value;
totalrow = parseInt(totalrow) + 1;
document.getElementById("maindiv").insertAdjacentHTML('beforeend', newRow(totalrow));
document.getElementById("totalrow").value = totalrow;
}
function newRow(row_number) {
return `<div id="row-` + row_number + `" class="sitting-days" style="display:flex; justify-content:center; margin-top:20px;">
<div class="rows-delete" style="text-align:center;">
<div class="row-delete" style="margin-right:30px;">
<button type="button" class="delete" onClick="delete_row(this.value)" value="` + row_number + `">Remove</button>
<input type="hidden" name="row_item[` + row_number + `][row_delete]" value="` + row_number + `" />
</div>
</div>
<div class="sitting-days" style="text-align:center;">
<div class="select-date" style="margin-right:30px;">
<input type="date" class="house-sitting-date" name="row_item[` + row_number + `][house_sitting_date]" value="">
</div>
</div>
<div class="choose-options">
<div class="yes-no-option" style="display:inline-grid;">
<select name="row_item[` + row_number + `][house_sitting_date_yes_no]" class="house-yes-no" style="height:24px; ">
<option value="nada">Please choose an option</option>
<option value="yes">Yes</option>
<option value="no">No</option>
</select>
</div>
</div>
</div>`;
}
</script>

How to Take value from buttons with same class Using JQuery

I have a PHP script which Produces the n number of buttons as an output based on database records. Each value is associated with a respective button.
When I click any button, I always get the value of first button.
How can I get the value of button which is clicked only?
<button class='btn btn-danger question_delete' value=".$row['action_id']."</button>
My jQuery script:
$(document).ready(function(){
$(".question_delete").click(function(){
var action_value = $(this).val();
if(action_value){
$.ajax({
type:'POST',
url:'delete_question_group.php',
data:{delete_action:action_value},
success:function(data){
refresh_table();
refresh_paper();
}
});
}else{
// $('#select_qtype_list').html('<option value="">Select Question First</option>');
}
});
});
My PHP:
<?php
session_start();
$name =$_SESSION['name'];
$id = $_SESSION['id'];
include("database.php");
$run = mysqli_query($conn,"select * from users where id='$id' AND name='$name' ");
$user = mysqli_fetch_array($run);
$subject_id = $user['subject_id'];
$user_name = $user['name'];
$run1 = mysqli_query($conn,"select * from subject where sub_id='$subject_id'");
$subject = mysqli_fetch_array($run1);
$subject_name = $subject['sub_name'];
$query = $conn->query("select * from action where subject_id='$subject_id' AND user_id='$id'");
//Count total number of rows
$rowCounts = $query->num_rows;
//Display states list
if($rowCounts > 0){
$i=1;
while($row = $query->fetch_assoc()){
//echo '<option value="'.$row['qtype_id'].'">'.$row['qtype_name'].'</option>';
echo "<tr>";
//$q_id = $query['question_id'];
//$question_type_id = $query['question_type_id'];
echo "<td>$i</td>";
echo "<td>".$row['action_name']."</td>";
echo "
<td>
<button class='btn btn-danger question_delete' value=".$row['action_id'].">
<i class='fa fa-trash' aria-hidden='true'>
</i>
</button>
</td>
<td>
<button id='question_update' class='btn btn-primary' data-toggle='modal' data-target='#myModal_update' value=".$row['action_id'].">
<i class='fa fa-pencil' aria-hidden='true' >
</i>
</button>
</td>
</tr>
";
$i++;
}
}else{
echo '<td colspan="4" style="text-align: center; color:red;"><strong>No Questions are Selected</string></option>';
}
?>
Probably because the property action_id inside the value on each button don't change. Also you forgot to close the button tag, maybe that's why it doesn't work
<button class='btn btn-danger question_delete' value=".$row['action_id']."></button>
-This Problem is Solved and Worked Perfectly. Description of solution is as follow:
-First onclick attribute is used. and a function is created which takes the value of button each time when button will click.
Following Code is worked:
<button class='btn btn-danger' onclick='myfunction(this.value)' id='question_delete' value=".$row['action_id']."><i class='fa fa-trash' aria-hidden='true'></i></button>
JQuery Code:
$(document).ready(function(){
myfunction1 = function(e){
if(e){
$.ajax({
type:'POST',
url:'update_question_group.php',
data:{update_action:e},
success:function(html){
$('#update_action_list').html(html);
$('#update_action_list').selectpicker('refresh');
}
});
}else{
// $('#select_qtype_list').html('<option value="">Select Question First</option>');
}
}
});

automatically populate text box based on select entry

Is there a way within php to get a value picked up from database automatically?
Basically, If I have a select box & I select option "Laptop-01" , is there a way within PHP to check the database for that row and then automatically pick up the serial number of Laptop-01 and populate it within the text box for the devices serial number.
At the moment I've just got two text boxes and user would need to manually enter both the product number (Laptop-01) & then the serial number.
I've currently got the following code;
PHP
<?php
$selectquery = "SELECT * FROM `loanproducts`";
$selectresult = mysqli_query($connection, $selectquery);
$selectusersquery = "SELECT * FROM `loanusers`";
$selectusersresult = mysqli_query($connection, $selectusersquery);
if (isset($_POST['editloan'])):
$loanid = $_POST["loanid"];
$username = $_POST["username"];
$product=$_POST["product"];
$product_desc=$_POST["product_desc"];
$serial=$_POST["serial"];
$date_collected=$_POST["date_collected"];
$date_return = $_POST["date_return"];
$returned = $_POST["returned"];
$edit_query="UPDATE loans SET
username = '$username',
product = '$product',
product_desc = '$product_desc',
serial = '$serial',
date_collected ='$date_collected',
date_return = '$date_return',
returned = '$returned'
WHERE loanid ='$loanid'";
$edit_result= mysqli_query($connection, $edit_query);
if ($edit_result) :
header ('location: editloan.php?confirm=Loan successfully updated');
else :
echo "<b>This didn`t work, error: </b>";
echo mysqli_error($connection);
endif;
endif;
$loanid=$_GET['loanid'];
$my_query="select * from loans where loanid=$loanid";
$result= mysqli_query($connection, $my_query);
while ($myrow = mysqli_fetch_array($result)):
$username = $myrow["username"];
$product = $myrow["product"];
$product_desc = $myrow["product_desc"];
$serial = $myrow["serial"];
$date_collected=$myrow["date_collected"];
$date_return=$myrow["date_return"];
$returned=$myrow["returned"];
endwhile;
?>
HTML
<html>
<h2 align="center">Edit Product Form</h2>
<body>
<div id="loginp"<p align="center">Edit this loan for the Coleg Sir Gar Loan System</p></div>
<form method="POST" action="editloaninfo.php">
<div id="editp"><p align="center">
<label class="labelform">Username:</label><select name="username" style="width: 150px">
<?php while($row1 = mysqli_fetch_array($selectusersresult))
{ if ( $row1[1] == $username )
$selected = "selected";
else $selected = "";
echo "<option $selected>{$row1[1]}</option>";
}?>
</select></p></div>
<div id="editp"><p align="center">
<label class="labelform">Product:</label><select name="product" style="width: 150px">
<?php while($row1 = mysqli_fetch_array($selectresult))
{ if ( $row1[1] == $product )
$selected = "selected";
else $selected = "";
echo "<option $selected>{$row1[1]}</option>";
}?>
</select></p></div>
<div id="editp"><p align="center">
<label class="labelform">Product Description:</label><input class="inputform" type="text" name="product_desc" placeholder="Product Description..." autocomplete="off" required size="18" value="<?php echo $product_desc; ?>"></p></div>
<div id="editp"><p align="center">
<label class="labelform">Serial Number:</label><input class="inputform" type="text" name="serial" placeholder="Serial Number..." autocomplete="off" required size="18" value="<?php echo $serial; ?>"></p></div>
<div id="editp"><p align="center">
<label class="labelform">Date Collected:</label><input class="inputform" type="date" name="date_collected" autocomplete="off" size="30" value="<?php echo $date_collected; ?>"></p></div>
<div id="editp"><p align="center">
<label class="labelform">Date Returned:</label><input class="inputform" type="date" name="date_return" autocomplete="off" size="30" value="<?php echo $date_return; ?>"></p></div>
<div id="editp"><p align="center">
<label class="labelform">Returned:</label><select name="returned" style="width: 150px">
<option value="Yes" <?php echo $returned === 'Yes' ? 'selected="selected"' : '' ?>>Yes</option>
<option value="No" <?php echo $returned === 'No' ? 'selected="selected"' : '' ?>>No</option>
</select></p></div>
<br>
<input type="hidden" name=loanid value= "<?php echo $loanid; ?>" >
<div id="editp"><input class="inputform" type="submit" name="editloan" value="Save Changes">
<input class="inputform" type="button" name="Cancel" value="Cancel" onClick="window.location.href='editloan.php'"></div>
</form>
</body>
</html>
</div>
Basically you want to do is :
When User select 'Laptop-01' you page must update all INPUTS with information related to user's laptop (like Serial number).This can be done by adding AJAX
Please note : This answer will give you idea about how to Populate data from data base then you can do this for any information you needed.
<form>
<select id='product_name' onchange="get_data()">
<option value='Laptop-01'>Laptop-01</option>
</select>
<input name='serial_no' id='serial_no'>
<input name='product_no' id='product_no'>
</form>
<script src="js/ajax.js"></script>
<script>
function get_data(){
//In very short what this do is :
//get values
var serial_no = document.getElementById('product_name').value;
//create an Object
var ajax = ajaxObj("POST", "yourpage.php");
ajax.onreadystatechange = function() {
if(ajaxReturn(ajax) == true) {
//ajax.responsetex is things you echo from script next to it
var index1 = ajax.responseText.split(",");
//index1 is array holding values
//index1[0]=$serial_no
//index1[1]=$product_no
//Now set value of your serian_no INPUT to $serial_no = index1[0];
document.getElementById('serial_no').value = index1[0];
document.getElementById('product_no').value = index1[1]
}
}
//ajax.send = POST/GET method
ajax.send("product_name="+product_name);
}
</script>
<?php
if(isset($_POST['product_name'])){
$sql = "SELECT serial_no,product_no FROM loanuser WHERE username='$username'";
$query = ($connection , $query);
while ($myrow = mysqli_fetch_array($query)){
$serial_no = $myrow["serial_no"];
$product_no = $myrow["product_no"];
}
//form a (,) separated list and echo it.
echo $serial_no.",".$product_no;
exit();
}
?>
Ajax.js
function ajaxObj(meth, url) {
var x = new XMLHttpRequest();
x.open(meth, url, true);
x.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
return x;
}
function ajaxReturn(x){
if(x.readyState === 4 && x.status === 200){
return true;
}
}
If you want me to add more explanation on AJAX used in this page , please add request in comment section i will edit it to more better answer

Page wise display is not working as expected

i am trying to display records as a multiples of 5, but i am getting only the first 5 records again and again.
HomePage-slideshow.php
<select multiple class="form-control " id="sel2" size="10" >
<?php
session_start();
if (isset($_SESSION["min"]) || isset($_SESSION["count"])) {
$time = (int)$_SESSION["min"];
$something = $_SESSION["something"];
$everything = $_SESSION["everything"];
}
$count = (int)$_SESSION["count"];
$select_query= "SELECT * from video_details WHERE c_something = '$something' OR c_everything = '$everything' HAVING video_min <= $time LIMIT $count,5";
$select_query_run = mysqli_query($conn,$select_query);
while ($select_query_array= mysqli_fetch_array($select_query_run) )
{
echo "<option value='".htmlspecialchars($select_query_array["video_question"])."' >".htmlspecialchars($select_query_array["video_question"])."</option>";
}
?>
</select>
<?php
$new = $count + 5;
$_SESSION["count"] = $new;
$_SESSION["min"] = $time;
$_SESSION["something"] = $something;
$_SESSION["everything"] = $everything;
//session_destroy();
?>
</div>
</div>
<div class="center">
<input type="button" class="btn btn-success font-30" value="I AM CURIOUS ABOUT THIS" />
<form id="next_page" name="next_page" method="post" action="next.php" data-ajax="false">
<input type="submit" class="btn btn-success font-30" id="next" name="next" value="LEARN SOMETHING ELSE" />
</form>
</div>
I am trying to increase the $count value when the LEARN SOMETHING ELSE button is pressed. It redirects to next.php where i try to reassign the increased value to count.
next.php
<?php
session_start();
$inc = (int)$_SESSION["count"];
$time = (int)$_SESSION["min"];
$something = $_SESSION["something"];
$everything = $_SESSION["everything"];
echo $inc;
$_SESSION["count"] = $inc;
$_SESSION["min"] = $time;
$_SESSION["something"] = $something;
$_SESSION["everything"] = $everything;
header("location: HomePage-slideshow.php#services-section");
?>
The echo statement gives 5 as output, but the query displays only the old output still. If i hardcode 5 in my query, it gives next 5 records but i am not able to dynamically change the value of $count in here.
Please help me

Categories

Resources