Storing User Preferences in Cookie - javascript

I'm creating a website in php using which allows users to filter the content displayed through checkboxes. I want to save their preferences. I'm using jquery.mmenu and generating the checkboxes as follows
<form id="menu-right method="post" action="">
<li>
'. $sportArray[$ids]["Event"] . '
<input type="checkbox" class="Toggle" name="sportList[]" value="'.$sportArray[$ids]["Event"].'" />
</li>'
</form>
I'm able to collect an array and print the values of the array through the below code, but I'm unable to set cookies, retrieve cookies, and haven't even started adding a check in the checkbox to restore the 'checked' values when loaded the checkboxes. I've tried a number of methods through javascript and php with no luck. There are pseudo elements in the CSS which I understand broke a couple of options for javascript
<?
if(isset($_POST['sportList'])) {
for ($i=0; $i<=count($_POST['sportList']); $i++){
echo $_POST['sportList'][$i];
setcookie('userSportList[$i]', $_POST['sportList'][$i], time()+60*60*24*365, '/');
}
}
?>
Any solution welcome.. it's probably something stupid at this stage as I'm tried so many options now. Alternatives such as localstorage or something also welcome, what ever is the best solution
<?php
if(isset($_POST['sportList'])) {
session_start();
$_SESSION['sesUserPrefs'] = $_POST['sportList'];
$serUserPrefs = serialize($_SESSION['sesUserPrefs']);
$bcSerUserPrefs = base64_encode($serUserPrefs);
$expire = 2000000000;
setcookie("cUserPrefs", $bcSerUserPrefs, time()+$expire);
}
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html;charset=iso-8859-1" />
<title>test
</title>
<link type="text/css" rel="stylesheet" href="css/main.css" />
<link type="text/css" rel="stylesheet" href="css/mmenu.5.3.css" />
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/hammer.js/1.0.5/jquery.hammer.min.js"></script>
<script type="text/javascript" src="js/umd.all.js"></script>
<script src="http://cdn.jsdelivr.net/jquery.cookie/1.4.0/jquery.cookie.min.js"></script>
<script type="text/javascript">
// The menu on the left
$(function() {
$('nav#menu-left').mmenu();
});
// The menu on the right
$(function() {
var $menu = $('form#menu-right');
$menu.mmenu({
offCanvas: {
position : "right"
},
classes : 'mm-light',
dragOpen : true,
counters : true,
searchfield: {
add: true,
search: false
},
labels : {
fixed : !$.mmenu.support.touch
},
navbars: {
position: "top",
content: [
'Save'
]
}
});
});
</script>
</head>
<body>
<?php
// DB Configuration
$config = parse_ini_file('config/config.ini');
//Timezone dropdown
function timezone() {
$list = DateTimeZone::listAbbreviations();
$idents = DateTimeZone::listIdentifiers();
$data = $offset = $added = array();
foreach ($list as $abbr => $info) {
foreach ($info as $zone) {
if ( ! empty($zone['timezone_id'])
AND
! in_array($zone['timezone_id'], $added)
AND
in_array($zone['timezone_id'], $idents)) {
$z = new DateTimeZone($zone['timezone_id']);
$c = new DateTime(null, $z);
$zone['time'] = $c->format('h:i a');
$data[] = $zone;
$offset[] = $z->getOffset($c);
$added[] = $zone['timezone_id'];
}
}
}
array_multisort($offset, SORT_ASC, $data);
$options = array();
foreach ($data as $key => $row) {
$options[$row['timezone_id']] = $row['time'] . ' - '
. formatOffset($row['offset'])
. ' ' . $row['timezone_id'];
}
return $options;
}
function formatOffset($offset) {
$hours = $offset / 3600;
$remainder = $offset % 3600;
$sign = $hours > 0 ? '+' : '-';
$hour = (int) abs($hours);
$minutes = (int) abs($remainder / 60);
if ($hour == 0 AND $minutes == 0) {
$sign = ' ';
}
return 'GMT' . $sign . str_pad($hour, 2, '0', STR_PAD_LEFT)
.':'. str_pad($minutes,2, '0');
}
?>
<div id="page">
<div id="header">
<!-- Sub Header -->
<form id="tzForm" method="POST" action="">
<select name="userTZ" >
<?php foreach(timezone() as $key => $tz) { ?>
<option value="<?php echo $key; ?>"<?php if ($_POST['userTZ'] == $key) { echo ' selected>';} else { echo '>';} //keep tz as last selected
echo $tz; ?></option>
<?php } ?>
</select> <input type="submit" value="Set">
</form>
</div> <!-- Close Header -->
<div id="content">
<?php
//Collect Selected Sport/Category/Event values from right menu
if (isset($_COOKIE["cUserPrefs"])) {
echo "<script type='text/javascript'>alert('ding ding ding');</script>";
} elseif (isset($_SESSION['sesUserPrefs'])) {
$sportListItem = $_SESSION['sesUserPrefs'];
//update array with selected toggles
while ($row = $result->fetch_array()) {
if ($row['SportCategory'] == $sportListItem OR $row['Sport'] == $sportListItem OR $row['Event'] == $sportListItem) {
$gameArray[ $row['PK_ID'] ] = array(
'GameDate' => $row['GameDate'],
'Timezone' => $row['Timezone'],
'TeamOne' => $row['TeamOne'],
'TeamTwo' => $row['TeamTwo'],
'urlTeamOne' => $row['urlTeamOne'],
'urlTeamTwo' => $row['urlTeamTwo'],
'FK_SportData' => $row['FK_SportData']
);
} //end inside if
};
}
?>
</div>
<div id="page">
<div id="content">
<p id="confirmation"></p>
</div>
<nav id="menu-left">
<?php
foreach ($sportArray as $ids=>$vals) {
//First List Item
if ($ids == 1) {
echo '<ul><li>
'. $sportArray[$ids]["SportCategory"]. '
<ul class="Vertical">';
}
//All others check if different to one before
elseif ($sportArray[$ids]["SportCategory"] != $sportArray[($ids - 1)]["SportCategory"]) {
echo '</ul></li></ul></li><li>
'. $sportArray[$ids]["SportCategory"] . '
<ul class="Vertical">'; //opening thse UL without an event could cause issues
}
//Check the previous sport is not the same
if ($sportArray[$ids]["Sport"] != $sportArray[($ids - 1)]["Sport"]) {
echo '<li>
'. $sportArray[$ids]["Sport"] . '
<ul class="Vertical">';
}
//Print Event
echo '<li>
'. $sportArray[$ids]["Event"] . '
</li>';
}
?>
</ul></li></ul></li></ul>
</nav>
<form id="menu-right" method="post" action="">
<?php
foreach ($sportArray as $ids=>$vals) {
//First List item
if ($ids == 1) {
echo '<ul class="Vertical"><li>
'. $sportArray[$ids]["SportCategory"]. '
<input type="checkbox" class="Toggle" name="sportList[]" value="'.$sportArray[$ids]["SportCategory"].'" />
<ul class="Vertical">';
}
//All others check if different to one before
elseif ($sportArray[$ids]["SportCategory"] != $sportArray[($ids - 1)]["SportCategory"]) {
echo '</ul></li></ul></li><li>
'. $sportArray[$ids]["SportCategory"] . '
<input type="checkbox" class="Toggle" name="sportList[]" value="'.$sportArray[$ids]["SportCategory"].'" />
<ul class="Vertical">'; //opening thse UL without an event could cause issues
}
//Check the previous sport is not the same
if ($sportArray[$ids]["Sport"] != $sportArray[($ids - 1)]["Sport"]) {
echo '<li>
'. $sportArray[$ids]["Sport"] . '
<input type="checkbox" class="Toggle" name="sportList[]" value="'.$sportArray[$ids]["Sport"].'" />
<ul class="Vertical">';
}
//Print Event
echo '<li>
'. $sportArray[$ids]["Event"] . '
<input type="checkbox" class="Toggle" name="sportList[]" value="'.$sportArray[$ids]["Event"].'" />
</li>';
}
?>
</ul></li></ul></li></ul>
</form>
</div>
</body>
</html>

