Set hidden field value by Javascript - javascript

How can I pass USER_ID of the tag < a > for a Javascript function Javascript that set a hidden field?
I tried the Javascript function showConfirm(), but the hidden field isn't being filled. It stays null... I think the onClick attribute, of the field deleteid, is wrote wrong.
I want fill this field by javascript. How can I?
The message of error says
You have an error in your SQL syntax; check the manual that
corresponds to your MySQL server version for the right syntax to use
near '' at line 1
probably because the hidden field "id_action" isn't receiving datas of the function.
Whatever, the main problem is set the function showConfirm by paramters 'show', $row['id'] for the hidden field id_action.
<script>
function showConfirm (action, delID) {
if (action == 'show') {
document.confirm.id_action.value = delID;
}
}
</script>
<tbody>
<?php
if (!empty($_POST)) {
if (isset($_POST['id_action'])) {
$del_id = $_POST['id_action'];
$delUser = new User;
$delUser->deletarUsuario($del_id);
unset($delUser);
}
}
$listUser = new User;
$result = $listUser->listarUsers();
if (is_array($result)) {
foreach ($result as $row) {
echo "
<tr>
<td align='right'>" . $row['id'] . "</td>
<td>". $row['name'] . " ".$row['sobrename']."</td>
<td>" . $row['email'] . "</td>
<td>" . $row['login'] . "</td>
<td>
<a data-toggle='modal' id='deleteid' data-target='#modal_delUser' onclick=\"showConfirm('show'," . $row['id'] . ")\">
Remove
</a>
</td>
</tr>";
}
}
unset($listUser);
?>
</tbody>
<!-- Button trigger modal -->
<div class='modal fade' id='modal_delUser' tabindex='-1' role='dialog' aria-labelledby='modal_delUserLabel' aria-hidden='true'>
<div class='modal-dialog'>
<div class='modal-content panel-danger'>
<div class='modal-header panel-heading'>
<button type='button' class='close' data-dismiss='modal' aria-hidden='true'>×</button>
<h4 class='modal-title' id='modal_delUserLabel'>The user will be deleted</h4>
</div>
<div class='modal-body'>
Are you sure continue?
</div>
<div class="modal-footer">
<form role="form" id="confirm" action="users.php" method="post">
<input type="hidden" name="id_action">
<button type="button" class="btn btn-default" data-dismiss="modal">No</button>
<button type="submit" class="btn btn-danger">Yes</button>
</form>
</div>
</div>
</div>
</div>
Here the SQL that I am generating from the query
public function deletarUsuario($id) {
$del_id = $this->db->real_escape_string(trim($id));
if ($update = $this->db->query("DELETE FROM usuario WHERE id = $del_id")) {
if ($this->db->affected_rows) {
echo "<div><p>Deleted user!</p></div>";
}
else {
echo "<div><p>Failed to delete user.</p></div>";
}
}
else {
echo "<div><p>". $this->db->error."</p></div>";
echo "<script>$('#modal_erroBD').modal('show');</script>";
}
}

Do it in php by using $id_action = $_POST["id_action"]
Check if you are passing the id at this stage:
change
if (isset($_POST['id_action'])) {
$del_id = $_POST['id_action'];
$delUser = new User;
$delUser->deletarUsuario($del_id);
unset($delUser);
}
to
if (isset($_POST['id_action'])) {
$del_id = $_POST['id_action'];
echo $del_id;
}

Related

Fetch data from msql into selectpickers for editing

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;

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>

passing a MySQL data as string through PHP to javascript

