Problem by Passing variable between PHP, JS and HTML - javascript

In my code I send $id to Java Script section and it returns the same value inside <p id="retid"></p> and I can't get the value as integer inside $text variable.
`while ($row = $result->fetch_assoc())
{
$id = $row["id"];
$regname = $row["reg-name"];
echo '<button class="btnicon btndel" type="button" name="answer" onclick="showDiv('.$id.')"><i class="fa fa-trash"></i> '.$regname.'</button>';
}
} else {
//header("Location: login.php?Msg=wrongPass"); }
}
?>
</div>
<div id="DelMessageDiv" style="display:none;" class="answer_list" >
<form action="_modify.php" method="get">
<div id="alerts">
<?php
$text = '<p id="retid"></p>';
echo $text.'-+-'.strip_tags($text,'<p>').'
Are you sure for delete?
<input name="id" type="hidden" value="'.strip_tags($text).'" />
<button class="btnicon btndel" type="submit" name="operation" value="0+regDelete">Yes Delete</button>
';
?>
</div>
</form>
</div>
</div>
<?php include '_footer.php'; ?>
<script src="js/extention/choices.js"></script>
<script>
const choices = new Choices('[data-trigger]',
{
searchEnabled: false
});
function showDiv(x) {
document.getElementById('DelMessageDiv').style.display = "block";
document.getElementById('retid').innerHTML = x;
}
</script>`
Thanks for all helps.

Related

How to delete values from JSON object array in php?

I have a PHP code and JSON as shown below:
PHP Code:
<?php if (!empty($_POST) && isset($_POST['savechanges']) && $_POST['savechanges'] == 1 && isset($_SESSION['pageadmin'])) {
$output = array();
$output['en_desc']=$_POST['en_desc'];
$output['code']=$_POST['code'];
$fp = fopen('../feeds/ptp-ess_landing_scommittees.json', 'w');
fwrite($fp, json_encode($output));
fclose($fp);
}
if(file_exists('../feeds/ptp-ess_landing_scommittees.json')){
$data = json_decode(file_get_contents('../feeds/ptp-ess_landing_scommittees.json'));
}
?>
<?php if($data) { ?>
<form method="post" id="myform" style="text-align:left;">
<input type="hidden" id="savechanges" name="savechanges" value="1">
<div style="text-align:center; margin-right:9px; margin-bottom:24.703px;">
<button type="submit">Save</button>
</div>
<?php foreach ($data->code as $key => $value) { ?>
<div class="house-senate-committee" style="text-align:center; margin-top:15px;">
<button type="button" onclick="removeRow(this)" style="margin-right:10px;">Delete</button>
<input type="text" name="code[]" style="margin-right:10px;" value="<?= $data->code[$key] ?>">
<input type="text" name="en_desc[]" value="<?= $data->en_desc[$key] ?>">
</div>
<?php } ?>
</form>
<?php } else { echo 'Cannot read JSON settings file'; }?>
JSON:
{"code":["AEFA","AGFO"], "en_desc":["Foreign Affairs and International Trade","Agriculture and Forestry"]}
The following DOM is generated through the PHP/JSON code above:
DOM (HTML):
<div class="house-senate-committee" style="text-align:center; margin-top:15px;">
<button type="button" onclick="removeRow(this)" style="margin-right:10px;">Delete</button>
<input type="text" name="code[]" style="margin-right:10px;" value="AEFA">
<input type="text" name="en_desc[]" value="Foreign Affairs and International Trade">
</div>
<div class="house-senate-committee" style="text-align:center; margin-top:15px;">
<button type="button" onclick="removeRow(this)" style="margin-right:10px;">Delete</button>
<input type="text" name="code[]" style="margin-right:10px;" value="AGFO">
<input type="text" name="en_desc[]" value="Agriculture and Forestry">
</div>
The following JS code deletes a row from the DOM on click of a delete button. On refreshing the page,
the deleted row comes back again as everything is rendered through JSON.
JS code:
<script>
function removeRow(el) {
el.parentNode.remove();
}
</script>
Problem Statement:
The above JS code is deleting the row (on click of a delete button) from the DOM but on refresing the page, everything is rendered again.
I am wondering what PHP code I need to add so that it delete the values from the JSON on saving the form when row is deleted from DOM through JS.
Step 1: User delete the row from the DOM on click of a delete button.
Step 2: On saving the form and rendering the page, that deleted row should not be present.
I know I have to use unset function in order to remove the values from the JSON but I am not sure how I can integrate it in the form.
unset($data->code);
unset($data->en_desc);
You have a typo here:
$data = json_decode(file_get_contents('../feeds/ptp-ess_landing_scommittees.json'));
it should be
$data = json_decode(file_get_contents('../feeds/ptp-ess_landing_committees.json'));
Look at the "s" :)
Edit: you also were saving the new file without actually checking if there is a post happening, here is the full code:
<?php
if (isset($_POST['submit'])) {
$output = array();
$output['en_desc'] = $_POST['en_desc'];
$output['code'] = $_POST['code'];
$fp = fopen('../feeds/ptp-ess_landing_committees.json', 'w');
fwrite($fp, json_encode($output));
fclose($fp);
}
if (file_exists('../feeds/ptp-ess_landing_committees.json')) {
$data = json_decode(file_get_contents('../feeds/ptp-ess_landing_committees.json'));
}
?>
<?php if ($data) { ?>
<form method="post" id="myform" style="text-align:left;">
<div style="text-align:center; margin-right:9px; margin-bottom:24.703px;">
<button type="submit" name="submit">Save</button>
</div>
<?php foreach ($data->code as $key => $value) { ?>
<div class="house-senate-committee" style="text-align:center; margin-top:15px;">
<button type="button" onclick="removeRow(this)" style="margin-right:10px;">Delete</button>
<input type="text" name="code[]" style="margin-right:10px;" value="<?= $data->code[$key] ?>">
<input type="text" name="en_desc[]" value="<?= $data->en_desc[$key] ?>">
</div>
<?php } ?>
</form>
<?php } else {
echo 'Cannot read JSON settings file';
} ?>
<script>
function removeRow(el) {
el.parentNode.remove();
}
</script>

