Page wise display is not working as expected - javascript

i am trying to display records as a multiples of 5, but i am getting only the first 5 records again and again.
HomePage-slideshow.php
<select multiple class="form-control " id="sel2" size="10" >
<?php
session_start();
if (isset($_SESSION["min"]) || isset($_SESSION["count"])) {
$time = (int)$_SESSION["min"];
$something = $_SESSION["something"];
$everything = $_SESSION["everything"];
}
$count = (int)$_SESSION["count"];
$select_query= "SELECT * from video_details WHERE c_something = '$something' OR c_everything = '$everything' HAVING video_min <= $time LIMIT $count,5";
$select_query_run = mysqli_query($conn,$select_query);
while ($select_query_array= mysqli_fetch_array($select_query_run) )
{
echo "<option value='".htmlspecialchars($select_query_array["video_question"])."' >".htmlspecialchars($select_query_array["video_question"])."</option>";
}
?>
</select>
<?php
$new = $count + 5;
$_SESSION["count"] = $new;
$_SESSION["min"] = $time;
$_SESSION["something"] = $something;
$_SESSION["everything"] = $everything;
//session_destroy();
?>
</div>
</div>
<div class="center">
<input type="button" class="btn btn-success font-30" value="I AM CURIOUS ABOUT THIS" />
<form id="next_page" name="next_page" method="post" action="next.php" data-ajax="false">
<input type="submit" class="btn btn-success font-30" id="next" name="next" value="LEARN SOMETHING ELSE" />
</form>
</div>
I am trying to increase the $count value when the LEARN SOMETHING ELSE button is pressed. It redirects to next.php where i try to reassign the increased value to count.
next.php
<?php
session_start();
$inc = (int)$_SESSION["count"];
$time = (int)$_SESSION["min"];
$something = $_SESSION["something"];
$everything = $_SESSION["everything"];
echo $inc;
$_SESSION["count"] = $inc;
$_SESSION["min"] = $time;
$_SESSION["something"] = $something;
$_SESSION["everything"] = $everything;
header("location: HomePage-slideshow.php#services-section");
?>
The echo statement gives 5 as output, but the query displays only the old output still. If i hardcode 5 in my query, it gives next 5 records but i am not able to dynamically change the value of $count in here.
Please help me

Related

Fetch data from msql into selectpickers for editing

I have a code which inserts data from a modal form into two related tables, namely inventory_order table and inventory_order_product table. That code is working fine but my problem comes when I want to fetch the same data back into the modal form for editing. The code for fetch single is only retrieving data for the first line in the selectpicker while the remaining are not retrieved. Please if my question is not clear refer to the image below and please bear with me I'm a novice in php, ajax and mysql.
$(document).on('click', '.update', function(){
var inventory_order_id = $(this).attr("id");
var btn_action = 'fetch_single';
$.ajax({
url:"order_action.php",
method:"POST",
data:{inventory_order_id:inventory_order_id, btn_action:btn_action},
dataType:"json",
success:function(data)
{
$('#orderModal').modal('show');
$('#inventory_order_name').val(data.inventory_order_name);
$('#inventory_order_date').val(data.inventory_order_date);
$('#inventory_order_address').val(data.inventory_order_address);
$('#span_product_details').html(data.product_details);
$('#payment_status').val(data.payment_status);
$('.modal-title').html("<i class='fa fa-pencil-square-o'></i> Edit Order");
$('#inventory_order_id').val(inventory_order_id);
$('#action').val('Edit');
$('#btn_action').val('Edit');
}
})
});
if($_POST['btn_action'] == 'fetch_single')
{
$query = "
SELECT * FROM inventory_order WHERE inventory_order_id = :inventory_order_id
";
$statement = $connect->prepare($query);
$statement->execute(
array(
':inventory_order_id' => $_POST["inventory_order_id"]
)
);
$result = $statement->fetchAll();
$output = array();
foreach($result as $row)
{
$output['inventory_order_name'] = $row['inventory_order_name'];
$output['inventory_order_date'] = $row['inventory_order_date'];
$output['inventory_order_address'] = $row['inventory_order_address'];
$output['payment_status'] = $row['payment_status'];
}
$sub_query = "
SELECT * FROM inventory_order_product
WHERE inventory_order_id = '".$_POST["inventory_order_id"]."'
";
$statement = $connect->prepare($sub_query);
$statement->execute();
$sub_result = $statement->fetchAll();
$product_details = '';
$count = '';
$count = $count++;
foreach($sub_result as $sub_row)
{
$product_details .= '
<script>
$(document).ready(function(){
$("#product_id'.$count.'").selectpicker("val", '.$sub_row["product_id"].');
$(".selectpicker").selectpicker();
});
</script>
<span id="row'.$count.'">
<div class="row">
<div class="col-md-8">
<select name="product_id[]" id="product_id'.$count.'" class="form-control selectpicker" data-live-search="true" required>
'.fill_product_list($connect).'
</select>
<input type="hidden" name="hidden_product_id[]" value="'.$sub_row["product_id"].'" />
</div>
<div class="col-md-3">
<input type="text" name="quantity[]" class="form-control" value="'.$sub_row["quantity"].'" required />
</div>
<div class="col-md-1">
';
if($count == '')
{
$product_details .= '<button type="button" name="add_more" id="add_more" class="btn btn-success btn-xs">+</button>';
}
else
{
$product_details .= '<button type="button" name="remove" id="'.$count.'" class="btn btn-danger btn-xs remove">-</button>';
}
$product_details .= '
</div>
</div>
</div><br />
</span>
';
}
$output['product_details'] = $product_details;
echo json_encode($output);
}
Problem in your code is with variable $count.As in your backend code this is declare outside your foreach.. loop so when first time your loop will run it will have correct value i.e : 0 but you never increment it that's why it is only giving correct value for first selectpicker. Instead you need to increment its value to set value for second value ,third and so on. i.e :
foreach($sub_result as $sub_row)
{
//you code html and jquery
$count = $count++;//add this inside for loop
}
Also, i don't why you have given $count = ''; . Instead , it should be $count = 0;

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...