I am trying create a social media site.
In the fourth line, the onclick='func_cmnt_open(".$row['post_ID'].") should display a div unique to each entry. it seems like a syntax error but I'm unable to narrow it down if its in PHP or javascript.
In line 6, id attribute was set to comment".$row['post_ID']." to make each div unique from the while loop iteration.
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
echo "<h4>".$row["username"]." said ".$row["cm_text"]." at ".$row["time"]." comment".$row['post_ID']."</h4>";
echo "<button class='w3-button w3-teal w3-xlarge' onclick='func_cmnt_open(".$row['post_ID'].")'>☰</button>";
echo "<button class='w3-button w3-teal w3-xlarge' onclick='func_like()' id='like'>☰</button>";
echo "<div class='w3-black' id='comment".$row['post_ID']."' style='display: none'>";
echo " <div class='w3-container''>";
echo " <h4>";
echo " ///code was here ";
echo " </h4>";
echo " <button class='w3-button w3-grey w3-xlarge' onclick='document.getElementById('id02').style.display='block''>☰</button>";
echo " <div id='id02' class='w3-modal'>";
echo " <div class='w3-modal-content w3-card-4'>";
echo " <header class='w3-container w3-teal'> ";
echo " <span onclick='document.getElementById('id02').style.display='none'' class='w3-button w3-display-topright'>×</span>";
echo " ///code was here";
echo " </header>";
echo " <div class='w3-container'>";
echo " <form class='w3-container' action='home.php' method='GET'>";
echo " <p><input type='text' class='w3-input' name='post_comment' placeholder='Whats happening there...'/></p>";
echo " <p><button class='w3-button w3-black'>Post</button></p>";
echo " </form>";
echo " </div>";
echo " <footer class='w3-container w3-teal'>";
echo " <p>nothing here</p>";
echo " </footer>";
echo " </div>";
echo " </div>";
echo " </div>";
echo "</div>";
}
}
JAVASCRIPT:
i had tried using string concat to join "comment" and "num" to get the unique id of div. that did not work either.
function func_cmnt_open(num) {
if (document.getElementById('comment'+num.tostring()).style.display == "none")
{
document.getElementById('comment'+num.tostring()).style.width = "100%";
document.getElementById('comment'+num.tostring()).style.display = "block";
}
else
{
document.getElementById('comment'+num.tostring()).style.width = "0%";
document.getElementById('comment'+num.tostring()).style.display = "none";
}
}
OUTPUT:the selected button should invoke the javascript with arguments from PHP code and display a black div where i can enter comments
I'm not sure of this is the most efficient way of doing it. please advice if there are any other way also to achieve the same output.
If post_ID is not strictly a string you will get a syntax error in Javascript.
... onclick='func_cmnt_open(".$row['post_ID'].")'...
Consider this value 1 Above will create this in the page source code.
... onclick='func_cmnt_open(1)'...
Now consider this value post1
... onclick='func_cmnt_open(post1)'...
In the second case it should be
... onclick='func_cmnt_open("$row['post_ID']")'...
To get that in PHP with the way you have echo you'll have to escape double quotes or the ' in the attribute will also cause issues. So like this:
... onclick='func_cmnt_open(\"".$row['post_ID']."\")'...
There were a few other quoting issues onclick='document.getElementById('id02').style.display='block'' ..>, I don't know if I got them all but should be better.
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
echo "<h4>{$row["username"]} said {$row["cm_text"]} at {$row["time"]} comment{$row['post_ID']}</h4>
<button class='w3-button w3-teal w3-xlarge' onclick='func_cmnt_open(\"{$row['post_ID']}\")'>☰</button>
<button class='w3-button w3-teal w3-xlarge' onclick='func_like()' id='like'>☰</button>
<div class='w3-black' id='comment{$row['post_ID']}' style='display: none'>
<div class='w3-container''>
<h4>
///code was here
</h4>
<button class='w3-button w3-grey w3-xlarge' onclick='document.getElementById(\"id02\").style.display=\"block\"'>☰</button>
<div id='id02' class='w3-modal'>
<div class='w3-modal-content w3-card-4'>
<header class='w3-container w3-teal'>
<span onclick='document.getElementById(\"id02\").style.display=\"none\"' class='w3-button w3-display-topright'>×</span>
///code was here
</header>
<div class='w3-container'>
<form class='w3-container' action='home.php' method='GET'>
<p><input type='text' class='w3-input' name='post_comment' placeholder='Whats happening there...'/></p>
<p><button class='w3-button w3-black'>Post</button></p>
</form>
</div>
<footer class='w3-container w3-teal'>
<p>nothing here</p>
</footer>
</div>
</div>
</div>
</div>";
}
}

Disable Submit button once database field is filled

