checked checkbox will remain through pagination - javascript

i am doing a php script wherein I need to remember the checked checkbox and save it all the database. Unfortunately, my code save only the current page where I checked the checkbox but the other checked box became unchecked.
Example In Page 1 I checked 3 items, on the second page I checked I tem. When I click the submit button I only got the checked item of the current page. And when I go back to the previous page the item that I checked became unchecked.How can I preserved and save the value of my checked checkbox through pagination?
here is my code for CreateTest.php
<html>
<body>
<?php
ob_start();
session_start();
include("connect.php");
error_reporting(0);
$item_per_page=10;
$results = mysqli_query($con,"SELECT COUNT(*) FROM tblitem");
$get_total_rows = mysqli_fetch_array($results); //total records
//break total records into pages
$pages = ceil($get_total_rows[0]/$item_per_page);
//create pagination
if($pages > 1)
{
$pagination = '';
$pagination .= '<ul class="paginate">';
for($i = 1; $i<=$pages; $i++)
{
$pagination .= '<li>'.$i.'</li>';
}
$pagination .= '</ul>';
}
?><!DOCTYPE html>
<script type="text/javascript">
$(document).ready(function() {
$("#results").load("fetch_pages.php", {'page':0}, function() {$("#1-page").addClass('active');}); //initial page number to load
$(".paginate_click").click(function (e) {
$("#results").prepend('<div class="loading-indication"><img src="ajax-loader.gif" /> Loading...</div>');
var clicked_id = $(this).attr("id").split("-"); //ID of clicked element, split() to get page number.
var page_num = parseInt(clicked_id[0]); //clicked_id[0] holds the page number we need
$('.paginate_click').removeClass('active'); //remove any active class
//post page number and load returned data into result element
//notice (page_num-1), subtract 1 to get actual starting point
$("#results").load("fetch_pages.php", {'page':(page_num-1)}, function(){
});
$(this).addClass('active'); //add active class to currently clicked element (style purpose)
return false; //prevent going to herf link
});
});
</script>
<form name="myform" action="CreateTest.php" method="POST" onsubmit="return checkTheBox();" autocomplete="off">
<body>
<?php
if(isset($_POST['save'])){
$testPrice = $_POST['testPrice'];
$testName = $_POST['testName'];
$items = $_POST['items'];
$quantity = $_POST['quantity'];
$testDept = $_POST['testDept'];
$measurement = $_POST['measurement'];
global $con;
Tool::SP_Tests_Insert(strip_tags(ucwords($testName)), $testPrice, $testDept);
$result = mysqli_query($con, "SELECT MAX(TestID) FROM lis.tbltests");
$data= mysqli_fetch_array($result);
$testID=$data[0];
foreach ($items as $key => $value){
$checkedItem[] = $value;
echo $value, " | ",$quantity[$key], " | ",$measurement[$key], "<br>";
mysqli_query($con,"INSERT INTO tbltestitem (TestID, ItemID, ItemQuantity, ItemMeasurement) VALUES ($testID, $value, '$quantity[$key]', '$measurement[$key]')");
}
echo "<script type='text/javascript'>alert('Succesfully added test!')</script>";
$site_url = "tests.php";
echo "<script language=\"JavaScript\">{location.href=\"$site_url\"; self.focus(); }</script>";
}else if(!isset($_POST['save'])){
$selectDept='';
$result= mysqli_query($con,"select * from tbldepartment");
$selectDept.="<option value=''>Select Department:</option>";
while($data = mysqli_fetch_array($result)){
$selectDept.="<option value='{$data['DeptID']}'>{$data['DeptName']}</option>";
}
?>
<td style="vertical-align: top;">
<body>
<div id="container" align="center">
<div id="title">Create Test</div>
<div id="a">Input Test Name:</div><div id="b"><input type="text" name="testName" id="myTextBox" onkeyup="saveValue();" ></div>
<div id="a">Input Test Price:</div><div id="b"><input type="number" name="testPrice"></div>
<div id="a">Select Department:</div><div id="b"><select name="testDept" ><?php echo $selectDept; ?></select></div>
<div id="results"></div><div id="a"><?php echo $pagination; ?></div>
<div align="right" style="padding: 10px;"><input type="submit" name="save" value="Submit"></div> </div>
<?php
}
?>
</body>
</html>
This is my fetch_pages.php code.
this php page help me to keep the textbox values through pagination through jquery it will be loaded without going the another page of pagination
<?php
include("connect.php");
require_once('classes/tool.php');
$item_per_page=10;
//sanitize post value
$page_number = $_POST["page"];
//validate page number is really numaric
if(!is_numeric($page_number)){die('Invalid page number!');}
//get current starting point of records
$position = ($page_number * $item_per_page);
//Limit our results within a specified range.
$results = mysqli_query($con,"SELECT * FROM tblitem ORDER BY ItemID ASC LIMIT $position, $item_per_page");
$connection=mysqli_connect($dbhost,$dbuser,$dbpass,$dbname);
$selectMeasure='';
$measurements = Tool::SP_Measurement_Select();
foreach($measurements as $measure) {
$selectMeasure.='<option value=' . $measure['MeaName'] . '>' . $measure['MeaName'] . '</option>';
$i=0;
while($item = mysqli_fetch_array($results))
{
echo "<div id='a'><input type='checkbox' name='items[$i]' id='item[]' value='". $item['ItemID'] ."' >".$item['ItemName']."</div>";
echo "<div id='b'><input type='number' name='quantity[$i]' class='quantity' /></div>";
echo "<div id='b'><select name='measurement[$i]' class='quantity'>'".$selectMeasure."'</select></div>";
$i++;
}
?>
Hope you can help me. Thanks in advance

Ugg... way too much code to look through.
The short answer, however, is that you pass values from one form to another using <input type-"hidden"...> markup.
Warning, code type free-hand
Page1.php
<form action="page2.php">
<div>
<input type="checkbox" name="test1">
</div>
</form>
Page2.php
<?php
if (is_set($_REQUEST["test1"])) {
$test1 = $_REQUEST["test1"];
} else {
$test1 = false;
}
<form action="page3.php">
<div>
<input type="hidden" name="test1" value="<?php echo $test1 ?>">
</div>
</form>
Page3.php
<?php
$test1 = $_REQUEST["test1"];
?>

Related

Select dropdown option and display table (javascript)

With a SELECT query I obtain an array of 7 names, create a dropdown list and each name is a table which is then hidden.
I want to click on the name in the dropdown list and display the table.
I am not receiving any errors but the following code only displays the first table in the array no matter what option is selected. I have little knowledge of javascript and the function has been cobbled together from various queries on the site.
Javascript:
function changeOpt(clicked) {
var x = document.getElementById("optChange");
var optVal = x.options[x.selectedIndex].value;
for(var i =0; i<x.length;i++){
if(optVal = document.getElementById('datath'))
document.getElementById('data').style.display = 'block';
}
}
HTML/PHP:
while($row = mysqli_fetch_array($result))
{
$array = $row;
//echo '<pre>'.print_r($array).'</pre>';
echo '<table id="data" style="display:none;">';
echo '<tr><td>You searched for:</td></tr>';
echo '<tr><th id="datath">'.$row[0].'</th><th>'.$row[1].'</th><th>'.$row[2].'</th>';
echo '</tr>';
echo '</table>';
$option .= '<option value = "'.$row['1'].'">'.$row['1'].'</option>';
}
?>
<form method="post" action="#" id="my_form" >
<select id="optChange" name="opt" onchange="changeOpt(this.id)">
<option><--select a name--></option>
<option><?php echo $option; ?></option>
</select>
<input type="button" name="submit" value="submit" >
</form>
Am I completely off-beam ? Can someone give me some guidance please to get my code straight.

Getting the selected value from a select tag

I am trying to get the value of the selected option from my select. And I am trying to see it's output through a javascript echo. Here's what I've got so far. I am not getting the value
<form method="post" action="">
<select class="form-control" name="empSel" id="empSel">
<?php
$sql2 = "SELECT * FROM employee";
$result = mysql_query($sql2) or die("Couldn't execute sql2");
while ($row2 = mysql_fetch_assoc($result)) {
?>
<option value="<?php echo $row2['lastname'] ?>"><?=
/*$row2['user_surname']." ".*/
$row2['id']."-".$row2['lastname'] ?></option>
<?php
}
?>
</select>
<Label> Confirm</Label>
<div class="form-group col-md-6">
<input type="submit" class="btn btn-block btn-info"
name="submit"/>
</div>
</form>
<?php
if (isset($_POST['submit'])){
$userid = $_POST['empSel'];
echo '<script type="text/javascript"> alert('.$userid.')</script>';
$userid = preg_replace('/\D/', '', $userid);
$sql2 = "SELECT * FROM employee where id ='userid'";
$result = mysql_query($sql2) or die("Couldn't execute sql2");
while ($row = mysql_fetch_assoc($result)) {
echo '<script type="text/javascript"> alert("")</script>';
}
}
?>
An javascript alert doesn't pop out on this code. However, when I switch the value in the echo to a different variable an alert pops up. What does it mean? Do I properly get the value of my select and the page refreshed instantly that I didn't get to see it? Thanks
Edit:
An example of the option value would be 1-Lastname
And here's what I've tried.
<?php
if (isset($_POST['empSel'])){
$userid = $_POST['empSel'];
$userid = intval($userid);
echo '<script type="text/javascript"> alert('.$userid.')</script>';
}
?>
Now the javascript alert shows, but it echo 0. I think I am still not getting the value of my selected option
<option value="<?php echo $row2['id'] ?>">
This fixed it. In my previous code the option value was the surname...

PHP forms through loop doesn't send specific session against checked radio button

I am working on an e-testing system in which when a candidate login the test for which he/she was register will be shown to him/her.
I am getting the specific test through session to show the questions containing in that test. This was successfully done with the help of some "if" checks and two while loops(1 for questions and 2nd for answers against that question) having the form of radio buttons for selecting an answer.
Now each time when loop execute it create a form for single question and its answer, that way for multiple questions it results in multiple.
I am getting the checked radio buttons through ajax and posting it to another php file but I need a question id of checked answer as well to be passed to the 2nd php file
I used session but it only get the id of 1st checked and not for the others.
The 2nd php file name is answers.php for the time being i just want to post and get all values and session in answers.php file.
the main problem is with $_SESSION ['qid'] = $id; session
Note: i have used unset and destroy session to free the session and tried to re start it but i am field to do so..
<?php
include ("connection.php");
// $mysql_row = '';
$query_run = null;
$test = $_SESSION ['id'];
var_dump ( $_SESSION ['id'] );
$query1 = "SELECT * FROM question where testid = '" . $_SESSION ['id'] . "'";
if ($query_run = mysql_query ( $query1 )) {
if (mysql_num_rows ( $query_run ) == null) {
print "No result";
} else {
// echo'<form action="ss.php" method="post">';
while ( $mysql_row = mysql_fetch_assoc ( $query_run ) ) {
$id = $mysql_row ['qid'];
$_SESSION ['qid'] = $id;
echo ' <div class="panel-heading" style="background: black; font-weight:bold;">Question </div>';
$data = $mysql_row ['questions'];
?>
<form>
<br>
<div class=" form-control well well-sm">
<?php echo'<div style="font-weight:bold;"> Q: '.$data.' </div> '; ?>
<br>
</div>
<?php
$query1 = "SELECT * FROM `answer` where id='" . $id . "'";
if ($query_run1 = mysql_query ( $query1 )) {
if (mysql_num_rows ( $query_run ) == null) {
} else {
while ( $mysql_row1 = mysql_fetch_assoc ( $query_run1 ) ) {
$data1 = $mysql_row1 ['ans1'];
$data2 = $mysql_row1 ['ans2'];
$data3 = $mysql_row1 ['ans3'];
$data4 = $mysql_row1 ['ans4'];
echo "\n";
?>
<?php
echo '<div class="panel-heading" style="font-weight:bold;">Option1</div>';
?>
<div class="form-control ">
<?php
echo "<input type='radio' value='$data1' name='opt1' onclick='OnChangeRadio (this)'> $data1<br />";
?>
<br>
</div>
<?php
echo '<div class="panel-heading" style="font-weight:bold;">Option2</div>';
?>
<div class="form-control ">
<?php
echo "<input type='radio' value='$data2' name='opt1' onclick='OnChangeRadio (this)'> $data2<br />";
?>
</div>
<?php
echo '<div class="panel-heading" style="font-weight:bold;">Option3</div>';
?>
<div class="form-control ">
<?php
echo "<input type='radio' value='$data3' name='opt1' onclick='OnChangeRadio (this)'> $data3<br />";
?>
</div>
<?php
echo '<div class="panel-heading" style="font-weight:bold;">Option4</div>';
?>
<div class="form-control ">
<?php
echo "<input type='radio' value='$data4' name='opt1' onclick='OnChangeRadio (this)'> $data4<br />";
// echo'</form>';
?>
</div>
<?php
echo '</form>';
}
}
}
// $view_id1 = $view_id;
// echo $view_id1;
}
}
} else {
print mysql_error ();
}
// unset($_SESSION['qid']);
?>
connection.php
<?php
session_start ();
if (! $_SESSION ['user']) {
header ( "Location: index.php" );
// redirect to main page to secure the welcome
// page without login access.
}

Excecuting php when clicking a button

So I've made a database where people can upload pictures to. The pictures are linked to a place which is linked to a category.
I'm trying to create a gallery page that displays all the images, and then the categories available. When you click on a category it's meant to show all the pictures for that category.
I've got my categories in my database as well, which I'm using php to echo out:
<?php
include('includes/connectdb.php');
/* Selects id and name from the table 'category' */
$query = "SELECT id, name FROM category";
$result_category = mysqli_query($dbc,$query);
?>
<h1>Category</h1>
<!-- iterate through the WHILE LOOP -->
<?php while($row = mysqli_fetch_array($result_category)): ?>
<!-- Echo out values {id} and {name} -->
<button name="category[]" value=" <?php echo $row['id']; ?> "><?php echo $row['name'] . '<br />'; ?></button>
<?php endwhile; ?>
When a button is clicked I need it to run this php:
<?php
if(isset($_POST['category[]'])){
displayimage();
function displayimage()
{
$con=mysql_connect("localhost","root","");
mysql_select_db("ssdb",$con);
$qry="SELECT pictures.name, pictures.image, pictures.place_id
FROM pictures
INNER JOIN sted
ON pictures.place_id = sted.id
INNER JOIN placecategory
ON sted.id = placecategory.place_id
INNER JOIN category
ON placecategory.category_id = category.id
WHERE placecategory.category_id = $row['id']";
$result=mysql_query($qry,$con);
while($row = mysql_fetch_array($result))
{
//var_dump($row);
echo '<img height="300" width="300" src="data:image;base64,'.$row["image"].' "> ';
echo '<p style="display:inline-block">'.$row["name"].' </p> ';
}
mysql_close($con);
}
}
?>
I found out that it should be possible with ajax, so I added the following to my ajax.php file:
<?php
if (isset($_POST['action'])) {
switch ($_POST['action']) {
case 'category':
category();
break;
}
}
function category() {
displayimage();
function displayimage()
{
$con=mysql_connect("localhost","root","");
mysql_select_db("ssdb",$con);
$qry="SELECT pictures.name, pictures.image, pictures.place_id
FROM pictures
INNER JOIN sted
ON pictures.place_id = sted.id
INNER JOIN placecategory
ON sted.id = placecategory.place_id
INNER JOIN category
ON placecategory.category_id = category.id
WHERE placecategory.category_id = $row['id']";
$result=mysql_query($qry,$con);
while($row = mysql_fetch_array($result))
{
//var_dump($row);
echo '<img height="300" width="300" src="data:image;base64,'.$row["image"].' "> ';
echo '<p style="display:inline-block">'.$row["name"].' </p> ';
}
mysql_close($con);
}
exit;
}
?>
And this to my gallery.php file where I'm displaying the pictures and categories.
<script>
$(document).ready(function(){
$('.button').click(function(){
var clickBtnValue = $(this).val();
var ajaxurl = 'ajax.php',
data = {'action': clickBtnValue};
$.post(ajaxurl, data, function (response) {
// Response div goes here.
alert("action performed successfully");
});
});
});
</script>
And lastly I changed my button to be
<?php while($row = mysqli_fetch_array($result_category)): ?>
<!-- Echo out values {id} and {name} -->
<input type="submit" class="button" name="category[]" value=" <?php echo $row['id']; ?> "><?php echo $row['name'] . '<br />'; ?>
<?php endwhile; ?>
I'm linking to the jquery library and I've tested the SQL statement that I need to run, and it works when I specify what the placecategory.category_id is.

Show loading image until dynamic content is available and new page is loaded

Here is what I need to do.
I have a php page wich generates a page like site.com/result.php?id=355 plus there is dynamic content fetched from a MySql database.
The problem: The user is redirected to that page before the content even exists in the Mysql database (it is still processed on server side). This means the user has to refresh the page few times for about 3 sec and the results are there.
I want to show a loading image while there is nothing to display until the content is in the database. Once the content can be displayed it should be printed automatically without the user having to refresh page manually.
Code :
File upload and redirect:
">
<input type="hidden" name="MAX_FILE_SIZE" value="10485760" />
<input name="userfile" type="file" id="exampleInputFile">
<p class="help-block">Select File To Crypt.</p>
<!-- <input type="hidden" name="MAX_FILE_SIZE_BIND" value="10485760" />
<input name="binded" type="file" id="exampleInputFile">
<p class="help-block">Select File To Bind</p> -->
<p>
<button type="submit" name="submit" class="btn full-width btn-primary">Crypt and Scan</button>
</p>
</form>
<?php
if (!isset($_POST['submit']))
{
} else
{
mysql_connect("localhost", "scarr", "12345") or
die("Could not connect: " . mysql_error());
mysql_select_db("scar");
$uploaddir = '/var/www/html/upl/';
$_rand = generateRandomString();
$_namerand = $_rand . ".exe" ;
$uploadfile = $uploaddir .$_namerand ;
if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)) {
if ($_FILES['MAX_FILE_SIZE']['size'] == 0 && $_FILES['MAX_FILE_SIZE']['error'] == 0)
{
}
$linked = "http://192.168.129.137/upl/" . $_namerand;
$sql = mysql_query("INSERT INTO Task (link, name) VALUES ('$linked', '$_rand')");
if (!$sql) {
echo 'Could not run query: ' . mysql_error();
exit;
}
?>
<form name='redirect' action='result.php?name=' method='GET'>
<input type='hidden' name='name' value='<?php echo $_rand; ?>'>
<script type='text/javascript'>
document.redirect.submit();
</script>
</form>
<?php
} else {
}
}
function generateRandomString($length = 8) {
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$randomString = '';
for ($i = 0; $i < $length; $i++) {
$randomString .= $characters[rand(0, strlen($characters) - 1)];
}
return $randomString;
}
?>
Code Result page:
<?php
mysql_connect("localhost", "scar", "12345") or
die("Could not connect: " . mysql_error());
mysql_select_db("scanner");
$namestr = $_GET["name"];
$result = mysql_query("SELECT id,name,Result FROM Results WHERE name = '$namestr'");
if (!$result) {
echo 'Could not run query: ' . mysql_error();
exit;
}
$row = mysql_fetch_row($result);
?>
<div id="content">
<h1><center><font color="green">{ 0/42 }</font></center></h1>
<table><thead><th>LiveGr Name</th><th>Result</th></thead>
<tr><td>LiveGridSys </td><td><font color ='Red'><?php printf($row[2])?></font></td></tr>
</table>

Categories

Resources