Hide/Show toggle echo results in php - javascript

I am trying to toggle results i have echo'd out of table but i am having no luck.
I have tried the same code in HTML and it works perfectly.
Ive been working on this for a while now, and was wondering if someone could point me in the right direction.
What I've tired
Adding the javascript inside the php echo.
Adding a counter to the id, to make it unique on loop
Placing each line of the echo results in echo(""); tags.
adding a counter, to make the id unique on loop.
PHP
$i = 1;
while ($output = $fc_sel->fetch_assoc()) {
$fc_run .= $output['Food_Cat_name'] . $output['Food_Cat_Desc'] . '<br>';
$_SESSION['Food_Cat_name'] = $output['Food_Cat_name']; //echo out product name
$_SESSION['Food_Cat_Desc'] = $output['Food_Cat_Desc']; //echo out product desc
echo"
<div id='first_product'>
<button onclick='toggle_visibility('tog')'>Toggle</button>
<div id='tog'>
<div id='red_head'>
<p id='menu_title' class ='hidden' onclick='toggle_visibility('tog')'> Add your first menu item</p>
</div>
<h3 id='menu'>Menu Section</h3>
<form name='first_prod' id='first_prod' enctype='multipart/form-data' action='testing.php' method='POST' accept-charset='utf-8' >
<label id='cat_label' name='cat_label'>Name</label>
<input type='text' id='cat_name' name='cat_name' value=''>
<label id='desc_label' name='desc_label'>Description</label>
<input type='text' id='cat_desc' name='cat_desc' value=''>
</form>
</div>
</div>
";
}
}
JAVASCRIPT
<script>
//turn entire div into toggle
function toggle_visibility(id) {
var e = document.getElementById(id);
if (e.style.display == 'block' || e.style.display == '')
e.style.display = 'none';
else
e.style.display = 'block';
}
</script>

The single quotes in onclick='toggle_visibility('tog')' are conflicting with the outer single quotes. So either escape them or use double quotes in either the outer pair or the inner pair.
Then in PHP, remove the <?php echo. Just put the HTML in PHP. The echo only complicates things. If you need dynamic data in your HTML, just inject it at that place with <?php ... ?>. But so far I haven't seen any of that in your HTML: it is static.
Here is a working snippet, after having made that change in two places:
//turn entire div into toggle
function toggle_visibility(id) {
var e = document.getElementById(id);
if (e.style.display == 'block' || e.style.display == '')
e.style.display = 'none';
else
e.style.display = 'block';
}
<div id='first_product'>
<button onclick="toggle_visibility('tog')">Toggle</button>
<div id='tog'>
<div id='red_head'>
<p id='menu_title' class ='hidden' onclick="toggle_visibility('tog')"> Add your first menu item</p>
</div>
<h3 id='menu'>Menu Section</h3>
<form name='first_prod' id='first_prod' enctype='multipart/form-data' action='testing.php' method='POST' accept-charset='utf-8' >
<label id='cat_label' name='cat_label'>Name</label>
<input type='text' id='cat_name' name='cat_name' value=''>
<label id='desc_label' name='desc_label'>Description</label>
<input type='text' id='cat_desc' name='cat_desc' value=''>
</form>
</div>
</div>
Edit after modification of the question
The code in the question was extended so the HTML is produced in a loop now.
You should now take care to produce unique id values only. So you'll probably want to add <?=$i?> at several places, like this:
<?php
session_start();
// ....
$i = 1;
while ($output = $fc_sel->fetch_assoc()) {
$fc_run .= $output['Food_Cat_name'] . $output['Food_Cat_Desc'] . '<br>';
$_SESSION['Food_Cat_name'] = $output['Food_Cat_name'];
$_SESSION['Food_Cat_Desc'] = $output['Food_Cat_Desc'];
?>
<div id='first_product<?=$i>'>
<button onclick="toggle_visibility('tog<?=$i>')">Toggle</button>
<div id='tog<?=$i>'>
<div id='red_head<?=$i>'>
...etc. Note that the PHP was closed before the HTML output started. Do this, instead of a large echo. Then at the end of it, open PHP tag again to end the loop:
<?php
}
?>

