Add list item every time i click submit - php

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.

Related

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
}

Deleting divs via 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.

Codeigniter - How to store the test selected answer after pagination

I am creating a test system, this is my first codeigniter project. I am able to make the pagination, so each page will only display one question and click next button to go next question. Now my problem is when user answer one question and go next but when he/she go back to previous question the answer doesn't appear there. Below are my code:
Controller.php
...
$config['per_page'] = 1;
$page = ($this->uri->segment(4)) ? $this->uri->segment(4) : 0;
$data['question'] = $this->TestModel->getAllQuestion($id, $page);
$data['links'] = $this->pagination->create_links();
$this->load->view('TestView',$data);
TestView.php
<form name="testform" action="" method="post">
<div class="bs-question">
<?php
foreach ($question as $row)
{
?>
<h3><?php echo $row->question; ?></h3>
<br/>
<br/>
<div style="padding-left:20px;">
<?php
foreach ($answer as $an)
{
?>
<div class="radio">
<label>
<input type="radio" name="optionsRadios" id="optionsRadios1" value="<?php echo $an->aid?>"><?php echo $an->answer ?>
</label>
</div>
<?php } ?>
</div>
<?php
}
?>
<br/>
<br/>
<?php echo $links; ?>
<div class="clearfix"></div>
</div>
</div>
</form>
How can I store the selected answer, when user go back previous/next qeustion?
What I do:
$('#next a').click(function () {
var link = $(this).get(0).href; // get the link from the DOM object
var form = $('#testform'); // get the form you want to submit
var segments = link.split('/');
// assume the page number is the fifth parameter of the link
$('#page').val(segments[3]); // set a hidden field with the page number
form.attr('action', link); // set the action attribute of the form
form.submit(); // submit the form
return false; // avoid the default behaviour of the link
});
In my controller:
if($this->input->post('optionsRadios')){
$s_v = array(
'questionno'. $this->input->post('qnsid') => $id = $this->input->post('qnsid'),
'optionsRadios'. $this->input->post('qnsid') => $id = $this->input->post('optionsRadios')
);
$this->session->set_userdata($s_v); //add the ID to your session
}
In my view:
<input type="radio" name="optionsRadios" <?php if( $this->session->userdata('optionsRadios'.$question->qid) && $this->session->userdata('optionsRadios'.$question->qid) == $row['aid'] ) echo "checked";
else echo ""; ?> value="<?php echo $row['aid']?>">

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.

Avoid code re-use when handling form validation

I am generating form and handling the submit event in the same file.
If user has not entered the title, I want to display the form again and include an error message (e.g. "You forgot the title.").
That means that I have to duplicate code twice - once to diplay empty form and second to display form with body and ask user to enter title:
<?php if(strlen(strip_tags($_POST['posttitle'])) == 0):
// Display the form with question body that user has entered so far and ask user to enter title.
?>
<label for="title"><b>Title:</label><br/>
<input type="text" name="posttitle" id="posttitle" />
<?php endif;?>
<?php elseif ( 'POST' == $_SERVER['REQUEST_METHOD'] && !empty( $_POST['action']) && $_POST['action'] == 'post') : ?>
<!-- Everything ok - insert post to DB -->
<?php else :
// just display form here (again ouch!)
<label for="title"><b>Title:</label><br/>
<input type="text" name="posttitle" id="posttitle" />
?>
I would do it like this:
If REQUEST_METHOD is POST I will validate the input and collect messages in an array ($errors in my code).
Then I would just print the form and if there was an error the code will print it.
<?php
$errors = array();
function print_value_for($attr) {
if (isset($_POST[$attr]))
echo $_POST[$attr];
}
function print_error_for($attr) {
global $errors;
if (isset($errors[$attr]))
echo $errors[$attr];
}
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
// do validation here and add messages to $errors
// like $errors['posttitle'] = "The title you entered is bad bad bad";
if (empty($errors)) {
// update database and redirect user
}
}
?>
<!-- display the form and print errors if needed -->
<form>
<?php print_error_for('posttitle'); ?>
<input name="posttitle" type="text" value="<?php print_value_for('posttitle') ?>">
<?php print_error_for('postauthor'); ?>
<input name="postauthor" type="text" value="<?php print_value_for('posttitle') ?>">
<?php print_error_for('postbody'); ?>
<textarea name="postbody">
<?php print_value_for('posttitle') ?>
</textarea>
<input type="submit">
</form>
PS. Consider using MVC to separate code and templates.
Here is a quick way to do that.
<form>
<input type="text" name="title" value="<?php echo $_REQUEST['title']; ?>"/>
<input type="text" name="field_a" value="<?php echo $_REQUEST['field_a']; ?>"/>
....
</form>
But I can also advise you to display a var called $title which is the result of a check on $_REQUEST['title].
You could use an output buffer to grab the form and then assign it to a variable like so:
<?php
ob_start();
include('path/to/your/form');
$form = ob_get_flush();
// then later you can just go
print $form;
?>
Hope this helps
When you display the form, use the possibly empty $_POST values as default field values for both the title and question body. If either is empty, the form will display the second time with the other already filled in:
<?php
$message = "";
if (empty($_POST['title'])) $message .= " Please enter a title.";
if (empty($_POST['body'])) $message .= " Please enter a body.";
?>
<form action='me.php'>
<input name='title' type='text' value='<?php if (!empty($_POST['title'])) echo htmlentities($_POST['title'], ENT_QUOTES); ?>' />
<textarea name='body'><?php if (!empty($_POST['body'])) echo $_POST['body']; ?></textarea>
</form>
Read this MVC
Your can write form in view, handler in controller, and business logic in model

Categories