You should use session array for this. First store values into a session. Then you need to :
Serialize your session array and apply base64_encode. Put this value
into cookie.
At the start check if cookie exist then apply base64_decode and unserialize that data and push into session array.
If you know about serialize, unserialize, base64_encode and
base64_decode then you can easily do this task.
Hopefully you will done this easily.

Related

Onclick function is not working on a particular span

I am having a problem that my Onclick event is not triggering on a tag. The same onclick event is working properly when binded to a image.
I am making a follow and unfollow function in php and jquery .It is not working so I decided to test a alert after clicking the follow or unfollow button . Then also it is not working .
The code is this
<?php
if ($my_id != $id) {
$check_follow_not = mysqli_query($conn, "SELECT * FROM follower WHERE user_id='$my_id' AND following='$id'");
$check_follow_not_rows = mysqli_num_rows($check_follow_not);
if ($check_follow_not_rows == 0) {
$editfollowunfollow = "<span class='btn_f_uf'><a onclick=\"don();\">Follow</a></span>";
} else {
$editfollowunfollow = "<span class='btn_f_uf'><a onclick=\"don();\">UnFollow</a></span>";
}
} else {
$editfollowunfollow = "<span class='btn_f_uf'><a>Edit Profile</a></span>";
}
echo $editfollowunfollow;
?>
The php code is okay, the problem is with the jquery code
The don() function is this
function don(){
alert();
}
This function is working fine on a image in same file . But not working in the follow and unfollow button.
Thanks in advance . I appreciate all answer
EDIT
Css code of class btn_f_uf
.btn_f_uf{
border:0;
outline:0;
padding:10px;
background:#53a93f;
border-radius:5px;
color:white;
float:right;
margin-right:20px;
margin-top:25px;
display:inline-block;
}
EDIT 2
The profile page whole code
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"></meta>
<title>Profcee</title>
<link rel="stylesheet" href="style/style.css">
<script src="js/jquery-2.1.3.js"></script>
<script src="js/check.js"></script>
<script src="js/jquery-ui.js"></script>
<script src="js/jquery-ui.min.js"></script>
</head>
<?php
session_start();
if(isset($_GET['id'])){
include "function/checklogin.php";
include "config/connect.php";
$my_profile_image = $_SESSION['profile_image'];
$my_email = $_SESSION['email'];
$my_id = $_SESSION['id'] ;
$my_name = ucfirst($_SESSION['name']);
$my_background_image = $_SESSION['background_image'];
$id = $_GET['id'];
$check = mysqli_query($conn,"SELECT * FROM users WHERE id='$id'");
$check_num = mysqli_num_rows($check);
if($check_num == 0){
header("location:home.php");
}else{
$fetch = mysqli_fetch_assoc($check);
$name = ucfirst($fetch['name']);
$email = $fetch['email'];
$profile_image = $fetch['profile'];
$background_image = $fetch['background'];
if($my_id != $id){
$check_follow_not = mysqli_query($conn,"SELECT * FROM follower WHERE user_id='$my_id' AND following='$id'");
$check_follow_not_rows = mysqli_num_rows($check_follow_not);
if($check_follow_not_rows == 0){
$editfollowunfollow = "<span class='btn_f_uf'><a class='btns'>Follow</a></span>";
} else{
$editfollowunfollow = "<span class='btn_f_uf'><a class='btns'>UnFollow</a></span>";
}
}else{
$editfollowunfollow = "<span class='btn_f_uf'><a>Edit Profile</a></span>";
}
?>
<?php
include "header.php"; ?>
<div id="profile_full">
<div id="background_image">
<img src="<?php echo $background_image;?>" width="100%" height="400px" onclick="don();">
</div>
<div id="profile_image">
<img src="<?php echo $profile_image?>" width="250px" height="250px">
</div>
<div id="profile_header">
<h1><?php echo $name;?></h1>
<div id="profile_follower">
<?php
$follower = mysqli_query($conn,"SELECT * FROM follower WHERE following='$id'");
$follower_count = mysqli_num_rows($follower);
?>
<h2><?php echo $follower_count;?> Follower</h2>
</div>
<div id="profile_following">
<?php
$following = mysqli_query($conn,"SELECT * FROM follower WHERE user_id='$id'");
$following_count = mysqli_num_rows($following);
?>
<h2><?php echo $following_count;?> following </h2>
</div>
<?php echo $editfollowunfollow;?>
</div>
</div>
<?php
include "footer.php";
?>
<?php
}
}else{
header("location:home.php");
}
?>
The check.js file
$(document).on("click",".btns", function(e){
e.preventDefault();
alert();
});
Like other said, give it class name btns and removeonclick inline javascript on that anchor tag :
.....
if($check_follow_not_rows == 0){
$editfollowunfollow = "<span class='btn_f_uf'><a class='btns'>Follow</a></span>";
} else{
$editfollowunfollow = "<span class='btn_f_uf'><a class='btns'>UnFollow</a></span>";
}
....
And in js code :
$(document).on("click",".btns", function(e){
e.preventDefault();
alert();
});
If you wanna stick with function don(), use this(but must be sure to remove onclick inline javascript) :
$(document).on("click",".btns", don );
In don function :
function don(){
alert();
return false;
}

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>