How to sent id from one page to another when click on submit?

I have a database which consists of question_id, question, and options. Where I'll display the question and options. When the user clicked on submit I want to store the option they clicked and the question_id.
I am able to store the option they clicked but want to know how to store the question_id.
$user_email = $_SESSION['email'];
$query1="SELECT * FROM votes WHERE user_email='$user_email'";
$query2="SELECT * FROM poll_question WHERE status='1'";
$fetch2 = mysqli_query($con,$query2);
<html>
<head>
<body>
<div class="container">
<br />
<br />
<br />
<div class="row">
<div class="col-md-6">
<?
while( $row2 = mysqli_fetch_array($fetch2))
{
?>
<form method="post" class="poll_form">
<h3><?echo $row2['question']?>?</h3>
<br />
<div class="radio">
<label><h4><input type="radio" name="poll_option" class="poll_option" value=<?echo $row2['option1']?> /><?echo $row2['option1']?></h4></label>
</div>
<div class="radio">
<label><h4><input type="radio" name="poll_option" class="poll_option" value=<?echo $row2['option1']?> /> <?echo $row2['option2']?></h4></label>
</div>
<br />
<?php
if( $count >0)
{ ?>
<button disabled="disabled" alt="<?php echo $row2['question_id']; ?>" rel="<?php echo $user_email; ?>" class="btn btn-primary poll_option" title="<?php echo $ip; ?>">Submit</button>
<h>You selected : <? echo $row1['vote_option']; ?></h>
<br>
<p id="demo"></p>
<?php
}
else
{ ?>
<button alt="<?php echo $row2['question_id']; ?>" rel="<?php echo $user_email; ?>" class="btn btn-primary poll_option" title="<?php echo $ip; ?>">Submit</button>
<?
}
?>
</form>
<? }
} ?>
<br />
</div>
</div>
<br />
<br />
<br />
</div>
</body>
<script type="text/javascript">
$(document).ready(function(){
$(".poll_form").submit(function(event){
event.preventDefault(); //prevents the form from submitting normally
var poll_option = '';
$('button.poll_option').each(function(){
if($(this).prop("checked"))
{
poll_option = $(this).val();
var option=poll_option;
}
var url = '<?php echo SITE_URL; ?>';
});
$.post("poll_vote.php",$('.poll_form').serialize(),
function(data)
{
if(data=="User Created Success"){
window.setTimeout(function () {
location.href ="<?php echo SITE_URL; ?>poll.php";
}, 100);
}
else{
$("#result").html(data);
}
}
);
//to reset form data
});
});
<? } ?>
</script>
</html>
Using th below function I am sending the poll_option to other where I kept the inset operation. Now I want to send the question_id also
Create a hidden input filed in your form
<input type="hidden" name="question_id" value="<?php echo $row2['question_id']; ?>">
Create a hidden input field in your form.
<input type="hidden" id="question_id" name="question_id" value="<?= $row2['question_id'] ?>">
PHP solution:
In this case your question_id will be included in the POST.
You can then access it by calling $_POST['question_id'].
Jquery solution:
In Jquery you can also access it by:
$("#question_id").val();

insert data in database dynamically

