Deleting divs via PHP - php

I'm making a To do application with PHP (school assignment)
At this moment, I can add tasks to the list. Deleting is the next problem.
The "problem" is that I HAVE to use PHP to delete the corresponding div. (It needs to delete the div i'm clicking)
My question: what's the best practice to do that? (Working with a specific number maybe?)
Index.php
<div class="container">
<form action="/Periodeopdracht/index.php" method="POST">
<div class="headerToDo">
<input class="addText title" type="text" value="Click to add a task" name="nextToDo">
<input class="clickablePlus" type="submit" value="+" name="submit"></div>
</form>
<?php if(!$empty): ?>
<?php foreach ($_SESSION["todoList"] as $_SESSION["key"] => $toDo): ?>
<div class="toDo">
<form action="/Periodeopdracht/index.php" method="POST">
<button value="<?php echo $_SESSION["key"] ?>" name="done" class="done" type="submit" >V</button>
<div value="<?php echo $_SESSION["key"] ?>" class="textToDo"><?= $toDo ?></div>
</form>
</div>
<?php endforeach ?>
<?php endif ?>
</div>
application.php:
<?php
session_start();
$GLOBALS["empty"] = true;
$_SESSION['todoList'] = isset($_SESSION['todoList']) ? $_SESSION['todoList'] : array();
if(isset($_POST["submit"]))
{
$empty = false;
array_unshift($_SESSION['todoList'], $_POST["nextToDo"]);
}
if (isset($_POST['done'])) {
foreach ($_SESSION["todoList"] as $key => $toDo) {
if ($toDo == $_POST['done']) {
unset($_SESSION['todoList'][$key]);
break;
}
}
}
?>

foreach ($_SESSION["todoList"] as $key => $toDo)
then use $key as the value of your "done" button, When processing you can just unset($_SESSION['todoList'][$key])
you will have to check that the key is valid coming from the post though.

Add a <hidden> field to each toDo with, the id of the toDo, then you will know what to remove from the toDo list.

In addition to what exussum was stating. U'll need to define in your HTML which todo item u want to delete. Atm your just posting an empty button. Change your html to something like this:
<div class="toDo">
<form action="/../index.php" method="POST">
<button name="done" class="done" value="<?= $toDO ?>" type="submit">V</button>
<div class="textToDo"><?= $toDo ?></div>
</form>
</div>
Now if you post the form the variable $_POST['done'] will contain the task that is completed. Now the check this :
<?php
if (isset($_POST['done']) {
foreach ($_SESSION["todoList"] as $key => $toDo) {
if ($toDo == $_POST['done']) {
unset($_SESSION['todoList'][$key]);
break; //terminates the loop as we found the correct item
}
}
$empty = empty($_SESSION["todoList"]);
}
I'm not a huge fan of posting raw values to check whether items need to be deleted.
Its beter to work with (unique) id's if you are using these.

Related

PHP CodeIgniter: Updating a dynamic array bound to an input field

What I'm about to show might be the most horrific code in existence, so be prepared. I'm new to PHP and received a CodeIgniter project. Here we go:
In my edit_article view, I dynamically generate <input> fields and make them accessible to the controller by posting them as an array, notice name="pricelevel_checked_array[]":
<form id="form-work" class="form-horizontal" role="form" autocomplete="off" method="post">
<!-- excluded code to display form content -->
<?php
$pricelevel_array = array();
$count = 0; ?>
<?php foreach($array_used_for_loop as $item_used_for_loop): ?>
<?php $article_group_price = ""; ?>
<!-- excluded code to fill $article_group_price -->
<div class="col-sm-2">
<div class="checkbox">
<span class="bg-transparent left">
<input type="checkbox" data-init-plugin="switchery" data-size="small" data-color="primary" id="<?=$count?>"
<?php if($article_group_price !== ""): ?>
<?php array_push($pricelevel_array, 1); ?>
checked="checked"
<?php else: array_push($pricelevel_array, 0); ?>
<?php endif; ?>
onchange="groupprice_active_changed(this)"/>
</span>
</div>
</div>
<input hidden type="number" id="pricelevel_checked_array" name="pricelevel_checked_array[]" value="<?=$pricelevel_array[$count];?>">
<?php $count++; ?>
<?php endforeach; ?>
</form>
As you can see, I fill that array with 1's or 0's depending on the value of $article_group_price (I get these values from the controller and originally the database).
It all works fine upon first loading the view and the array is filled correctly, but I can't seem to update the array when I check- or uncheck a checkbox.
I've tried to do this quick and dirty using javascript onchange="groupprice_active_changed(this)" where I would use the $count variable to change the index of the array, but unfortunatly that didn't work out since I only get one value and not the entire array:
<script>
function groupprice_active_changed(obj) {
if($(obj).is(":checked")){
alert("Yes checked");
var input_value_array = document.getElementById('pricelevel_checked_array').value;
console.log(input_value_array);
for (index = 0; index < input_value_array.length; index++) {
console.log(input_value_array[index]);
}
}else{
alert("not checked")
}
}
</script>
How can I best update this array or change my code so I can post the dynamic generated checkboxes to the controller? Another problem is that I need the checkbox-id in the controller, even if it's false. And that the browser doesn't post an unchecked checkbox value. So, just passing the checkboxes isn't an option.
I'm of course prepared to post more code.
Thank you
Disclaimer: Please no steal
View: Complete code
Controller: Complete code
Edit 1: Changed 'php' to 'the browser' in the last section
Edit 2: Added as good as the whole code because filtering out will only make it more difficult.
One technique I have see used to make checkboxes behave better is to use
a hidden input with the same name as the checkbox. Put the hidden input before
the checkbox. If the checkbox is not checked, the value of the hidden input
gets sent. If you check the checkbox then the checkbox value overrides the hidden input.
This works because only one of the values is sent. The browser sends the later one.
Take a look at the following example.
<html>
<head>
</head>
<body>
<div>
<form method="post">
<input type="hidden" name="foo" value="off">
<input type="checkbox" name="foo" /> Foo
<input type="submit" />
</form>
</div>
</body>
</html>
<?php if ( ! empty($_POST) ) : ?>
<div> Hello </div>
<div>
Checkbox is <?= $_POST['foo']?>
</div>
<?php endif ?>
I eventually made the decision to drop the whole array approach and follow the KISS principle by passing my index to the controller. I use these indexes to only save the rows that are checked. Thanks to #ryantxr for showing me that I was overthinking all this.
v_edit_article
<?php $index = 0; ?>
<?php foreach($array_used_for_loop as $item_used_for_loop): ?>
<?php $article_group_price = ""; ?>
<!-- excluded code to fill $article_group_price -->
<div class="col-sm-2">
<div class="checkbox">
<span class="bg-transparent left">
<input type="checkbox" name="group_active[]" data-init-plugin="switchery" data-size="small" data-color="primary" value="<?=$index;?>"
<?php if($article_group_price !== ""): ?>
checked="checked"
<?php endif; ?>/>
</span>
</div>
</div>
</div>
<?php $index++; ?>
<?php endforeach; ?>
admin (controller)
public function edit_article($id) {
// Excluded code
$group_prices_active = array();
if(isset($data['group_active'])):
echo "<script>console.log('GROUP_ACTIVE ".print_r($data['pricelevel_checked'])."');</script>";
foreach($data['group_active'] as $value):
array_push($group_prices_active, $group_prices[$value]);
endforeach;
echo "<script>console.log('GROUP_PRICES_ACTIVE ".print_r($group_price_active)."');</script>";
unset($data['group_active']);
endif;
// Excluded code
$this->m_articles->edit_article($data, $id, $article_types, $group_prices_active);
$this->session->set_flashdata('succes', $this->lang->line('edit_success'));
redirect('/administrator/articles', 'refresh');
}

using the export button function to another php file

This is the form.php file and i would like to put export button file to another php file. I am still rocky for php language.
form php
<form action="<?php echo url_for("attendance/viewAttendanceRecord"); ?>" id="reportForm" method="post" name="frmAttendanceReport">
<fieldset>
<ol>
<?php
if ($form->hasErrors()) {
echo $form['employeeName']->renderError();
}
?>
<?php echo $form->render(); ?>
<?php echo $form->renderHiddenFields(); ?>
<li class="required">
<em>*</em> <?php echo __(CommonMessages::REQUIRED_FIELD); ?>
</li>
</ol>
<p class="formbuttons">
<input type="button" class="" id="btExport" onclick='myfunction()' value="<?php echo __('Export') ?>"/>
I want to use export function in this action.php file
action.php
if($post['export'] == '1')
{
//statement
}
Php uses name attribute of the elements in order to build $_POST array. So add name attribute to button along with other input elements as follows.
<input type="submit" id="btExport" name="btExport" value="<?php echo __('Export') ?>"/>
in action.php do something like the following to handle posted values.
if($_POST["btExport"])
{
//statement
}
or you can also check if $_POST is empty or not as follows
if (!empty($_POST))
{
//statement
}

insert form to database

i have program codeigniter anda i want to insert form to database.
code view:
<form target="paypal" method="post">
<div class="field1">
<div class="field">
<label>Nama</label>
<input placeholder="Nama" name="nama" type="text">
</div>
<div class="field">
<label>No. HP</label>
<input placeholder="No. HP" name="handphone" type="text">
</div>
<div class="field">
<label>Alamat</label>
<input placeholder="alamat" name="alamat" type="text">
</div>
<div class="field">
<label>Jumlah</label>
<div class="selectbox">
<select name="jumlah" id="">
<?php for ($i=1; $i <= 20; $i++): ?>
<option value="<?php echo $i; ?>"><?php echo $i; ?></option>
<?php endfor; ?>
</select>
</div>
</div>
<button type="submit" name="submit" class="ui teal button order-button">Order now</button>
</div>
</form>
code controller
function simpanOrder()
{
$this->load->model("M_order");
$data['nama'] = $_POST['nama'];
$data['handphone'] = $_POST['handphone'];
$data['alamat'] = $_POST['alamat'];
$data['jumlah'] = $_POST['jumlah'];
if($this->input->post('submit')){
$this->M_order->insert($data);
}
}
when i click submit data not insert to database. so can you help me with this code problem? thanks.
Your form doesn't have an action, and therefore may not be going to the function you want it to. (/controller/function)
<form target="paypal" method="post">
Also, instead of using a button to submit the form - try using <input type="submit"...
Using the <button>, in some browsers, you would have "submit" submitted, in others, "Order now".
If the above doesn't work - check your SQL.
As a side note, CodeIgniter has a form helper and a form_validation library which are quite useful if you're already using CodeIgniter. That won't fix your problem but it's just something I felt I would point out.
See:
http://ellislab.com/codeigniter%20/user-guide/libraries/form_validation.html
http://ellislab.com/codeigniter/user-guide/helpers/form_helper.html
Call model from controller. and write below code in model.
$data = array(
'handphone' => $this->input->post('handphone'),
'alamat' => $this->input->post('alamat'),
)
In this array key is database columnname.
$this->db->insert(yourtablname, $data);
$insert_id = $this->db->insert_id();
You need to define action attribute in form tag where you will provide controller name and method name like this
<form action="<?php echo site_url('controllername/simpanOrder')?>" method="post">
After posting you can debug your code like this
$post = $this->input->post();
echo '<pre>';
print_r($post);
Then
if($this->input->post('submit')){
$this->M_order->insert($data);
}
And finally
echo $this->db->last_query();
This will display you the last query run.

Add list item every time i click submit

I want a script which will echo a text from a form to a div tag every time i click the submit button.
i was able to do that in no time but i want the text to still be displayed in the div even when i submit another. i want every new submitted text to create a list. adding it to a previous list.
may be this got to do with database but i will like to know as every time i click the submit i only get the current text been submitted.
example of such script
<?php
$text = $_POST['text'];
?>
<html>
<div>
<?php echo "<ul>";
echo "<li>".$text."</li>";
echo "</ul>";
?>
</div>
<form method="POST" action="<?php echo $_SERVER['PHP_SELF'];?>">
Name: <input type="text" name="text" /><br/>
<input type="submit" value="Submit"/>
</form>
</html>
i want to just be adding entries to the <li> list every time i click submit.
I'm happy you're having fun. Here's a quick "starter for 10" :)
<?php
$items = array();
if('POST' === $_SERVER['REQUEST_METHOD']) {
if( ! empty($_POST['item'])) {
$items[] = $_POST['item'];
}
if(isset($_POST['items']) && is_array($_POST['items'])) {
foreach($_POST['items'] as $item) {
$items[] = $item;
}
}
}
?>
<html>
<head>
<title>Demo</title>
</head>
<body>
<?php if($items): ?>
<ul>
<?php foreach($items as $item): ?>
<li><?php echo $item; ?></li>
<?php endforeach; ?>
</ul>
<?php endif; ?>
<form method="post">
<input type="text" name="item" />
<input type="submit" value="Add Item" />
<?php if($items): ?>
<?php foreach($items as $item): ?>
<input type="hidden" name="items[]" value="<?php echo $item; ?>" />
<?php endforeach; ?>
<?php endif; ?>
</form>
</body>
</html>
You could use sessions to handle this if the list is temporary:
<?php
session_start();
if(isset($_POST['text']) && trim($_POST['text']) != "")
{
// add to a session array
$_SESSION['text'][] = $_POST['text'];
}
?>
<html>
<div>
<ul>
<?php if(isset($_SESSION['text']) && !empty($_SESSION['text'])): foreach($_SESSION['text'] AS $text): ?>
<li><?php echo $text; ?></li>
<?php endforeach; endif; ?>
</ul>
?>
<!-- rest of your html here -->
thought I would chime in too. This is a simple solution that will work only in the current instance of a page.
<?php
if ( isset( $_POST['text'] ) ) { # Find out if the form had been submitted
$text = $_POST['text']; # If so then store the submitted text in the $text var
if ( isset( $_POST['previous'] ) ) { # Find out if there were any previous inputs
$current = $_POST['previous'] . "," . $_POST['text']; # If there were then pop the latest one on the end of the previous ones with a comma and make that our current set of text
} else {
$current = $_POST['text']; # Otherwise the current set of text just comprises our most recently input text
}
}
?>
<html>
<div>
<?php
if ( isset( $_POST['text'] ) ) { # Find out if some text was input
$text_arr = explode(",", $current); # If it was then take our current set of text and make an array from it
echo "<ul>"; # Start the list
foreach ( $text_arr as $text ) { # For each item of text that has previously been input
echo "<li>".$text."</li>"; # Print out the list item with the text in it
}
echo "</ul>"; # End our list
}
?>
</div>
<form method="POST" action="<?php echo $_SERVER['PHP_SELF'];?>">
<?php if ( isset( $_POST['text'] ) ) { ?> # If the previous form submitted some text
<input type="hidden" name="previous" value="<?php echo $current ?>" /> # Store it in a hidden input field to be submitted later
<?php } ?>
Name: <input type="text" name="text" /><br/>
<input type="submit" value="Submit" />
</form>
</html>
So this will do what you want but without any storing into a database. If storing into a database is what you want to do then you might want to do some research into MySQL or some other method of permanently storing list items.
Hope mine has been of some help, I'm sure many others have popped an answer on while I have been typing this...
You would need to keep adding to a session variable and best to use an array.
Like so;
<?php
session_start(); // This is needed to keep your session
if(!isset($_SESSION['text'])){
// set session array if not already set previously
$_SESSION['text'] = array();
}
if($_SERVER['REQUEST_METHOD'] == 'POST' && strlen($_POST['text']) > 0){
// add text to session array and escape for security
$_SESSION['text'][] = htmlspecialchars($_POST['text'], ENT_QUOTES);
}
?>
<html>
<div>
<ul>
<?php foreach($_SESSION['text'] AS $text): ?>
<li><?php echo $text; ?></li>
<?php endforeach; ?>
</ul>
</div>
<form method="POST">
Name: <input type="text" name="text" /><br/>
<input type="submit" value="Submit"/>
</form>
</html>
Edit: This only works for the current session, if you want to come back later and see the same list. You would need to store the values somewhere like a database.

Deleting objects using checkboxes with Codeigniter

I have read many post like this but have failed to find my particular situation.Trying to delete the selected checkbox. right now you can submit the form and it takes you to all the right pages except it doesn't actually delete anything.
Here is my controller info
function deleteFolder() {
if(array_key_exists('deleteMe',$_POST)) {
$checkbox = $this->input->post['checkbox'];
$this->index_model->deleteFolder($checkbox);
}
$this->folderdeleted();
}
Here is my Model
function deleteFolder($checkbox) {
$this->db->where('folderName', 'folderName');
$this->db->delete('senior', $checkbox);
return;
}
Here is my View
<!DOCTYPE html>
<?php $this->load->view('partials/page_head'); ?>
<body>
<div id="container">
<div id="top">
<div class="topcenter">
<h2><a class="homebtn" href="<?php echo base_url();?>">Home</a></h2>
</div>
<div class="navdescription"><span>Delete Page</span></div>
</div>
<div class="projectFolders">
<?php foreach($foldername as $row) { ?>
<div class="folder">
<button><?php echo $row->folderName; ?></button>
<div class="delete">
<form name="delete" method="post" action="<?php echo base_url(); ?>index.php/home/folderdeleted">
<p>
<input type = "checkbox" id = "check_<?php echo $row->folderName; ?>"/>
<?php echo form_submit('deleteFolder', 'Delete'); ?>
</p>
</form>
</div>
</div>
<?php } ?>
</div>
</div><!-- End of container div -->
</body>
</html>
There are several errors in your code. I'm not sure whether I've found all of them and whether the code will work.
The controller should be:
function deleteFolder() {
if($this->input->post('checkbox') !== false) {
$checkbox = $this->input->post('checkbox');
$this->index_model->deleteFolder($checkbox);
}
$this->folderdeleted();
}
The model should be:
function deleteFolder($checkbox) {
$this->db->where('folderName', $checkbox);
$this->db->delete('senior');
return;
}
The input tag in the view should be:
<input name="checkbox" value="<?php echo $row->folderName; ?>" type = "checkbox" id = "check_<?php echo $row->folderName; ?>"/>
A little warning for checkboxes: if they aren't checked, you won't find anything in the $_POST variable.

Categories