How to calculate amount by javascript?

As u can see i have this form that calculate number of employees multiply by test that will be select by user. number of employees will be input by user and test are coming from database. each test have their individual price set in database. I used script for dropdown list.
If user put any value in no.of employees and check on anytest then in total amount sum should be calculate onclick buytest?
<form action="add_corporate_test.php" method="POST">
<script type="text/javascript">
$(document).ready(function () {
$('#example-onDeselectAll').multiselect({
includeSelectAllOption: true,
onDeselectAll: function () {
alert('please select any test!');
}
});
});
</script>
<div class="row">
<h5 class="cor_label">No. of Emp/Students:</h5>
<input
type="text" id="no_emp"
placeholder="No. of Employees/Students"
class="normal" required
>
<h5 class="cor_label">Email Address:</h5>
<input
type="text"
id="no_emp2"
placeholder="Email Address"
class="normal" value="<?php echo $_SESSION[email]; ?>"
required
disabled
>
<h5 class="cor_label">Select Test:</h5>
<select id="example-onDeselectAll" multiple="multiple">
<?php
$sql = mysql_query("select * from `test` ");
while ($data = mysql_fetch_assoc($sql)) {
$sum = 0;
?>
<option value="<?php echo $data['test_name']; ?>">
<?php echo $data['test_name']; ?>
</option>
<?php } ?>
</select>
<h5 class="cor_label">Total Amount:</h5>
<input
type="text"
id="no_emp3"
class="normal"
name="total_amount"
placeholder="total amount"
value="<?php echo $sum; ?>"
disabled
>
<button class="btn btn-primary" type="submit" name="corporate_buy">
Buy Test
</button>
</div>
</form>
Hi bro, use for loop for script b'coz u have multiple select option
`
<script>
$('#example-onDeselectAll').change(function() {
var value = $(this).val();
var i=0;
var len = value.length;
var no_emp = $("#no_emp").val();
for(i; i < len; i++){
var res = value[i] .split("_");
var tot_amount += res[1]*no_emp;
}
$("#no_emp3").val(tot_amount);
});
</scrit>
`
get the test and value on select option. on select split the value using javascript. and then sum the amount and no.of.employee
`
<select id="example-onDeselectAll" multiple="multiple" >
<?php
$sql=mysql_query("select * from `test` ");
while($data=mysql_fetch_assoc($sql))
{
$sum=0;
?>
<option value="<?php echo $data['test_name'];?>_<?php echo $data['price'];?>"><?php echo $data['test_name'];?></option>
<?php }?>
</select>
<script>
$('#example-onDeselectAll').change(function() {
var value = $(this).val();
var no_emp = $("#no_emp").val();
var res = value .split("_");
var tot_amount = res[1]*no_emp;
$("#no_emp3").val(tot_amount);
});
</scrit>
`

automatically populate text box based on select entry

