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']?>">
Related
I'm pretty new with PHP, so help please.
I need a web page in php with a checkbox. That page should refresh itself each time I do an action to the checkbox (so for both check or uncheck). Once it’s refreshed the page should keep the latest value of the checkbox.
I tried the following example modifying another code I took from StackOverflow, but it doesn’t works as I wish.
Any suggestion?
<?php
session_start();
$checked = "";
if($_SESSION['myaction'] != $_SESSION['value'])
{
if(isset($_POST['sharks']))
{
$_SESSION['value'] = $_POST['sharks'];
}
else
{
$_SESSION['value'] = '';
echo ":(";
}
$_SESSION['myaction'] = $_SESSION['value'];
}
?>
<form action="" method="POST">
<?php
print '<input name="sharks" type="checkbox" value="1" id="sharks" ';
if ($_SESSION['value'] == 1)
{
echo "checked='checked'";
}
$myaction = 2;
print ">";
?>
</form>
<form method='POST'>
<input name='sharks' type='checkbox' value='1' id='sharks' />
</form>
Some simpple, vanilla, Javascript that makes use of the localStorage ( or sessionStorage ). The click handler will set the checked status and on page load that value will help re-check, or not, the checkbox. Javascript is intended for this sort of purpose - though it is entirely possible to use PHP to re-check the checkbox when the page reloads provided it has some means to check a value against a stored value or a form submission.
document.addEventListener('DOMContentLoaded',()=>{
let chk=document.querySelector('input[type="checkbox"][name="sharks"]');
chk.checked=localStorage.getItem( chk.name )==null || localStorage.getItem( chk.name )=='false' ? false : true;
chk.addEventListener('click',e=>{
localStorage.setItem( chk.name, chk.checked )
location.reload();
});
});
Don't use a checkbox if you don't want the behaviour of a checkbox.
If you are submitting data, use a submit button. Users expect submit buttons to trigger a reload of the page.
<?php
$current_state = get_state_from_database_or_session_or_whatever();
if (isset($_POST['new_state'])) {
if ($_POST['new_state']) == "on") {
$current_state = "off";
} else {
$current_state = "on";
}
update_datebase_or_session_or_whatever_with_new_state($current_state);
}
$other_state = "off";
if ($current_state == "off") {
$other_state = "on";
}
?>
<p>The current state is <?php echo $current_state; ?></p>
<form method="post">
<button name="state" value="<?php echo $other_state; ?>">Set state to <?php echo $other_state; ?></button>
</form>
What you need to is pretty simple- assuming you are submitting the form on the same page.
<?php
$filterUsers=array();
if(isset($_GET['users'])){
foreach($_GET['users'] as $key){
$filterUsers[]=$key;
}
function valueInFilter($value){
if(in_array($value, $filterUsers)){
echo "checked";
}else{
echo "";
}
}
?>
<html>
<head>Filter </head>
<body>
<form method="get" action="<?php echo
htmlspecialchars($_SERVER["PHP_SELF"]); ?>">
<input type="checkbox" name="users[]" value="john" id="1" <?php
valueInFilter("john",$filterUsers) ?>>
<label for="1"> John doe</label><br>
<input type="checkbox" name="users[]" value="john" id="2" <?php
valueInFilter("mayor",$filterUsers) ?>>
<label for="2"> John Mayor</label><br>
</form>
</body>
</html>
This is not an job for PHP like Professor Abronsius wrote.
Write it in JavaScript like this:
(() => {
// on page reloaded
const checkboxNode = document.getElementById('sharks')
if (localStorage.getItem('sharkCheckBox')) {
// the checkbox is stored as CHECKED
// e.g. check the checkbox again or what ever:
checkboxNode.checked = true
} else {
// the checkbox is stored as NOT checked
}
// handle the click
checkboxNode.addEventListener('click', function() {
// get the checkbox status
const isChecked = this.checked
// store the checked status inside the browser cache
localStorage.setItem('sharkCheckBox', isChecked)
// there are several ways to to an page reload. Here an example
// see details here https://stackoverflow.com/a/39571605/7993505
location.reload()
})
})()
I'm trying to auto submit a form when a user clicks checkbox select (with ajax). I want to prevent the default reload, and then attempt to use the category checkbox values to repopulate the relevant business names, which the user will be able to select to retrieve the full company details.
Quite frankly, it's been driving me a bit mad! I've tried both post and get methods, and 100 other workarounds and I just can't get it to work
If I remove the e.preventDefault(); from my on submit function then the page reloads and I get the correct info across both category and name via $_GET. But problem I have is getting the ajax data passed back to the var_dump($_GET). It always stays empty aside from the URL.
Am I going about this in the wrong way?
Here's my form:
<form id="businessSearch" action="" type="get" enctype='multipart/form-data'>
<div class="col-md-6 business-cat">
<h2>Business Category</h2>
<div class="business-inner">
<input id="category" class="main" <?php if ( !isset($_GET['category']) || ($_GET['category'] == 'All')) { echo 'checked'; } ?> type="checkbox" name="category" value="All" /> All <br>
<?php foreach($data['businessCats'] as $category) : ?>
<input id="category" class="main" <?php if ( isset($_GET['category']) && ($_GET["category"] == $category->BusinessCategory)) { echo 'checked'; } ?> type="checkbox" name="category" value="<?php echo $category->BusinessCategory; ?>"> <?php echo $category->BusinessCategory; ?><br>
<?php endforeach; ?>
</div>
</div>
<div class="col-md-6 business-name">
<h2>Company Name</h2>
<div class="business-inner">
<?php if( isset($_GET['category']) && ($_GET['category'] != 'All')) : ?>
<?php foreach($data['businessCategoryListing'] as $businessCatListing) : ?>
<input id="name" class="sub" <?php if (isset($_GET["name"]) && ($_GET["name"] == $businessCatListing->company_name)) { echo 'checked'; } ?> type="checkbox" name="name" value="<?php echo $businessCatListing->company_name; ?>"> <?php echo $businessCatListing->company_name; ?><br>
<?php endforeach; ?>
<?php else: ?>
<?php foreach($data['getAllBusinessListings'] as $getAllBusinessListings) : ?>
<input id="name" class="sub" <?php if (isset($_GET["name"]) && ($_GET["name"] == $getAllBusinessListings->company_name)) { echo 'checked'; } ?> type="checkbox" name="name" value="<?php echo $getAllBusinessListings->company_name; ?>"> <?php echo $getAllBusinessListings->company_name; ?><br>
<?php endforeach; ?>
<?php endif; ?>
</div>
</div>
</form>
<?php if ( isset($_GET['category']) && isset($_GET['name']) ) : ?>
<div class="clearfix"></div>
<div class="col-md-12 business-details">
<h2>Details</h2>
<div class="business-inner">
<h2><?php echo $data['businessListing']->BusinessName ?></h2>
<?php echo $data['businessListing']->BusinessDescription . '<br>' . $data['businessListing']->BusinessPhone . '<br>' . $data['businessListing']->BusinessWebsite . '<br>' . $data['businessListing']->BusinessAddress1 . '<br>' . $data['businessListing']->BusinessGrid . '<br>' ; ?>
</div>
</div>
<script>
$('input.main, input.sub').on('change', function() {
$('#businessSearch').trigger('submit');
});
$(document).ready(function () {
$('#businessSearch').on('submit', function(e) {
e.preventDefault();
var category = $('#category:checked').val(),
name = $('#name:checked').val();
$.ajax({
type: 'get',
data: { ajax: 1,category: category, name: name},
success: function(response){
//$('#response').text('category : ' + response);
}
});
});
});
</script>
I can see my output in the network tab in
I just cannot get it to filter back in the $_GET var_dump and then get the results to update correctly on my page whilst preventing the page reload.
Finally, here is how I'm calling that data from my db
public function getBusinessByCategory() {
$category = isset($_GET['category']) ? $_GET['category'] : '';
$this->db->query('SELECT * FROM business_directory WHERE category = :category and publish_status = "live" ORDER BY company_name ASC');
$this->db->bind(':category', $category);
$results = $this->db->resultSet();
return $results;
}
Can anyone give any pointers? I'm really stuck, and my head is about to explode!!!
If you want submit a form without reload the page then first do not user button type "submit" in HTML form. Instead of that use normal button and execute your ajax call when user click on that button.
If you will submit button then it will reload the page and it's default behaviour of the submit button type.
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.
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.
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.