Comments on Posts (PHP)

I'm currently trying to use comments on my website. The comments will be used on posts I have.
The thing is, I'm currently using an iframe to show them.
I would like the code to be on the same page as my posts.
I'll show you what I mean by posting my code:
comment_frame.php:
<?php
if (isset($_POST['postComment' . $getid . ''])) {
$post_body = $_POST['post_body'];
$posted_to = "Chris";
$insertPost = mysql_query("INSERT INTO post_comments VALUES ('','$post_body','$user','$posted_to','0','$getid')");
echo "<p style='color: green'>Comment Posted!</p><br /><br />";
}
// Get relevent comments
$get_comments = mysql_query("SELECT * FROM post_comments WHERE post_id='$getid' ORDER BY id DESC");
$count = mysql_num_rows($get_comments);
if ($count != 0) {
while ($comment = mysql_fetch_assoc($get_comments)) {
$comment_body = $comment['post_body'];
$posted_to = $comment['posted_to'];
$posted_by = $comment['posted_by'];
$removed = $comment['post_removed'];
echo "<b><a href='$posted_by' target='_blank'>$posted_by</a> said: <br /></b>".$comment_body."<hr /><br />";
}
}
else
{
// Do nothing!
}
?>
home.php:
<?php
// If the user is logged in
$getposts = mysql_query("SELECT * FROM posts WHERE user_posted_to='$user' ORDER BY id DESC LIMIT 10") or die(mysql_error());
while ($row = mysql_fetch_assoc($getposts)) {
$id = $row['id'];
$body = $row['body'];
$date_added = $row['date_added'];
$added_by = $row['added_by'];
$user_posted_to = $row['user_posted_to'];
$get_user_info = mysql_query("SELECT * FROM users WHERE username='$added_by'");
$get_info = mysql_fetch_assoc($get_user_info);
$profilepic_info = $get_info['profile_pic'];
if ($profilepic_info == "") {
$profilepic_info = "./img/default_pic.png";
}
else
{
$profilepic_info = "./userdata/profile_pics/".$profilepic_info;
}
?>
<script language="javascript">
function toggle<?php echo $id; ?>() {
var ele = document.getElementById("toggleComment<?php echo $id; ?>");
var text = document.getElementById("displayText<?php echo $id; ?>");
if (ele.style.display == "block") {
ele.style.display = "none";
}
else
{
ele.style.display = "block";
}
}
</script>
<?php
echo "
<br />
<div class='newsFeedPost'>
<div class='newsFeedPostOptions'>
<a href='javascript:;' onClick='javascript:toggle$id()'>Show Comments</a>
<div style='float: left;'>
<a href='$added_by'><img src='$profilepic_info' height='60' /></a>
</div>
<div class='posted_by'><a href='$added_by'>$added_by</a> wrote:</div>
<br /><br />
<div style='max-width: 600px; height: auto;'>
$body<br /><br /><br /><p />
</div>
Like – Re-Shout! – Comment
<br /><iframe src='./comment_frame.php?id=$id' frameborder='0' style='max-height: 200px; width: 100%; min-height: 10px;'></iframe>
</div>
</div>
";
}
}
?>
As you can see it shows the comment_frame.php page by using an iframe. I would like all of that code to be in a single page. How would I do that?
put ur home.php code in else condition if user adding new comment the first condition will work otherwise second one
if (isset($_POST['postComment' . $getid . ''])) {
your code here
}else {
// home.php code herer
}

