I am updating a span using below script but it is working if condition is false and if condition is true it does not update.
What i observed that it executes the same false condition and when i click the second time it updates the quantity but less 1 number than the actual quantity of records in the database.
Like total records are 2 and when i click submit the script runs and if condition is true in the database records are updated = 3 but in the span it shows 2.
When i click 2nd time and in the database records are = 4 and in the span it shows 3.
Button where i click and run the script
<input onclick='updateTitems("1");' type="submit" class="btn-style-2 mg-left-5" value="ADD TO CART">
script
<script>
function updateTitems(id) {
var uid = "<?php echo $ses_mem; ?>";
$.ajax({
type: "GET",
url: 'inc/menu_update_total_items.php',
data: "id=" + id + "&uid=" + uid,
success: function(data) {
$('.summary12').html(data);
}
});
}
</script>
menu_update_total_items.php
$user_id = $_GET['uid'];
$item = "select count(*) as records
from orders_temp
where user_id = '".$user_id."'
";
$itemq = $dba->query($item);
$itemr = $itemq->fetch_assoc();
$count = $itemr['records'];
---------------------------------
$itemx = "select count(*) as records
from orders_temp
where date = now()
and user_id = '".$user_id."'
";
$itemqx = $dba->query($itemx);
$itemrx = $itemqx->fetch_assoc();
$check = $itemrx['records'];
<span class="summary12"><!-- class of javascript -->
<?php
if ($check == 1){
echo $count+1;
}else{
echo $count;
}
?>
Items
</span>
After trying lot of things i came up with the following solution and the issue has been solved.
Please need your opinion on this. Thanks
Button
<input onclick='updateTitems();' type="submit" class="btn-style-2 mg-left-5" value="ADD TO CART">
Script
function updateTitems(){
$.ajax({
url: "menu_update_total_items.php",
cache: false,
success: function(data){
$(".summary12").html(data);
//div or span reload script after success
setInterval(function () {
$('.summary12').load('inc/menu_update_total_items.php');
}, 1000);
}
});
}
menu_update_total_items.php
<?php
#session_start();
include ("inc/db.php");
$ses_mem = session_id();
$items = "select count(*) as trecords
from orders_temp
where user_id = '".$ses_mem."' ";
$item = $dba->query($items);
$count = $toitemszx->fetch_assoc();
?>
<a href="cart/review" class="cart-link">
<i class="fa fa-shopping-basket"></i>
<?php echo $count['trecords']; ?>
Items
</a>
Related
I have 2 php files, the first file is the index file where the pagination is found, and an ajax script for getting the table data which is found on the second file.
The ajax script from the first file is also sending sorting option that the user requested to the second file. The second file will then sort and calculate the number of result that is found.
Since the pagination is in first file, I need the result from the second file to calculate the proper number of pages for my pagination.
I have this pagination script
<ul class="pagination mx-1 mx-md-0">
<?php
if(!empty($total_pages)){
for($i=1; $i<=$total_pages; $i++){
if($i == 1){
?>
<li class="pageitem active" id="<?php echo $i;?>">
<a href="JavaScript:Void(0);" data-id="<?php echo $i;?>" class="page-link" ><?php echo $i;?></a>
</li>
<?php
}
else {
?>
<li class="pageitem" id="<?php echo $i;?>">
<?php echo $i;?>
</li>
<?php
}
}
}
?>
</ul>
I have this ajax script for my first file
$("#target-content").load("pagination.php?page=1");
$(".page-link").click(function(){
var id = $(this).attr("data-id");
var sort = $("#myselect").val();
var select_id = $(this).parent().attr("id");
var categorytype = MyApp.categorytypes;
$.ajax({
url: "secondfile.php",
type: "GET",
data: {
page : id,
sorted:sort,
categorytype:categorytype
},
cache: false,
success: function(dataResult){
$("#target-content").html(dataResult);
$(".pageitem").removeClass("active");
$("#"+select_id).addClass("active");
}
});
});
for my 2nd file I have this code
<? php
$limit= 2;
$sqls = "SELECT COUNT(id) FROM producttable $categorytypes ORDER BY $sortertype
$sorterorder LIMIT $start_from, $limit";
$rs_results = mysqli_query($conn, $sqls);
$row = mysqli_fetch_row($rs_results);
$total_records = $row[0];
$total_pages = ceil($total_records / $limit);
?>
and to pass my data to the first file I tried creating another ajax script
$(document).ready(function() {
var numb = <?php echo $total_pages ?>;
$.ajax({
url: "inde.php",
type: "GET",
data: {
numb:numb
}
});
});
and tried to get the values in the first file using GET [] but it seems that it doesn't work. Am I doing something wrong here? should I rewrite my whole code?
My displayed tables are going well, its just the number of pages that are shown when I'm sorting the data in my table.
Here is what I would do. Drop that last code bit you showed and in your second .php file echo out the total_pages like this
<? php
$limit= 2;
$sqls = "SELECT COUNT(id) FROM producttable $categorytypes ORDER BY $sortertype
$sorterorder LIMIT $start_from, $limit";
$rs_results = mysqli_query($conn, $sqls);
$row = mysqli_fetch_row($rs_results);
$total_records = $row[0];
$total_pages = ceil($total_records / $limit);
echo $total_pages;
?>
then in your ajax script, update your pagination using JS and you have your $total_pages passed through as dataResult
$.ajax({
url: "secondfile.php",
type: "GET",
data: {
page : id,
sorted:sort,
categorytype:categorytype
},
cache: false,
success: function(dataResult){
// dataResult will contain $total_pages
$("#target-content").html(dataResult);
$(".pageitem").removeClass("active");
$("#"+select_id).addClass("active");
updatePagination(dataResult);
}
});
I will describde the problem as straight as I can, so:
I've got website, on which I have button, by clicking which I want to run AJAX, which would run .php code which will update database records.
Right now, with code below Im not getting any errors, and also database is at the same state as it was before clicking button. What's more I guess that ajax doesnt works properly, as the website refreshes as I click update button.
Any 1? Anything?
Here goes main php (updated):
<form role='form' method='post' action='' autocomplete='off'>
<input type='submit' id='addBidSlow' name='addBidSlow' value='Slow bid' class='btn btn-inline-block btn-success auctionDetails' tabindex='1'>
</form>
</td>
</tr>
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script>
$("#addBidSlow").click(function(){
var bidAuthor = "<?php echo $_SESSION['username']; ?>";
var itemID = <?php echo $_GET['id']; ?>;
$.post(
"addBidSlow.php",
{bidAuthor: bidAuthor, itemID: itemID},
false
);
});
</script>
And updater php:
<?php
require('includes/config.php');
$bid = 1000;
$bidAuthorPoints = "";
$finalPoints = "";
$finalDate = "";
$todayDate = date("Y-m-d H:i:s");
$stmt = $db->prepare("SELECT itemID, endTime FROM items WHERE itemID = :itemID");
$stmt->execute(array(':itemID' => $itemID));
while($row = $stmt->fetch(PDO::FETCH_OBJ)) {
$finalDate = $row->endTime;
}
$addedTime = strtotime($finalDate) + 60*10;
$finalDate2DB = date('Y-m-d H:i:s' , $addedTime);
$stmt = $db->prepare("UPDATE items SET endTime = :finalDate2DB WHERE itemID = :itemID");
$stmt->execute(array(
':itemID' => $itemID,
':finalDate2DB' => $finalDate2DB
));
?>
I Have problem, I have ajax request and php script, when I click button, results duplicate.
HTML AND JS:
$("#more-news").click(function(e) {
e.preventDefault();
$.ajax({ //create an ajax request to load_page.php
type: "GET",
url: "/getnews.php",
dataType: "html", //expect html to be returned
data: {
lang: lng,
last_id: last_id,
ids: dataN
},
success: function(response){
var content = document.getElementById("responsecontainer");
content.innerHTML = content.innerHTML+response;
//$("#responsecontainer").html(response);
$('#more-news').attr('data-lim', Number($('#more-news').attr('data-lim')) + 10);
//alert(response);
}
});
});
<div id="responsecontainer"></div>
<div style="text-align: center;">
<button id="more-news" data-lim="10" style="border:none" class="btn-type-one">
<span class="more"><?= $this->trans->t('More'); ?></span>
</button>
</div>
<?php
$dtTTNews = [];
foreach ($front_page_news as $item) {
$dtTTNews[] = $item['id'];
?>
<? } ?>
<script>
var dataN = <?php echo json_encode($dtTTNews); ?>;
var lng = '<?=$lang?>';
var last_id = '<?=end($dtTTNews)?>';
</script>
PHP:
$ids = $_GET['ids'];
$dtNow = new \DateTime('now');
$db->set_charset("utf8");
$news_id = abs($db->real_escape_string($_GET['last_id']));
$date_now = new \DateTime('now');
$in = join(',', array_fill(0, count($ids), '?'));
//$q = $db->query("select * count(*)
$q = $db->query('SELECT * FROM news WHERE id < "'.$news_id.'" ORDER BY date_show DESC LIMIT 3');
//$q = $db->query('SELECT id, title_ru, title_md, body_ru, body_md, is_video, thumb_ru, thumb_md, date_show,title_ru, title_md
//FROM news GROUP BY id');
$lang = (isset($_GET['lang']) && $_GET['lang'] == 'ru') ? 'ru' : 'md';
$isHidden = false;
if($q->num_rows > 0):
while($item = $q->fetch_assoc()):
$dtNews = new \DateTime($item['date_show']);
if ($dtNews > $dtNow) {
$isHidden = true;
break;
}
$qs = $db->query("SELECT * FROM news_categories WHERE news_id = " . $item['id']);
if($qs->num_rows > 0) {
$dd = $qs->fetch_assoc();
$qss = $db->query("SELECT * FROM categories WHERE id = " . $dd['categories_id']);
$dd2 = $qss->fetch_assoc();
if(in_array('Скрытые новости', $dd2) || in_array('Hidden News', $dd2)) {
$isHidden = true;
break;
}
}
$dtShow = $dtNews->format("Y-m-d");
//$dtShow = \Noitools\Utils::timeFromPost($item['date_show'], $lang);
if($item['active'] == '1'):
if($item['body_' . $lang] != ''):
if(!$isHidden):
?>
<div class="article-item" data-news="<?= $item['id']; ?>">
<a href="/<?=$lang?>/news_id/<?=$item['id']?>"
class="link-img-wrap<?= ($item['is_video']) ? ' video-icon-medium' : ''; ?>">
<img src="/uploads/newsthumbs/760_500/<?=$item['id']?>.jpg"
alt="">
</a>
<div class="details-post">
<i><?=$dtShow?></i>
<?= $dd2['title_' . $lang] ?>;
</div>
<h3><a href="/<?=$lang?>/news_id/<?=$item['id']?>"><span
class="detail-title"><?=$dtShow?></span> <?= $item['title_' . $lang] ?></a></h3>
<p class="small-text">
<?= mb_substr(strip_tags($item['body_' . $lang]), 0, 180,
'utf-8') ?>
</p>
</div>
<?php endif; endif; endif; endwhile; endif; ?>
How I Can Fix this duplicates? I think, because LIMIT 3, when I click button he load 3 same elements ..
I want when I click button more, load 3 more news
On first glance it appears that the problem lies with you SQL statement:
$q = $db->query('SELECT * FROM news WHERE id < "'.$news_id.'" ORDER BY date_show DESC LIMIT 3');
Since you are appending the Ajax results each time, you only want to fetch news results that you haven't fetched before. By using less than, you are fetching ALL results less than $news_id, each time.
What you need to do is to window your results. In other words, you need to have a starting id and then fetch several more records. So:
$q = $db->query('SELECT * FROM news WHERE id > "'.$news_id.'" ORDER BY date_show DESC LIMIT 3');
And as long as you keep passing the new id (last_id in your javascript), as the last record fetched, it should work.
The other problem you may have is your ordering. You need to order the same way that you are comparing. If comparing by id, you need:
$q = $db->query('SELECT * FROM news WHERE id > "'.$news_id.'" ORDER BY id ASC LIMIT 3');
If comparing by date then something like:
$q = $db->query('SELECT * FROM news WHERE date_show < "'.$date_show.'" ORDER BY date_show DESC LIMIT 3');
You can't mix both id and date_show. Unless you know that id and date_show are strictly in the same order.
This question already has an answer here:
Function doesn't work after appending new element
(1 answer)
Closed 5 years ago.
Extremely new to JavaScript, jquery and ajax and am having difficulties with a very basic set of scripts to load more data from a database on button clicks.
The first time I click load more, it works. But the 2nd clicks do not pass the values and does nothing.
Here is the main script that loads data once and includes the jquery, ajax stuff.
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#btn1, #btn2").click(function() {
pagenum = $(this).val();
val = "Loading page " + pagenum + "...";
$(this).text(val);
$.ajax({
type: "POST",
url: "loadmore.php",
data: {page: pagenum},
success: function(response){
if(response){
$("#btn1").hide();
$("#div1").append(response);
}
}
});
});
});
</script>
</head>
<?php
// main.php contains db connection
include('main.php');
$rowsperpage = 2;
$q = "SELECT col1, col2 from mytableORDER BY col1 LIMIT $rowsperpage OFFSET 0";
$r = pg_exec($dbconnect, $q);
echo "<div id='div1' style='margin:10px;'>";
while ($row = pg_fetch_row($r) ) {
echo "<div>$row[1]</div>";
}
echo "<button id='btn1' value=2>Load More</button>";
echo "</div>";
?>
And here is the script fetched more data to display.
<?php
include('../config.php');
include('functions.php');
$rowsperpage = 2;
if(isset($_POST['page'])) {
$paged=$_POST['page'];
} else {
$paged = 1;
}
if($paged > 1) {
$rowoffset = $rowsperpage * ($paged -1);
$limit = " LIMIT $rowsperpage OFFSET $rowoffset";
} else {
$limit = " LIMIT $rowsperpage OFFSET 0 ";
}
$q = "select subindustryid, subindustry from sub_industries ORDER BY subindustry $limit";
$r = pg_exec($dbconnect, $q);
while ($row = pg_fetch_row($r) ) {
echo "<div>$row[1]</div>";
}
$nextpage = $paged + 1;
echo "<button id='btn1' value=$nextpage>Load even more </button>";
?>
The problem is the the 2nd button is displayed and nothing happens when it gets clicked.
Thank for your time!
The problem is the event binding. Change this line-
$("#btn1, #btn2").click(function() {
to this line
$("#div1").on("click","#btn1, #btn2",function(){
Also your php returns a button with id btn1 and not btn2
Read about jQuery Event bindings here: https://learn.jquery.com/events/handling-events/ and http://learn.jquery.com/events/event-delegation/
Actually id identifiers should be unique- this is general convention. You have load more button with id="#btn1" and hiding old button appearing new button from the response text form ajax by hiding and appending- but you can manage such with out sending button in response text-
Have following changes on your html page
value should be quoted <button id="btn1" value="2">Load More ... </button>
Make use of dedicated function calling in jQuery like- $(document).on('event','dom_identifiers',callbackfunction(){})
In ajax don't need to hide current button which is clicked, instead of hiding the button just add new records fetched before the load more button by using before() function of jQuery
For next page you can increase the value of current button
$(document).ready(function(){
// dedicated function calling
$(document).on('click','#btn1',function() {
pagenum = $(this).val();
val = "Loading page " + pagenum + "...";
$(this).text(val);
$.ajax({
type: "POST",
url: "loadmore.php",
data: {page: pagenum},
success: function(response){
if(response){
// increase the value load more
$("#btn1").val(parseInt($("#btn1").val())+1);
// add response data just before the loadmore button
$("#btn1").before(response);
}
}
});
});
});
button should be like
echo "<button id='btn1' value="2">Load More</button>";
Now in fetching php page please remove these two lines-
$nextpage = $paged + 1;
echo "<button id='btn1' value=$nextpage>Load even more </button>";
I am making a temperature target page where the form will read the current target, allow the user to +/- by 0.5 using Javascript buttons and then 'set' the target which takes the new value and saves it back to the database.
I have a working page which can read the DB value and set it, but then automatically reverts to '0.0' as the target. If the page is refreshed then it will display the target, but sometimes saves it at 0.0 in the DB.
I'm very confused as to why as I've spent far too long on this, but its bugging me! Any help is much appreciated, thanks.
Here is my code:
<?php
$conn = connect DB stuff here...
$queryTarget = "SELECT * FROM target;";
$result2 = $conn->query($queryTarget);
$conn->close();
if ($result2->num_rows > 0) {
while($row = $result2->fetch_assoc()) {
$target = $row['target'];
}
}
?>
<form id="input" method="post" action="">
Temp <input type="text" value="<?php echo $target; ?>" name="temp" id="temp" >
<input type="button" id="Up" value="up" / >
<input type="button" id="Down" value="down"/ >
<input type="submit" id="submit" value="submit " name="submit">
</form>
<?php
$conn = connect DB stuff here...
$temp = $_POST['temp'];
$updateTarget = "UPDATE target SET target = '";
$updateTarget = $updateTarget . $temp . "' WHERE id = 1;";
$result = $conn->query($updateTarget);
$conn->close();
?>
<script>
var min = 15,
max = 25;
$("#Up").click(function(){
if($("#temp").val() < 25 && $("#temp").val() >= 15)
$("#temp").val(Number($("#temp").val()) + 0.5);
});
$("#Down").click(function(){
if($("#temp").val() <= 25 && $("#temp").val() > 15)
$("#temp").val(Number($("#temp").val()) - 0.5);
});
</script>
<script>
$(document).ready(function(){
$('#submit').click(function(){
var srt = $("#input").serialize();
// alert is working perfect
alert(srt);
$.ajax({
type: 'POST',
url: 'form.php',
data: srt,
success: function(d) {
$("#input").html(d);
}
return false;
});
});
});
</script>
just echo this temp value
<?php
//$conn = connect DB stuff here...
$temp = $_POST['temp'];
or
print_r($_POST);
echo $temp;
die();
$updateTarget = "UPDATE target SET target = '";
$updateTarget = $updateTarget . $temp . "' WHERE id = 1;";
then check alert if alert show right data then
then use single query like this
$updateTarget = "UPDATE target SET target = '$temp' WHERE id = 1";
//i think it will help you to find issue
$result = $conn->query($updateTarget);
$conn->close();
?>
and your javascript function need to update
<script>
$(document).ready(function(){
$('#submit').click(function(){
var srt = $("#input").serialize();
// alert is working perfect
alert(srt);
$.ajax({
type: 'POST',
url: 'form.php',
data: srt,
success: function(d) {
alert(d);
$("#input").html(d);
}
});
return false;
});
});
</script>
if you find right data then check your db structure that is it allow float etc. i think it will work
you can also check this
How to Search value from input by mysqli in database