I have created a form with submit button. If "price" for a particular product is already filled then the Submit button must be disabled:
Code Php
<?php
$host="localhost";
$username="root";
$password="";
$db_name="ge";
$con=mysqli_connect("$host", "$username", "$password","$db_name")or die("Your Connection is in error");
$sql="SELECT pname,catogery,email FROM quetation WHERE catogery = '$catogery'";
$results=mysqli_query($con,$sql);
$count=mysqli_num_rows($results);
if($count == 0) {
echo "<font color=\"#0000\"><h1 align=\"center\">No details found</h1></font>";
} else {
$resource=mysqli_query($con,$sql);
echo "<font color=\"#000000\">
<h2 align=\"center\"></h2>
<table align=\"center\" border=\"1\" width=\"50%\">
<tr>
<td><b>ProdName</b></td>
<td><b>Catogery</b></td>
<td><b>Price</b></td>
</tr> ";
while($result=mysqli_fetch_array($resource)) {
echo "
<div class=\"row\">
<div class=\"input-field col s12\">
<tr>
<td>".$result[0]."</td>
<td>".$result[1]."</td>
<td>
<form name=\"abc\" methos=\"post\" action=\"postprice.php\">
<input type=\"submit\" value=\"send\">
</form>
</td>
</div>
</div>
</tr>";
} echo "</table></font>";
}
?>
Only once price should be entered if already entered then send button should be disabled
Whenever I load this page it should check the database and if price value is filled then it should disable the send button.
Use the below code in the submit button:
<input type="submit" onClick="this.disabled=true;">
This will disable the button after clicking the submit button. Hope it helps you.
PLz try this code, hope it will work.
<?php
$host="localhost";
$username="root";
$password="";
$db_name="ge";
$con=mysqli_connect("$host", "$username", "$password","$db_name")or die("Your Connection is in error");
$sql="SELECT pname,catogery,email,price FROM quetation WHERE catogery = '$catogery'";
$results=mysqli_query($con,$sql);
$count=mysqli_num_rows($results);
if($count == 0)
{
echo "<font color=\"#0000\"><h1 align=\"center\">No details found</h1></font>";
}
else
{
$resource=mysqli_query($con,$sql);
echo "<font color=\"#000000\">
<h2 align=\"center\"></h2>
<table align=\"center\" border=\"1\" width=\"50%\">
<tr>
<td><b>ProdName</b></td>
<td><b>Catogery</b></td>
<td><b>Price</b></td>
</tr> ";
while($result=mysqli_fetch_array($resource))
{
echo "
<div class=\"row\">
<div class=\"input-field col s12\">
<tr>
<td>".$result[0]."</td>
<td>".$result[1]."</td>
<td><form name=\"abc\" methos=\"post\" action=\"postprice.php\">";
if($result[3]==''){
echo "<input type=\"submit\" value=\"send\" onClick='this.disabled=true;'>";
} else {
echo "<input type=\"submit\" value=\"send\" disabled>";
}
echo "</td>
</form>
</div>
</div>
</tr>";
}echo "</table></font>";
}
?>
first you will check in database product price is available or not if price is available then set the variable 0 for not available or 1 for available;

Modal reopens automatically after clicking the closing button