htmlspecialchars_decode causes width issues

I have been messing about creating stuff in PHP so decided to create a site... However, when I am pulling things from my DB it is resizing the text and pushing things off of the page :/
I have tested with plain text and my site is displaying correctly:
http://gentetcreations.co.uk/blog-2.php
However, with HTML text it displays in a weird way and I can't seem to get it fixed:
http://gentetcreations.co.uk/blog-1.php
JSFidle here!
<!DOCTYPE HTML>
<html>
<head>
<title>GentetCreations</title>
<meta charset="UTF-8">
<link rel="stylesheet" type="text/css" href="style/style.css" />
</head>
<body>
<div id="main">
<?php
include("inc/pageHead.php");
?>
<div id="site_content">
<?php
include("inc/side.php");
?>
<div id="content">
<?php
include("inc/dbconnection.php");
$id = $_GET['id'];
$id = trim($id);
$result = mysqli_query($conn, "SELECT * FROM blog WHERE authorised = 1 AND blog_id = '" . $id . "'");
if(!$result) {
die("Database query failed: " . mysqli_error($conn));
} else {
$rows = mysqli_num_rows($result);
if ($rows > 0) {
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
$tags = "";
$result2 = mysqli_query($conn, "SELECT * FROM tags WHERE blog_id = '" . $row['blog_id'] . "'");
if(!$result2) {
die("A Database query failed: " . mysqli_error($conn));
} else {
while ($row2 = mysqli_fetch_array($result2, MYSQLI_ASSOC)) {
$rawTag = $row2['tag'];
$tag = str_replace(" ", "", $rawTag);
$tags .= "<a href='tag-" . $tag . ".php'>" . $tag . "</a> ";
}
}
echo "
<span class='mainContentWidth'>
<table>
<tr>
<th>
<a href='blog-" . $row['blog_id'] . ".php'>
<h2>" . $row['title'] . "</h2>
</a>
</th>
</tr>
<tr>
<td>
<p>" . date("d/m/Y", strtotime($row['createdDate'])) . "</p><br />
<span>" . $row['content'] . "</span>
<br />
<br />
<span><small>Tags: " . $tags . "</small></span>
</td>
</tr>
</table>
</span>";
} //$row = mysqli_fetch_array($result, MYSQLi_ASSOC)
} else { //$rows > 0
echo "<br /><h1>An error occurred.</h1><br /><h2>The blog you were looking for could not be found.</h2>";
}
}
?>
</div>
</div>
<?php
include("inc/footer.php");
?>
</div>
</body>
</html>
I am new to doing web based coding so I am really confused here and not too sure what is going on.
If anyone could help me here or push me in the right direction to display everything correctly, I would be very happy!
You have block level elements inside a span tag. You should avoid doing that.
For current issue you can add this CSS
table tr td > span {
width: 615px;
}

checked checkbox will remain through pagination

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"];
?>

Categories

Resources