$query = "select * from comments t1 inner join users t2 on t1.user_id = t2.UserId where usercomplain_id='$id'";
$run =mysqli_query($mysqli,$query);
while($row=mysqli_fetch_array($run))
{
$commentid = $row['comment_id'];
$comment = $row['comment'];
$username = $row['UserName'];
$userid1 = $row['UserId'];
$date = $row['CDate'];
$ageDate = time_elapsed_string($date);
?>
<div class="jumbotron" style="border:3px solid #2FAB9B; background-color:#68C8C6;">
<div class="row">
<div class="col-md-10">
<?php echo $comment; ?>
</div>
<div class="col-md-2">
<?php echo $ageDate; ?>
</div>
</div>
<br>
<label>Comment by <?php echo $username; ?></span></label><br>
<a class="reply" data-role="<?php echo $commentid; ?>">Reply</a>
<br>
<br>
<div style="width:63%; display:none;" class="replyForm" data-role="<?php echo $commentid; ?>">
<form method="post">
<textarea cols="100" rows="4"></textarea><br>
<br>
<input type="submit" name="reply" class="btn btn-primary" style="float:right" value="reply">
</form>
</div>
</div>
<script>
$(document).ready(function(){
$(".reply").click(function(){
var current = $(this).attr("data-role");
$('.replyForm[data-role="'+$(this).attr("data-role")+'"]').fadeIn();
});
});
</script>
<?php
if(isset($_POST['reply']))
{
echo "<script>alert('$commentid')</script>";
}
?>
<?php } ?>
it is a simple comment system with each comment there is a reply link on click on reply link a textbox is shown . I want to enter comment reply to database table therefore I want to get the record of the specific comment. How to do that with PHP.
this code should do what you want, completely dinamically
<div class="jumbotron comment-container" data-pk="<?php echo $commentid; ?>">
<div class="row">
<div class="col-md-10">
<?php echo $comment; ?>
</div>
<div class="col-md-2">
<em class="text-muted"><?php echo $ageDate; ?></em>
</div>
<div class="col-md-12">
<label>Comment by <?php echo $username; ?></label><br/>
<button class="btn btn-primary reply">Reply</button>
</div>
</div>
</div>
And here is the JS part. In order to reduce the code printed in the while loop, the reply form is cloned each time and appended where needed.
var reply_form = $('<div class="row replyForm-container"><div class="col-md-12">'+
'<form method="post" class="reply-form">'+
'<textarea class="form-control" rows="4">Prefilled content</textarea><br>'+
'<br>'+
'<button type="submit" name="reply" class="btn btn-primary" style="float:right" >Reply</button>'+
'</form>'+
'</div></div>');
$(".reply").click(function(){
$(this).hide();
var $container = $(this).closest('.comment-container');
var pk = $container.data('pk');
var rf_clone = reply_form.clone();
rf_clone.find('form').attr('data-pk', pk).data('pk', pk);
$container.append( rf_clone.hide().fadeIn(1000) );
});
// working with dynamical elements, we need to use delegation here
$(document).on('submit', '.reply-form', function(e){
e.preventDefault();
var reply_container = $(this).closest('.replyForm-container');
var pk = $(this).data('pk');
var reply = $(this).find('textarea').val();
console.log('Insert reply "'+reply+'" for comment ID: '+pk);
$.ajax({
type: "POST",
url: 'my_php_handler.php',
async: false,
dataType: "json",
data: {action: 'add-reply', commend_id: pk, reply_text: reply},
success: function (response) {
if( response ) {
reply_container.fadeOut('slow', function(){
var btn = reply_container.closest('.comment-container').find('button.reply');
$(this).remove(); //will remove the element after fadeOut completes
btn.show();
})
}
}
});
});
Check working Fiddle (ajax disabled)

Building Filtering sidebar and searching box

I want to build filtering sidebar and search box . My problem is, I can't make it run searching box and filtering items together at the same time. I hope any of u can help me?
I think,the main problem is in my script "var s" php parameter where I'm getting cities from
Let's see what I've done so for,
Here's my script;
<script>
$(function(){
$('.item_filter').change(function(){
var p = multiple_values('p');
var s ='<?php echo $_POST["search"]; ?>';
var url ="product.php?product=<?php echo
htmlentities($_GET['product']) ?>&s="+s+"&b="+b+"&p="+p;
window.location=url;
});
});
function multiple_values(inputclass){
var val = new Array();
$("."+inputclass+":checked").each(function() {
val.push($(this).val());
});
return val.join('-');
}
</script>
Search Box
<form class="search" name="search" method="POST"
action="product.php?product=<?php echo
''.htmlentities($_GET['product']).''; ?>" >
<a href="javascript:void(0);"><input id="small_search"
name="searchTerm" class="item_filter s" <?php { echo "checked"; } ?>
list="local" /></a>
<?php
while($row = mysqli_fetch_assoc($result)){
$local = ($row['local']); ?>
<a href="javascript:void(0);" target="_blank"><input type="submit"
id="small_search_btn" value="Search"></a >
<datalist id="local">
<option value="<?php echo ''.htmlentities($row['local']).''; ?
>"></option>
<?php } ?>
</form >
**Filtering **
<div class="list-group" style="font-size:14px;">
<h4 style="font-size:16px; font-weight: bold; color:black;">
</h4>
<?php
some sql statement..
?>
<a href="javascript:void(0);" class="list-group-item"
id="left_filtering" >
<label >
<input type="checkbox" class="item_filter b" value="<?php echo
htmlentities($row['brand']); ?>" <?php if(in_array($row['brand'],$b
{echo "checked"; } ?> > <?php echo ucfirst($row['brand']);
?></a>
</label>
<?php } ?>
</div>

