I have products in table I wish to display some when page load and remain data should display on button click, I have set limit as 6 per page, when page loading it is displaying first six rows and if I click on Load More button it is displaying another six rows here problem coming after got 12 rows from table when I click again on Load More button it is not working even I have more data in table, I have cross checked parameters also, it is fine parameters also sending with request. please help me how to solve this.
NOTE: when I test this script in core php it is working fine, when I implement this script in codeigniter first time click load more data working second time when i click it is not wokring.
Javascript Code Block
$('.more').click(function(){
var ID = $(this).attr("id");
var cats = $('input[name=cats]').val();
$("#more"+ID).html('<img src="<?=ROOT;?>resources/moreajax.gif" />');
$.post('<?=ROOT;?>product/dataLoad', {id:ID,cats:cats}, function(data){
if(data)
{
$('ol#updates').append(data);
$("#more"+ID).remove();
}
else
{
$(".morebox").html('The End');// no results
}
});
return false;
});
codeigniter controller function
public function dataLoad() {
if(isset($_POST['id']))
{
$lastmsg=$_POST['id'];
$cats = $_POST['cats'];
$query=mysql_query("select * from product where id > '".$lastmsg."' AND category_id IN ($cats) order by id asc limit 4");
$numrows = mysql_num_rows($query);
while($ob = mysql_fetch_array($query))
{
?>
<div>
<p>ID: <?=$ob['id']; </p>
<p>NAME: <?=$ob['name']; </p>
</div>
<?php
}//while
?>
<?php
if($numrows > 0)
{
?>
<div id="more<?php echo $ob['id']; ?>" class="morebox" style="clear:both">
<input type="hidden" name="cats" value="<?=$cats;?>" />
Load More
</div>
<?php
}
}
?>
product page code
<ol class="timeline" id="updates">
$str = implode(",",$cats);
$query = "select * FROM product WHERE category_id IN (".$str.") order by id asc limit 4";
$result=mysql_query($query);
$numrows = mysql_num_rows($result);
while($ob = mysql_fetch_array($result))
{
?>
<div>
<p>ID: <?=$ob['id']; </p>
<p>NAME: <?=$ob['name']; </p>
</div>
<?php
}//while
?>
</ol>
<?php
if($numrows > 0)
{
?>
<div id="more<?php echo $ob['id']; ?>" class="morebox" style="clear:both">
<input type="hidden" name="cats" value="<?=$cats;?>" />
Load More
</div>
<?php
}
?>
I solved this problem insted of this
$('.more').click(function(){
$("#updates").on("click",".more",function(){
Related
So i have a form that that does a simple calculation, depending on the users input. If the results is a certain value then it stores that value in a database, then it displays that value on a page. But i have to refresh the whole page for it to retrieve the latest updated value from the the database and display on the page.
I know how to write code to refresh the whole page, but in this case i only need the section where the it displays to be refreshed.
The original form to calculate
<div class="formC">
<form action="" method="post">
<label>Base Amount</label>
<input type="text" name="base"</input>
<label>Select Currency</label>
<div class="custom-select">
<span></span>
<select name="cur_name">
<option value="" selected>Choose a Base Currency</option>
<option value="EUR">EUR</option>
<option value="USD">USD</option>
</select>
</div>
<button type="submit" value="Submit">SUBMIT</button>
</form>
</div>
The form that gets the new values from the database
<div class="formC">
<form action="test.php" method="post">
<label>Base Amount</label>
<input type="text" name="base" id="new_base" value="<?php
$results = mysqli_query($con, "SELECT * FROM contents_arr ORDER BY id DESC LIMIT 1");
while($row = mysqli_fetch_array($results)){
echo $row["new_base"];
}
?>">
<div id="load_data"></div>
<label>Select Currency</label>
<input type="text" name="cur_name" value="<?php
$results = mysqli_query($con, "SELECT * FROM gain_name_table ORDER BY id DESC LIMIT 1");
while($row = mysqli_fetch_array($results)){
echo $row["gain_name"];
}
?>">
<button id="btn_submit" type="submit" value="Submit">SUBMIT</button>
</form>
</div>
Calculation
<?php
$base = $_POST['base'];
$value = $_POST['val'];
$selected = $_POST['cur_name'];
if ($selected == 'EUR') {
$results_eur = $base * $value;
// USD
}elseif ($selected == 'USD') {
$results_usd = $base * $value;
}
if($selected == 'EUR'){
$sql = "INSERT INTO calculation(new_base) VALUES('".$results_eur."')";
mysqli_query($con,$sql);
}elseif($selected == 'USD'){
$sql = "INSERT INTO calculation(new_base) VALUES('".$results_usd"')";
mysqli_query($con,$sql);
}
I managed to find the solution for this code using Ajax and jQuery:
$(document).ready(function(){
$('#btn_submit').click(function(){
var get_data = $('#new_base').val();
if($.trim(get_data) != '')
{
$.ajax({
url:"db2.php",
method:"POST",
data:{new_base:get_data},
dataType:"text",
success:function(data)
{
$('#new_base').val("");
}
});
}
});
setInterval(function(){
$('#load_data').load("fetch.php").fadeIn("slow")
}, 1000);
});
This can be done by creating a seperate php file and replacing the content on your page with the content of that other php page using javascript. This is not a full description on how to do it, just a hint on how this is done. There are plenty of resources where it is described in detail.
One place to start could be here W3Schools Ajax & Php
getData.php
header('Content-Type: application/json; charset=utf-8');
// do your php database stuff here
$data = //...
$data = json_encode($data);
echo $data;
And in your main file, you can fetch() the content of your getData.php in javascript to get the latest result and then inject the results into your div using document.getElementById('content').innerHTML = ...
Using this method, only your div refreshed, not the whole page.
I have a code in PHP that prints HTML elements based on the information we got in the database, so if we have for example 8 products the code will print 8 divs with the following elements inside
h1 the id of this element will be the same as the product in the database
input for client name
buy button that send the ID of the H1 to the database
here is some code i made
<?php
while($row=$consulta->fetch())
{
?> <img src="<?php echo $row["Imagen"];?>"style="width:12rem;height:12rem;" alt="Scotter" >
<br>
<div>
<h4 id="<?php echo $row["ID_Scooter"]; ?>"> <?php echo $row["ID_Scooter"]; ?> </h4>
<br>
<?php
echo $row["Nombre"];
?>
<br>
<?php
echo $row["Descripcion"];
?>
<br>
<?php
?>
<button onclick="abrir()">Alquilar</button>
<br>
</div>
<?php
}
?>
JavaScript
function abrir(){
var dialog = document.getElementById('favDialog');
dialog.show();
var id=document.getElementById("heres is where im supposed to get the id of the id i clicked");
alert("div id is="+id);
}
php assing ID for example (3,4,5,6,7) but when i click the button inside the div with id=5 it prints the id=3 no matter which button i click
please note that you've set onclick="abrir()" without passing any specific data!
you have got 2 way to do it:
1- passing data with php:
HTML:
abrir(<?php echo $row["ID_Scooter"]; ?>)
and use it in your js :
function abir(id){
let id_scooter = id;
...
}
2- passing clicked element with js:
HTML:
onclick="abrir(this)"
JS:
function abir(el){
let id_scooter = (el).attr(id);
...
}
I have a shop which uses dynamic content. Users can click on checkboxes to view products of specific categories. For this I am using jQuery to get products from another php file (works fine).
shop.php:
<input type="checkbox" class="category_btn" name="cat" id="category-books" value="books">
<input type="checkbox" class="category_btn" name="cat" id="category-dvds" value="dvds">
...
<div id="allProducts">
Load dynamic content with jQuery here...
</div>
loadProducts.php:
<?php
$categories = $_POST['categories'];
$productsData = load_products($categories);
for ($i = 0; $i < $amount; $i++) {?>
<div class="singleproduct">
<a href="product.php?id=<?php echo $productsData[$i]['ID'] ?>"><img
src="images/<?php echo get_image($productsData[$i]['ID']) ?>"
alt=""></a>
<p class="prod-title"><?php echo $productsData[$i]['title'] ?></p>
</div>
<?php }?>
jQuery code (shop.php):
<script>
jQuery(document).ready(function($) {
var checkedCats = [];
$(".category_btn:checked").each(function() {
checkedCats.push($(this).val());
});
$(".category_btn").click(function () {
var arraydata = {"categories[]" : checkedCats};
$.post('loadProducts.php', arraydata, function (data) {
var test = $('#allProducts').html(data);
});
});
};
</script>
Now if a user clicks on a product to view details and then returns to shop.php by using the back-button, he will see the main page of the shop with no dynamic loaded content. Is it possible to save the last view with marked checkboxes and loaded products?
I think history.js is the solution, but I have no idea how to do this. Maybe somebody can help...
I have a project in which I am displaying a button tag in a while loop. On every button click I want to display an alert box with the respective UserId. Here is my code:
<?php
$data = mysql_query("Select RegisterId,FName,Image1 from Information where RegisterID='$profileMonth1'") or die(mysql_error());
while ($dis1 = mysql_fetch_array($data)) {
?>
<div id="demo1" value="<?php echo "$RegisterId" ?>">
<button onClick="validate()">Show Interest</button>
</div>
<?php } ?>
Here is my validate function:
function validate1(id2)
{
// var id2;
id2 = document.getElementById('demo2').getAttribute('value');
alert(id2);
}
But it is always showing me last user id .. whereas i want to display userid for every user on everyclick.
Can someone help?
Here man, the function you were calling was undefined validate1, also you don't need to get any arguments on your function declaration, since you are not passing any arguments when you invoke it.
<?php
$data = mysql_query("Select RegisterId,FName,Image1 from Information where RegisterID='$profileMonth1'") or die(mysql_error());
while ($dis1 = mysql_fetch_array($data)) {
?>
<div id="demo" value="<?php echo "$RegisterId" ?>">
<button onClick="validate()">Show Interest</button>
</div>
JS
function validate(){
var id2 = document.getElementById('demo').getAttribute('value');
alert(id2);
}
try this in your code
HTML:
<button onClick="validate('<?php echo $RegisterId; ?>')">Show Interest</button>
Javascript:
function validate(id2)
{
alert(id2);
}
Your code needs some modifications.
Firstly, you have made a provision to send id to javascript function, but, you are not passing id to it.
PHP
<?php
$data = mysql_query("Select RegisterId,FName,Image1 from Information where RegisterID='$profileMonth1'") or die(mysql_error());
while ($dis1 = mysql_fetch_array($data)) {
?>
<div id="demo1" value="<?php echo $dis1['RegisterId'];?>">
<button onClick="validate('<?php echo $dis1['RegisterId'];?>')">Show Interest</button>
</div>
<?php } ?>
Javascript:
function validate1(id2) {
// var id2;
//id2 = document.getElementById('demo2').getAttribute('value');
alert(id2);
}
With this code, your clicks shouldn't even return the last id. Your javascript function is not looking good.
This should work;
<?php
$data = mysql_query("Select RegisterId,FName,Image1 from Information where RegisterID='$profileMonth1'") or die(mysql_error());
while ($dis1 = mysql_fetch_array($data)) {
?>
<!-- removed id attribute, as they're unique, you can't set it to every div.
If you really need id attribute, you can set one by using your RegisterId (e.g. id="demo-<?php echo $RegisterId; ?>)
And moved value attribute to button tag, it's much more useful in it. -->
<div>
<button onClick="validate(this)" value="<?php echo "$RegisterId" ?>">Show Interest</button>
</div>
<?php } ?>
Javascript
function validate(element){
alert(element.value)
}
This way, you can use it in other stuff much easier.
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"];
?>