please modify your code
echo "
<div id='first_product'>
<button onclick='toggle_visibility(\"tog\")'>Toggle</button>
<div id='tog'>
<div id='red_head'>
<p id='menu_title' class ='hidden' onclick='toggle_visibility(\"tog\")'> Add your first menu item</p>
</div>
<h3 id='menu'>Menu Section</h3>
<form name='first_prod' id='first_prod' enctype='multipart/form-data' action='testing.php' method='POST' accept-charset='utf-8' >
<label id='cat_label' name='cat_label'>Name</label>
<input type='text' id='cat_name' name='cat_name' value=''>
<label id='desc_label' name='desc_label'>Description</label>
<input type='text' id='cat_desc' name='cat_desc' value=''>
</form>
</div>
</div>
"

<button value='tog' onclick='toggle_visibility(this)'>Toggle</button>
Just use "this" and assign value to button its working

Try this ;)
<?php
$i = 1;
while($output = $fc_sel->fetch_assoc()){
$fc_run .= $output['Food_Cat_name'] . $output['Food_Cat_Desc'] . '<br>';
$_SESSION['Food_Cat_name'] = $output['Food_Cat_name']; //echo out product name
$_SESSION['Food_Cat_Desc'] = $output['Food_Cat_Desc']; //echo out product desc
?>
<div id="first_product<?php echo $i; ?>">
<button onclick="javascript:toggle_visibility('tog<?php echo $i; ?>')">Toggle</button>
<div id="tog<?php echo $i; ?>">
<div id="red_head<?php echo $i; ?>">
<p id="menu_title<?php echo $i; ?>" class ="hidden" onclick="toggle_visibility('tog<?php echo $i; ?>')"> Add your first menu item</p>
</div>
<h3 id="menu<?php echo $i; ?>">Menu Section</h3>
<form name="first_prod" id="first_prod<?php echo $i; ?>" enctype="multipart/form-data" action="testing.php" method="POST" accept-charset="utf-8">
<label id="cat_label<?php echo $i; ?>" name="cat_label">Name</label>
<input type="text" id="cat_name<?php echo $i; ?>" name="cat_name" value="">
<label id="desc_label<?php echo $i; ?>" name="desc_label">Description</label>
<input type="text" id="cat_desc<?php echo $i; ?>" name="cat_desc" value="">
</form>
</div>
</div>
<?php
$i++;
}
?>

Related

Why I need to use history.back(); twice for cancel button