Is there a way within php to get a value picked up from database automatically?
Basically, If I have a select box & I select option "Laptop-01" , is there a way within PHP to check the database for that row and then automatically pick up the serial number of Laptop-01 and populate it within the text box for the devices serial number.
At the moment I've just got two text boxes and user would need to manually enter both the product number (Laptop-01) & then the serial number.
I've currently got the following code;
PHP
<?php
$selectquery = "SELECT * FROM `loanproducts`";
$selectresult = mysqli_query($connection, $selectquery);
$selectusersquery = "SELECT * FROM `loanusers`";
$selectusersresult = mysqli_query($connection, $selectusersquery);
if (isset($_POST['editloan'])):
$loanid = $_POST["loanid"];
$username = $_POST["username"];
$product=$_POST["product"];
$product_desc=$_POST["product_desc"];
$serial=$_POST["serial"];
$date_collected=$_POST["date_collected"];
$date_return = $_POST["date_return"];
$returned = $_POST["returned"];
$edit_query="UPDATE loans SET
username = '$username',
product = '$product',
product_desc = '$product_desc',
serial = '$serial',
date_collected ='$date_collected',
date_return = '$date_return',
returned = '$returned'
WHERE loanid ='$loanid'";
$edit_result= mysqli_query($connection, $edit_query);
if ($edit_result) :
header ('location: editloan.php?confirm=Loan successfully updated');
else :
echo "<b>This didn`t work, error: </b>";
echo mysqli_error($connection);
endif;
endif;
$loanid=$_GET['loanid'];
$my_query="select * from loans where loanid=$loanid";
$result= mysqli_query($connection, $my_query);
while ($myrow = mysqli_fetch_array($result)):
$username = $myrow["username"];
$product = $myrow["product"];
$product_desc = $myrow["product_desc"];
$serial = $myrow["serial"];
$date_collected=$myrow["date_collected"];
$date_return=$myrow["date_return"];
$returned=$myrow["returned"];
endwhile;
?>
HTML
<html>
<h2 align="center">Edit Product Form</h2>
<body>
<div id="loginp"<p align="center">Edit this loan for the Coleg Sir Gar Loan System</p></div>
<form method="POST" action="editloaninfo.php">
<div id="editp"><p align="center">
<label class="labelform">Username:</label><select name="username" style="width: 150px">
<?php while($row1 = mysqli_fetch_array($selectusersresult))
{ if ( $row1[1] == $username )
$selected = "selected";
else $selected = "";
echo "<option $selected>{$row1[1]}</option>";
}?>
</select></p></div>
<div id="editp"><p align="center">
<label class="labelform">Product:</label><select name="product" style="width: 150px">
<?php while($row1 = mysqli_fetch_array($selectresult))
{ if ( $row1[1] == $product )
$selected = "selected";
else $selected = "";
echo "<option $selected>{$row1[1]}</option>";
}?>
</select></p></div>
<div id="editp"><p align="center">
<label class="labelform">Product Description:</label><input class="inputform" type="text" name="product_desc" placeholder="Product Description..." autocomplete="off" required size="18" value="<?php echo $product_desc; ?>"></p></div>
<div id="editp"><p align="center">
<label class="labelform">Serial Number:</label><input class="inputform" type="text" name="serial" placeholder="Serial Number..." autocomplete="off" required size="18" value="<?php echo $serial; ?>"></p></div>
<div id="editp"><p align="center">
<label class="labelform">Date Collected:</label><input class="inputform" type="date" name="date_collected" autocomplete="off" size="30" value="<?php echo $date_collected; ?>"></p></div>
<div id="editp"><p align="center">
<label class="labelform">Date Returned:</label><input class="inputform" type="date" name="date_return" autocomplete="off" size="30" value="<?php echo $date_return; ?>"></p></div>
<div id="editp"><p align="center">
<label class="labelform">Returned:</label><select name="returned" style="width: 150px">
<option value="Yes" <?php echo $returned === 'Yes' ? 'selected="selected"' : '' ?>>Yes</option>
<option value="No" <?php echo $returned === 'No' ? 'selected="selected"' : '' ?>>No</option>
</select></p></div>
<br>
<input type="hidden" name=loanid value= "<?php echo $loanid; ?>" >
<div id="editp"><input class="inputform" type="submit" name="editloan" value="Save Changes">
<input class="inputform" type="button" name="Cancel" value="Cancel" onClick="window.location.href='editloan.php'"></div>
</form>
</body>
</html>
</div>
Basically you want to do is :
When User select 'Laptop-01' you page must update all INPUTS with information related to user's laptop (like Serial number).This can be done by adding AJAX
Please note : This answer will give you idea about how to Populate data from data base then you can do this for any information you needed.
<form>
<select id='product_name' onchange="get_data()">
<option value='Laptop-01'>Laptop-01</option>
</select>
<input name='serial_no' id='serial_no'>
<input name='product_no' id='product_no'>
</form>
<script src="js/ajax.js"></script>
<script>
function get_data(){
//In very short what this do is :
//get values
var serial_no = document.getElementById('product_name').value;
//create an Object
var ajax = ajaxObj("POST", "yourpage.php");
ajax.onreadystatechange = function() {
if(ajaxReturn(ajax) == true) {
//ajax.responsetex is things you echo from script next to it
var index1 = ajax.responseText.split(",");
//index1 is array holding values
//index1[0]=$serial_no
//index1[1]=$product_no
//Now set value of your serian_no INPUT to $serial_no = index1[0];
document.getElementById('serial_no').value = index1[0];
document.getElementById('product_no').value = index1[1]
}
}
//ajax.send = POST/GET method
ajax.send("product_name="+product_name);
}
</script>
<?php
if(isset($_POST['product_name'])){
$sql = "SELECT serial_no,product_no FROM loanuser WHERE username='$username'";
$query = ($connection , $query);
while ($myrow = mysqli_fetch_array($query)){
$serial_no = $myrow["serial_no"];
$product_no = $myrow["product_no"];
}
//form a (,) separated list and echo it.
echo $serial_no.",".$product_no;
exit();
}
?>
Ajax.js
function ajaxObj(meth, url) {
var x = new XMLHttpRequest();
x.open(meth, url, true);
x.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
return x;
}
function ajaxReturn(x){
if(x.readyState === 4 && x.status === 200){
return true;
}
}
If you want me to add more explanation on AJAX used in this page , please add request in comment section i will edit it to more better answer

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