Script not working in a Form

I have been dealing with this issue and is a very stupid question but I really don't understand why my JavaScript functions never execute when I press the buttons I have tried everything please help thanks!!
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script type="text/javascript">
function validateForm()
{
var jArray= <?php echo json_encode($arr ); ?>;
var counter= <?php echo json_encode($i ); ?>;
var productId;
var productQty;
confirm(productId + " can not be empty");
for (i = 0; i < counter; i++) {
productQty = jArray[1][i];
productId= jArray[0][i];
if (document.getElementById("register").elements.namedItem("productId").value !== productQty) {
confirm(productId + " can not be empty");
}
}
}
</script>
<script type="text/javascript">
function myFunction1() {
alert("Hello! I am an alert box!");
}
</script>
</head>
>
<body>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<!-- Optional theme -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap-theme.min.css">
<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<?php
$code1 ="";
$exeption="";
$s="";
session_start();
$arr=array();
$con = mysqli_connect('localhost','root','','customer_service_experts');
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
$empId= $_SESSION['eId'];
$sql2= "SELECT locationId FROM location_user where empId='".$empId."' and active ='1'";
$result2 = mysqli_query($con,$sql2);
while($row = mysqli_fetch_array($result2)){
$code1 = $row["locationId"];
}
mysqli_select_db($con,"customer_service_experts");
$sql="SELECT * FROM location_product where productLocation=$code1";
$result = mysqli_query($con,$sql);
echo "
<form action='productInventoryEmp.php' method='POST' id='register'>
<div class='form-group col-md-5'>
";
$i=0;
while($row = mysqli_fetch_array($result)) {
$arr[1][$i]=$row['productQty'];
$arr[0][$i]=$row['productId'];
$sql1="SELECT productName FROM product where productId='".$row['productId'] ."' limit 1 ";
$result1 = mysqli_query($con,$sql1);
if($result1!=false){
while($row = mysqli_fetch_array($result1)){
$code = $row["productName"];
echo " <div class='input-prepend'>";
echo "<span class='add-on' >".$code."</span>";
}
echo "<input type='number' min='0' step='1' data-bind='value:replyNumber' class='span2' id=" . $row['productId'] . "/>";
echo "</div>";
}else {
$s="1";
$exeption="There are no Products for in this location!";
}
echo "<br>";
echo "<br>";
$i++;
}
$_SESSION['ArrayCount']=$i; //counter
$_SESSION['ArrayProduct']=$arr; // ID Product y Qty
if ($s=="1") {
echo $exeption;
}
?>
</div>
<div class="col-md-6">
<div class="form-group">
<label for="comment">Note:</label>
<textarea class="form-control" rows="5" id="comment"></textarea>
</div>
<button type="submit" class="btn btn-default" onclick="validateForm()">Cancel</button>
<button type="submit" class="btn btn-default" onsubmit="myFunction1()">Save and Start Shift</button>
</div>
</form>
<?php
mysqli_close($con);
?>
</body>
</html>
Your buttons submit the form. That's why your functions never execute.
<button type="button" class="btn btn-default" onclick="validateForm()">Cancel</button>
<button type="button" class="btn btn-default" onclick="myFunction1()">Save and Start Shift</button>
Then set id to your form
<form id="myform" action="..">
And in the end of your functions, if you want to submit the form, set
$('#myform').submit();
And don't forget to include jquery library.
Hope it works!
Change this:
<button type="submit" class="btn btn-default" onclick="validateForm()">Cancel</button
<button type="submit" class="btn btn-default" onsubmit="myFunction1()">Save and Start Shift</button>
To this:
<input type="submit" class="btn btn-default" onclick="validateForm()" >Cancel
<input type="submit" class="btn btn-default" id="Save">Save and Start Shift
In your script:
$('#Save').on('click', function(){
myFunction1(); //your function
});

Categories