I created a cancel button using the method explained by macino in this thread
cancel button using php
But I have to use history.back(); twice to cancel the form. What is the reason for that? Thanks.
$post_counter=1;
foreach ($comment as $c) {
echo $c['comment'] . "<br>";
echo "By " . $c['first_name'] . "<br>";
if($c['uid'] == $current_user) { ?>
Edit<br>
<div id="<?php echo "post_edit_box" . $post_counter; ?>" style="display:none">
<form id="<?php echo "reply_form" . $post_counter; ?>" method="post" action="<?php echo site_url('Forum/update_comment'); ?>">
<input type="text" name="edit_comment" value="<?php echo $c['comment'];?>" class="form-control">
<input type='hidden' name='edit_cid' value='<?php echo $c['id']; ?>'/>
<button type="submit">Save Changes</button>
<input type="button" value="Cancel" onclick="history.back();history.back();" />
</form>
</div>
<script>
function show_postedit_box(clicked_edit_id){
let str_edit = clicked_edit_id;
str_edit.replace("post_edit_link", "");
//console.log('mylink' + str.replace("mylink", ""));
document.getElementById('post_edit_box' + str_edit.replace("post_edit_link", "")).style.display = "block";
document.getElementById('post_edit_link' + str_edit.replace("post_edit_link", "")).style.display = "none";
}
</script>
<?php
$post_counter++;
}

Combining two or more submit buttons into one

I have submit buttons for different section of the webpage. The submit button is used to update the forms and database with the text value in the form fields. Currently, each submit button updates the forms (tied to their respective PKEY id, "consideration_no") only in their own sections. I want to update all the sections forms with one button click.
As you can see from the code below, there are 2 submit buttons. I have tried to link two together through IDs but it did not work for me.
// Include config file
require_once "config.php";
// Define variables and initialize with empty values
$question = $answer = "";
$question_err = $answer_err = "";
if(isset($_POST["dg_no"]) && !empty($_POST["dg_no"])){
//counter for array
$counter = 0;
// Get hidden input value
$dg_no = $_POST['dg_no'];
$consideration_no = $_REQUEST['consideration_no'];
$answer = $_POST['answer'];
// Check input errors before inserting in database
if(empty($answer_err)){
// Validate address address
$input_answer = trim($_POST["answer"]);
if(empty($input_answer)){
$answer_err = "Please enter an answer.";
} else{
$answer = $input_answer;
$answer1[$counter] = $input_answer;
}
// Prepare an Submit statement
$sql = 'Update "PDPC".consideration SET answer=:answer WHERE consideration_no = :consideration_no';
if($stmt = $pdo->prepare($sql)){
$stmt->bindParam(":answer", $param_answer);
$stmt->bindParam(":consideration_no", $param_consideration_no);
//$stmt->bindParam(":dg_no", $param_dg_no);
//Set Parameter in while loop, hence new set of parameter for every new form is created and executed.
//Could change the counter loop to a dynamic loop with foreach array.
while ($counter<15){
$param_answer = $answer[$counter];
$param_consideration_no = $consideration_no[$counter];
$stmt->execute();
//$param_dg_no = $dg_no;
// Attempt to execute the prepared statement
//debugggggg
/* $message = $consideration_no[$counter];
$message1 = $answer[$counter];
$message2 = 'lol';
echo "<script type='text/javascript'>alert('$message, $message1, $message2 ');</script>"; */
$counter++;
//apparently redirecting can be placed in the loop, and fields will still get changed.
//header("location: home1.php?dm_no=".$_GET["dm_no"]);
header("location: home1.php?dm_no=".$_GET["dm_no"]);
}
}
if($stmt->execute()){
//Records Submitd successfully. Redirect to landing page
header("location: home1.php?dm_no=".$_GET["dm_no"]);
exit();
} else{
echo "Something went wrong. Please try again later.";
}
// Close statement
unset($stmt);
}
// Close connection
unset($pdo);
} else{
/* --- DISPLAY/READ TABLE, SEE SECTIONS AND ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------- */
// Check existence of dg_no parameter before processing further
if(isset($_GET["dg_no"]) && !empty(trim($_GET["dg_no"]))){
// Get URL parameter
$dg_no = trim($_GET["dg_no"]);
// Prepare a select statement
$sql = 'SELECT * FROM "PDPC".consideration WHERE (dg_fkey = :dg_no AND code_no = 1) ORDER BY consideration_no';
if($stmt = $pdo->prepare($sql)){
// Bind variables to the prepared statement as parameters
$stmt->bindParam(":dg_no", $param_no);
// Set parameters
//$param_no = $dg_no;
$param_no = trim($_GET["dg_no"]);
// Attempt to execute the prepared statement
if($stmt->execute()){
if($stmt->rowCount() > 0){
SubSection($subsection1_1); //Consent Collection Subsection
while($row = $stmt->fetch()){
// Retrieve individual field value
$consideration_no = $row["consideration_no"];
$question = $row["question"];
$answer = $row["answer"];
$dg_no = $_GET['dg_no'];
//...time to show the questions and answers with the while loop...
?>
<form action="<?php echo htmlspecialchars(basename($_SERVER['REQUEST_URI'])); ?>" method="post">
<div class="form-group <?php echo (!empty($answer_err)) ? 'has-error' : ''; ?>">
<label><?php echo $question; ?></label>
<input type="text" name="answer[]" class="form-control" value="<?php echo $answer; ?>">
<span class="help-block"><?php echo $answer_err;?></span>
<input type="hidden" name="consideration_no[]" value="<?php echo $consideration_no; ?>"/>
<input type="hidden" name="dg_no" value="<?php echo $dg_no; ?>"/>
</div>
<?php
}
//...after the loop, show the Submit and Cancel button, coz we only need 1 set each section.
?>
<input type="Submit" name = "$consideration_no[]" class="btn btn-primary" value="Submit">
Cancel
</form>
</div>
<?php
}
}
else{
echo "Oops! Something went wrong. Please try again later.";
}
}
Section($section2); //Collection section
// Prepare a select statement
$sql = 'SELECT * FROM "PDPC".consideration WHERE (dg_fkey = :dg_no AND code_no = 2) ORDER BY consideration_no';
if($stmt = $pdo->prepare($sql)){
// Bind variables to the prepared statement as parameters
$stmt->bindParam(":dg_no", $param_no);
// Set parameters
//$param_no = $dg_no;
$param_no = trim($_GET["dg_no"]);
// Attempt to execute the prepared statement
if($stmt->execute()){
if($stmt->rowCount() > 0){
SubSection($subsection2); //Consent Collection Subsection
while($row = $stmt->fetch()){
// Retrieve individual field value
$consideration_no = $row["consideration_no"];
$question = $row["question"];
$answer = $row["answer"];
$dg_no = $_GET['dg_no'];
//...time to show the questions and answers with the while loop...
?>
<form action="<?php echo htmlspecialchars(basename($_SERVER['REQUEST_URI'])); ?>" method="post">
<div class="form-group <?php echo (!empty($answer_err)) ? 'has-error' : ''; ?>">
<label><?php echo $question; ?></label>
<input type="text" name="answer[]" class="form-control" value="<?php echo $answer; ?>">
<span class="help-block"><?php echo $answer_err;?></span>
<input type="hidden" name="consideration_no[]" value="<?php echo $consideration_no; ?>"/>
<input type="hidden" name="dg_no" value="<?php echo $dg_no; ?>"/>
</div>
<?php
}
//...after the loop, show the Submit and Cancel button, coz we only need 1 set each section.
?>
<input type="Submit" name = "$consideration_no[]" class="btn btn-primary" value="Submit">
Cancel
</form>
</div>
<?php
}
}
else{
echo "Oops! Something went wrong. Please try again later.";
}
}
// Close statement
unset($stmt);
// Close connection
unset($pdo);
}
else{
// URL doesn't contain dg_no parameter. Redirect to error page
header("location: error.php");
exit();
}
}
I want it to update all the fields, in different sections, with one submit button
your code was bit difficult to read, but from what i understood you are trying to combine two or more form submissions into one. It's quiet simple
<form method="POST" action="save.php">
<input type=text name=name[] />
<input type=text name=name[] />
</form>
by using the [] to identify the input element you can have multiple values with the same name where you can access them from the PHP script as an array.
For example the above example will produce an array as follows
<?php
print_r($_POST['name']); //("name" => Array....
is this clear enough for you? if not drop a comment, i will explain more. As a side note i do recommend you look into using template engine, and also a framework in your coding project.
Here's what I see when i separate the html into a new file. I tried to remove the excess forms but when I open the last collapsible section, it instantly executes a submit action and brings me back to the home page.
<button class="collapsible"><?php echo $section ?></button>
<div class="content">
<button class="collapsible"><?php echo $subsection ?></button>
<form action="<?php echo htmlspecialchars(basename($_SERVER['REQUEST_URI'])); ?>" method="post">
<?php
//while loop start
?>
<form action="<?php echo htmlspecialchars(basename($_SERVER['REQUEST_URI'])); ?>" method="post">
<div class="form-group <?php echo (!empty($answer_err)) ? 'has-error' : ''; ?>">
<label><?php echo $question; ?></label>
<input type="text" name="answer[]" class="form-control" value="<?php echo $answer; ?>">
<span class="help-block"><?php echo $answer_err;?></span>
<input type="hidden" name="consideration_no[]" value="<?php echo $consideration_no; ?>"/>
<input type="hidden" name="dg_no" value="<?php echo $dg_no; ?>"/>
</div>
<?php
//while loop ends
?>
<input type="Submit" name = "$consideration_no[]" class="btn btn-primary" value="Submit">
Cancel
</form>
</div>
<?php
//while loop start
?>
<form action="<?php echo htmlspecialchars(basename($_SERVER['REQUEST_URI'])); ?>" method="post">
<div class="form-group <?php echo (!empty($answer_err)) ? 'has-error' : ''; ?>">
<label><?php echo $question; ?></label>
<input type="text" name="answer[]" class="form-control" value="<?php echo $answer; ?>">
<span class="help-block"><?php echo $answer_err;?></span>
<input type="hidden" name="consideration_no[]" value="<?php echo $consideration_no; ?>"/>
<input type="hidden" name="dg_no" value="<?php echo $dg_no; ?>"/>
</div>
<?php
//while loop ends
?>
<input type="Submit" name = "$consideration_no[]" class="btn btn-primary" value="Submit">
Cancel
</form>
</div>
<?php

How to add class dynamically using javascript

I want to add an class to an closest element of an click object.
If you see code below, I would like to add an class to .process-signs-direction-cover-button
There is an loop, so the above classes get's repeated. But I want to add an classes to closest() .process-signs-direction-cover-button of where I click.
See picture
MY php:
<div class="col-md-6 reduced_padding_col7">
<?php
$signs_to_direction_and_cover_process = $mysqli_scs->query("SELECT * FROM agsigns_db3.stock_stk where idstc_stk = ".$row['idstc_stk']." AND directioncolor_stk = 'Yellow' ");
$row_cnt = $signs_to_direction_and_cover_process->num_rows;
if($row_cnt > 0){
while ($row = mysqli_fetch_assoc($signs_to_direction_and_cover_process)) { ?>
<div class="col-md-4 thumbnail"><img src="../../css/sign-directions/<?php echo $row['directionimage_stk']; ?>" class="processing-signs-direction-cover-sign-direction-selection-process" id="<?php echo $row['id_stk']; ?>" />
<div class="col-xs-12 text-center signs-text">
<span class="current_stock_figure">
<?php echo $row['stock_stk'] == "" ? "N/A" : $row['stock_stk']; ?>
</span>
<span class="max_stock_figure">
<?php echo $row['maxlevel_stk']; ?>
</span>
</div>
</div>
<?php
}
}
?>
</div>
<div class="col-md-2 process-button">
<img src="../../css/buttons/process-signs-covered-disabled.png" id="" class="process-signs-direction-cover-button disabled_button" rel="<?php echo $row['signcode_sgn']; ?>" alt="covered"/>
<div class="options-remember-checkbox">
<input type="checkbox" class="rememberoptions" name="rememberoption" value="checked" > Remember Options<br>
</div>
MY JQuery
$(".processing-signs-direction-cover-sign-direction-selection-process").click(function() {
$(this).closest("process-button.process-signs-direction-cover-button").toggleClass("process");
});
Modify
Question Modified
Image code
In your jquery part use addClass instead of toggleClass .
$(".processing-signs-direction-cover-sign-direction-selection-process").click(function() {
$(this).closest("process-button.process-signs-direction-cover-button").addClass("process");
});

php echo codeigniter into javascript array

I have this bit of code in my codeigniter view:
<script>
var content = [];
content[<?php echo $storageItem["id"]; ?>] = "<?php echo form_open("/account/edititem", array("class" => "form-inline"), array("id" => $storageItem["id"], "item_loc" => "inventory", "acctid" => $acct_data->account_id)); ?>
<div class="panel-body">
<div class="row">
<div class="col-xs-2">
<strong>Refine level:</strong> <input type="number" name="refine" class="form-control" value="<?php echo $storageItem["refine"]; ?>" <?php if ($storageItem["type"] != 4 && $storageItem["type"] != 5) { echo "readonly"; } ?> />
</div>
<div class="col-xs-2">
<strong>Broken?:</strong> <input type="checkbox" name="attribute" class="form-control" value="1" <?php if ($storageItem["attribute"] == 1) { echo "checked"; } if ($storageItem["type"] != 4 && $storageItem["type"] != 5) { echo "disabled"; } ?> />
</div>
<div class="col-xs-2">
<strong>Bound?:</strong> <input type="checkbox" name="bound" class="form-control" value="1" <?php if ($storageItem["bound"] == 1) { echo "checked"; } ?> />
</div>
</div>
<br />
<div class="row">
<div class="col-xs-2">
<strong>Card 1:</strong> <input type="number" name="card0" class="form-control" value="<?php echo $storageItem["card0"]; ?>" <?php if ($storageItem["type"] != 4 && $storageItem["type"] != 5) { echo "readonly"; } ?> /></br>
</div>
<div class="col-xs-2">
<strong>Card 2:</strong> <input type="number" name="card1" class="form-control" value="<?php echo $storageItem["card1"]; ?>" <?php if ($storageItem["type"] != 4 && $storageItem["type"] != 5) { echo "readonly"; } ?> /></br>
</div>
<div class="col-xs-2">
<strong>Card 3:</strong> <input type="number" name="card2" class="form-control" value="<?php echo $storageItem["card2"]; ?>" <?php if ($storageItem["type"] != 4 && $storageItem["type"] != 5) { echo "readonly"; } ?> /></br>
</div>
<div class="col-xs-2">
<strong>Card 4:</strong> <input type="number" name="card3" class="form-control" value="<?php echo $storageItem["card3"]; ?>" <?php if ($storageItem["type"] != 4 && $storageItem["type"] != 5) { echo "readonly"; } ?> /></br>
</div>
</div>
<?php echo form_close(); ?>
</div>";
</script>
I create array named 'content' in javascript and then need to stuff almost an entire form into it to be able to create a child row in DataTables.
( for more information regarding what I've been trying to do and where these variables come from, see Datatables child row with PHP data from Codeigniter )
I've tried escaping single and double quotes (PHP complains about this), json_encode (PHP also complains about this as I still need the quotes and PHP interprets the quotes as the end of the json_encode), I've tried surrounding the entire value of the javascript array with '"' and "'", I've tried surrounding every line with ' '+ without success as well. How do I get this entire string into a form where javascript and PHP will parse it correctly and neither of them freak out?
Look at what you're doing:
<script>
var content = [];
content[<?php [..snip..] ?>] = "<?php [..snip..] ?>
^---start of javascript string
<div class="panel-body">
^---end of javascript string
^---start of another string
That means you have essentially:
variable = "some string stuff"variable-variable"more string stuff"
which is outright illegal JS.
The specific fix is to ESCAPE all of the strings in that html:
<script>
yadayada
<div class=\"panel-body\"> yada yadayada
^-----------^
But that doesn't fix the fact that this is incredibly bad code. You shouldn't be dumping loads of html into a JS string, and you should never be directly echoing text from PHP into a JS context.
If nothing else, why not generate all the content in PHP, then dump it all out as json?
<?php
$data = "blah blah blah blah";
?>
<script>
var content = <?php echo json_encode($data); ?>;

Using a name selector instead of an id

How can I change the following code to work off of a name selector instead of the id?
<div id="light" class="change_group_popup">
<a class="close" href="javascript:void(0)">Close</a>
JavaScript
$('.change_group').on('click',function(){
$("#light,.white_overlay").fadeIn("slow");
});
$('.close').on('click',function(){
$("#light,.white_overlay").fadeOut("slow");
});
UPDATE:
I added more of my code to show the loop to help explain what I am doing in more detail.
$runUsers2 = mysqli_query($con,"SELECT * FROM users ORDER BY id DESC");
$numrows2 = mysqli_num_rows($run2);
if( $numrows2 ) {
while($row2 = mysqli_fetch_assoc($run2)){
if($row2['status'] == "Approved"){
//var_dump ($row2);
$approved_id = $row2['user_id'];
$approved_firstname = $row2['firstname'];
$approved_lastname = $row2['lastname'];
$approved_username = $row2['username'];
$approved_email = $row2['email'];
if ($approved_firstname == true) {
echo "Name - ". $approved_firstname . " " . $approved_lastname . "</br>" .
"Username - ". $approved_username . "</br></br>"
?>
<div class="change_group_button">
<a class="change_group" href="javascript:void(0)">Change User Permission</a>
</div><br>
<div class="change_group_popup light">
<a class="close" href="javascript:void(0)">Close</a>
<div class="group_success" style="color: red;"></div><br>
<form class="update_group" action="" method="POST">
<div class="field">
<label for="group">Group</label>
<input type="hidden" value="<?php echo $approved_id; ?>" name="approved_id" />
<input type="hidden" value="<?php echo $approved_firstname; ?>" name="approved_firstname" />
<input type="hidden" value="<?php echo $approved_lastname; ?>" name="approved_lastname" />
<input type="hidden" value="<?php echo $approved_username; ?>" name="approved_username" />
<input type="hidden" value="<?php echo $approved_email; ?>" name="approved_email" />
<select name='group_id' required>
You can get any element by name attribute by:
$('[name="someName"]')
Use DOM traversal functions to find the related element.
$(".change_group").click(function() {
var light = $(this).closest(".change_group_button").nextAll(".light").first(); // Find the next .light DIV after the button
light.add($(".white_overlay")).fadeIn("slow");
}):

Categories

Resources