I've been trying to dynamically create a modal view in a table.
The data used to create the table is comming from a sql database.
Now my problem:
Whenever I click on a button called "Details" the modal view is opening and contains the data it should.
However, when I try to close the view with the "Close"- Button or the X in the top right corner the modal view will close for a second and reopen on its own.
The background will get darker after I do one of the above mentioned operations.
Here comes the tricky part. Whenever I close the view with the escape button on my keyboard, it'll close as it should and I'll get back to my previous view.
<?php
mysql_connect("localhost", "****" , "****");
mysql_select_db("hallo");
$sql= "SELECT * FROM erfassung WHERE Status='Abgeschlossen'";
$query=mysql_query($sql) or die (mysql_error());
while($row = mysql_fetch_assoc($query)) {
$thisId = $row['id'];
$thisModalId = 'modal'.$thisId;
$thisModalIdHref = '#'.$thisModalId;
$thisFormDoneId = $row['id'].'FormDoneId';
// Create table row
echo "<tr onclick=\"input\" data-toggle=\"modal\" href='$thisModalIdHref'>";
echo "<td>";
echo $row['Name'];
echo "<td>";
echo $row['Betreff'];
echo "<td>";
echo "<button class=\"btn btn-primary btn-lg\" data-toggle=\"modal\" data-target='$thisModalIdHref'>";
echo "Details";
echo "</button>";
echo"<div class=\"modal fade\" id='$thisModalId' tabindex=\"-1\" role=\"dialog\" aria-labelledby=\"myModalLabel\" aria-hidden=\"true\">";
echo "<div class=\"modal-dialog\">";
echo "<div class=\"modal-content\">";
echo "<div class=\"modal-header\">";
echo "<button type=\"button\" class=\"close\" data-dismiss=\"modal\" aria-hidden=\"true\">×</button>";
echo "<h4 class=\"modal-title\" id=\"myModalLabel\">Weitere Information </h4>";
echo "</div>";
echo"<div class=\"modal-body\">";
echo "<dl class=\"dl-horizontal\">";
echo "<dt>Bereich</dt>";
echo "<dd>" .$row['Bereich']. "</dd>";
echo "</dl>";
echo"</div>";
echo"<div class=\"modal-footer\">";
echo "<button type=\"button\" class=\"btn btn-default\" data-dismiss=\"modal\">Close</button>";
echo "<button type=\"button\" class=\"btn btn-primary\">Save changes</button>";
echo"</div>";
echo"</div>"; //<!-- /.modal-content -->
echo"</div>";//<!-- /.modal-dialog -->
echo"</div>";//<!-- /.modal -->
echo "</td>";
echo "</tr>";
}
?>
For clarification:
If the $thisModalId is changed to the previous "MyModal" it works, but the button will, as it's supposed to, open the same text.
If you need any more source code or something else, I'd be more than happy to post it.
Thanks in advance for your help guys.
Best regards.
This is probably caused by the fact that your modal div is defined inside the element (tr) that the onclick handler is defined on. If the close button handler does not consume the click event, it will bubble to the containing elements all the way up (div, div, div, div, td, tr). When it gets to the tr, the onclick handler will execute and the modal will open again.
Obviously, you can solve this by not having your modal div inside your table structure, which doesn't really have a function anyway. This means that you will have to perform more than one separate loop, because the divs have to be all the way outside the table. This does not have to mean that your code will get messy if you take the advice of some of the commenters above and separate your PHP from your HTML a little bit.
Try something like this:
<?php
// Collect data
mysql_connect("localhost", "****" , "****");
mysql_select_db("hallo");
$sql= "SELECT * FROM erfassung WHERE Status='Abgeschlossen'";
$query=mysql_query($sql) or die (mysql_error());
$modals = array();
while($row = mysql_fetch_assoc($query)) {
$modals[] = array(
'id' => 'modal' . $row['id'],
'href' => '#modal' . $row['id'],
'FormDoneId' => $row['id'] . 'FormDoneId',
'Name' => $row['Name'],
'Betreff' => $row['Betreff'],
'Bereich' => $row['Bereich'],
);
}
?>
<table> <!-- Or something -->
<?php
foreach ($modals as $modal) {
// Create table rows
?>
<tr onclick="input" data-toggle="modal" href="<?php echo $modal['href'] ?>">
<td>
<?php echo $modal['Name'] ?>
<td>
<?php echo $modal['Betreff'] ?>
<td>
<button class="btn btn-primary btn-lg" data-toggle="modal" data-target="<?php echo $modal['href'] ?>">
Details
</button>
</td>
</tr>
<?php
}
?>
</table>
<?php
foreach ($modals as $modal) {
// Create modal divs
?>
<div class="modal fade" id='<?php echo $modal['id'] ?>' tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title" id="myModalLabel">Weitere Information </h4>
</div>
<div class="modal-body">
<dl class="dl-horizontal">
<dt>Bereich</dt>
<dd><?php echo $modal['Bereich'] ?></dd>
</dl>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Save changes</button>
</div>
</div> //<!-- /.modal-content -->
</div>//<!-- /.modal-dialog -->
</div>//<!-- /.modal -->
<?php
}

Categories

Resources