I am working on a jQuery load more data scroll, which when I click on category link it will sort the data based on that category I click, which is working well. It only load first six how can I fix this issue.
index.php
Category
<div class="container">
<div class="row" id="results"></div>
<div id="loader_image" align="center">
<img src="loader.gif" alt="" width="50">
</div>
<div id="loader_message" align="center"></div>
</div>
<script type="text/javascript">
//For The Scroll
var busy = false;
var limit = 6
var offset = 0;
var where = '<?php if(isset($_GET["where"])) {echo $_GET['where'];} else {echo ' ';} ?>';
function displayRecords(lim, off, where) {
$.ajax({
type: "GET",
async: false,
url: "<?php echo(link);?>getrecords.php",
data: "limit=" + lim + "&offset=" + off + "&where=" + where,
cache: false,
beforeSend: function() {
$("#loader_message").html("").hide();
$('#loader_image').show();
},
success: function(html) {
$("#results").append(html);
$('#loader_image').hide();
if (html == "") {
$("#loader_message").html('<button class="btn btn-default" type="button">No more records.</button>').show()
} else {
// $("#loader_message").html('<button class="btn btn-default" type="button">Loading please wait...</button>').show();
$('#loader_image').show();
}
window.busy = false;
}
});
}
$(document).ready(function() {
// start to load the first set of data
if (busy == false) {
busy = true;
// start to load the first set of data
displayRecords(limit, offset, where);
}
$(window).scroll(function() {
// make sure u give the container id of the data to be loaded in.
if ($(window).scrollTop() + $(window).height() > $("#results").height() && !busy) {
busy = true;
offset = limit + offset;
where = '<?php if(isset($_GET["where"])) {echo $_GET['where'];} else {echo ' ';} ?>';
// this is optional just to delay the loading of data
setTimeout(function() { displayRecords(limit, offset, where); }, 500);
// you can remove the above code and can use directly this function
// displayRecords(limit, offset);
}
});
});
</script>
getrecords.php
$where = '';
if(isset($_GET['where'])){
$search = str_replace('-',' ', $_GET['where']);
$where .= "WHERE category LIKE '%$search%'";
}
$limit = (intval($_GET['limit']) != 0 ) ? $_GET['limit'] : 6;
$offset = (intval($_GET['offset']) != 0 ) ? $_GET['offset'] : 0;
$sql = "SELECT * FROM users {$where} ORDER BY id ASC LIMIT $limit OFFSET $offset";
try {
$stmt = $user->runQuery($sql);
$stmt->execute();
$results = $stmt->fetchAll();
} catch (Exception $ex) {
echo $ex->getMessage();
}
if (count($results) > 0) {
foreach ($results as $res) {
?>
<div class="col-sm-4 my-4 text-center">
<div class="card">
<img class="rounded-circle img-fluid d-block mx-auto" src="http://placehold.it/200x200">
<h3><?php echo ucwords($res['name']); ?></h3>
<small><?php echo $res['category']; ?></small>
</div>
</div>
<?php
}
}
?>
see below preview it image of the issue
If the loading icon is never removed check the console for any errors. You're setting the loading icon to be shown in the beforeSend function but have no error property in the ajax handler.
Remove $("#results").append(html); from the top of your success: function(html) { .. } and move it into the else portion of your if statement. You do this so you're not attempting to append an empty string, or an unwanted string, for no reason and we have finer control over it via our if/else logic.
You'll also want to remove $('#loader_image').show() from the else statement. You're re-showing it even though the ajax call has been processed successfully.
See the cleaned up success function below.
success: function(html) {
$('#loader_image').hide();
if (html == "") {
$("#loader_message").html('<button class="btn btn-default" type="button">No more records.</button>').show()
} else {
$("#results").append(html);
}
window.busy = false;
}
New ajax call:
$.ajax({
type: "GET",
async: false,
url: "<?php echo(link);?>getrecords.php",
data: "limit=" + lim + "&offset=" + off + "&where=" + where,
cache: false,
beforeSend: function() {
$("#loader_message").html("").hide();
$('#loader_image').show();
},
success: function(html) {
$('#loader_image').hide();
if (html == "") {
$("#loader_message").html('<button class="btn btn-default" type="button">No more records.</button>').show()
} else {
$('#results').append(html);
}
window.busy = false;
},
error: function(error) {
console.log(error);
$('#loader_image').hide();
$('#loader_message').html('There was an error processing your request.').show();
}
});
Related
I am displaying ajax likes on number of posts but the problem is that when i click 'like button' the likes (without loading the page) display on first post only and when i refresh the page all the likes display on their own places.
I want to show ajax like on the particular post not on only the first one. I guess i need to pass the ID in success function but i do not know how. Here is the code.
In my code: a Rumor is a post, Like = approve, dislike = disapprove.
View Ajax + That Particular part of Html View
function approve_rumor(r_id) {
// alert("dfdfdf");
$.ajax({
type: "post",
url: "<?php echo base_url('Home1/approve_rumor') ?>",
data: {
r_id: r_id
},
cache: false,
success: function(val) {
if (true) {
$('#showapp').html(val);
} else {
// <?php //echo base_url('Login'); ?>;
alert("You need to Login");
}
}
});
}
<span class="like-listing fll approve" onclick="approve_rumor(<?php echo $rumors->rumor_id; ?>)">
<i class="fa fa-thumbs-o-up" aria-hidden="true"></i>
</span>
<span id="showapp" class="fll"><?php echo $rumors->rumor_totalapprovals ?></span>
Controller
function approve_rumor() {
if ($this - > session - > userdata('user_email', 'user_id')) {
$this - > load - > model('rumor_model');
$r_id = $this - > input - > post('r_id');
$data['user_id'] = $this - > session - > userdata('user_id');
$data['rumor_id'] = $r_id;
$this - > rumor_model - > ApproveRumor($data);
//$this->load->view('home1',['approval'=>$approval]);
} else {
return redirect('Login');
}
}
function ApproveRumor($data) {
// echo "<pre>";
// print_r($data);
// exit;
$r_id = $data['rumor_id'];
$query = $this - > db - > insert('approval', $data);
if ($query) {
$a = $this - > db - > query("SELECT * , count(rumor_id) as count_like FROM approval WHERE rumor_id = $r_id ");
echo "<pre>";
print_r($a - > row() - > count_like);
$totalapprovals = $a - > row() - > count_like;
$this - > db - > query("UPDATE rumors SET rumor_totalapprovals = $totalapprovals WHERE rumor_id = $r_id");
// echo $totalapprovals;
// $this->db->where('rumors.rumor_id',$r_id);
// $res = $this->db->update('rumors',$totalapprovals);
} else {
echo "0";
}
}
A cool way I've found to pass data through to the $.ajax callback function is adding a custom option and then referencing it in the $.ajax callback as this.optionProp:
$.ajax({
type: "post",
url: "your/url/here",
data: {
r_id: r_id
},
r_id:r_id, //Your custom option
cache: false,
success: function(val) {
console.log("r_id: " + this.r_id); //The custom option can be referenced with this.optProp
}
});
Let me know if this helps or is not what you are looking for and we'll get it fixed
You need to return an object from your server side function that has an id attribute so you can call it after success like this:
function approve_rumor(r_id) {
// alert("dfdfdf");
$.ajax({
type: "post",
url: "<?php echo base_url('Home1/approve_rumor') ?>",
data: {
r_id: r_id
},
cache: false,
success: function(val) {
var id = val.id; //gets the id attribute from the returned val Object
}
});
}
I wanted to work with input type ="hidden" so I can do a check. I have a slider which displays products of a category and through two Ajax requests I add and remove them through clicks on buy and remove buttons, however that does not have as much relevance in this question.
Only one such product on the slide can be purchased by order, but if one of them is added and the page is updated and the buy button is clicked again, another of that product is added, which should not happen. I wanted to make sure that in the update of the page, if there is already one of these products added, it is removed, but I do not know where to follow it to complete it.I think I should use an input type ="hidden", so that through it I can save the value of the id of the added product, but I do not know how to do this verification.
Below I will add the code of the buttons and the input that I have already made and are correct, besides the code of the Ajax requisitions. If necessary, I add the code of the controllers I use.
Button and input code:
<button style="margin-left: 11%;" type="button" class="button btn-cart" onclick="addCartao('<?php echo $_product->getId(); ?>')" name="cartaoMensagem<?php echo $_product->getId(); ?>" id="cartaoMensagem<?php echo $_product->getId(); ?>"><span><span><?php echo $this->__('Add to Cart') ?></span></span></button>
<button style="display: none; margin-left: 11%;" type="button" id="cartaoMensagemRemover<?php echo $_product->getId(); ?>" title="Remover" class="button btn-cart" onclick="removeCartaotoCart('<?php echo $_product->getId(); ?>')" name="cartaoMensagem<?php echo $_product->getId(); ?>"><span><span>Remove</span></span></button>
<input type="hidden" name="cartao_adicionado" id="cartao_adicionado" value="" />
Ajax requisition code:
var productSelected = "";
function addCartao(product){
if( productSelected != "" ){
removeCartaotoCart(productSelected); // Remove the item in cart, if there is one.
}
$j('#cartaoMensagem'+product).hide();
$j('#cartaoMensagemRemover'+product).show();
$j('#cartaoMensagemRemover'+product).css({'background-color': '#000000'});
$j.ajax({
type: "POST",
url: "<?php echo Mage::getUrl('fol_carousel/ajax/addCartao') ?>",
data: {
product: product
},
dataType: 'json',
cache : false,
beforeSend: function () {
},
success: function (retorno) {
var button = $j('#cartaoMensagemRemover'+product);
productSelected = product;
$j('#cartaoMensagemAdicionado').val(productSelected);
$j('.item-custom').append('<tr id="trAppend'+product+'"><td class="a-center lc-thumbnails"><img src="' + retorno['imagem'] + '" width="50" height="50" alt="' + retorno['name'] + '"></td><td><h3 class="product-name">' + retorno['name'] + '</h3></td><td class="a-center">1</td><td class="a-right"><span class="cart-price"><span class="price"> R$ ' + retorno['price'] + '</span></span></td></tr>');
getSubTotal();
getGrandTotal();
},
complete: function () {
},
error: function (x,y,z) {
alert("error");
alert(x);
alert(y);
alert(z);
}
});
}
function removeCartaotoCart(itemId){
productSelected = "";
$j('#cartaoMensagemRemover'+itemId).hide();
$j('#cartaoMensagem'+itemId).show();
$j.ajax({
type:"POST",
url:"<?php echo Mage::getUrl('fol_carousel/ajax/removeCartao') ?>",
data:{
itemId: itemId
},
cache: false,
beforeSend: function(){
},
success: function(retorno){
var button = $j('#cartaoMensagemRemover'+itemId);
$j('#cartaoMensagemAdicionado').val(productSelected);
$j('.item-custom #trAppend'+itemId+'').remove();
getSubTotal();
getGrandTotal();
},
complete: function () {
},
error: function (x,y,z) {
alert("error");
alert(x);
alert(y);
alert(z);
}
});
}
What you should do is make a small php code to do the verification, where it contains the SKUs of these products and if they are in the cart, assign a value to a boolean variable and insert it into an input to work this value in jQuery.
Php code for verification:
<?php
$array_de_skus_de_cartoes = array(45,60,80,90,102,103,104,105); //SKUs of products
$isCartaoAdicionado = 0;
$cart = Mage::getModel('checkout/cart')->getQuote();
foreach ($cart->getAllItems() as $item) {
foreach ($array_de_skus_de_cartoes as $sku) {
if($sku == $item->getProduct()->getSku()) {
$isCartaoAdicionado = 1;
$cartao_id = Mage::getModel("catalog/product")->getIdBySku($sku);
}
}
}
if($isCartaoAdicionado == 1) {
?>
<input type="hidden" name="cartao_adicionado" id="cartao_adicionado" value="1" />
<input type="hidden" name="cartao_adicionado_product_id" id="cartao_adicionado_product_id"" value="<?php echo $cartao_id ?>" />
<?php
}
else {
?>
<input type="hidden" name="cartao_adicionado" id="cartao_adicionado" value="0" />
<input type="hidden" name="cartao_adicionado_product_id" id="cartao_adicionado_product_id"" value="" />
<?php
}
?>
Ajax request code updated:
var isCartaoAdicionado = $j('#cartao_adicionado').val();
var isCartaoAdicionadoProductId = $j('#cartao_adicionado_product_id').val();
var productSelected = "";
function addCartao(product){
if(isCartaoAdicionado == 1){
removeCartaotoCart(isCartaoAdicionadoProductId);
}
if( productSelected != "" ){
removeCartaotoCart(productSelected); // Remove the item in cart, if there is one.
}
$j('#cartaoMensagem'+product).hide();
$j('#cartaoMensagemRemover'+product).show();
$j('#cartaoMensagemRemover'+product).css({'background-color': '#000000'});
$j.ajax({
type: "POST",
url: "<?php echo Mage::getUrl('fol_carousel/ajax/addCartao') ?>",
data: {
product: product
},
dataType: 'json',
cache : false,
beforeSend: function () {
},
success: function (retorno) {
var button = $j('#cartaoMensagemRemover'+product);
productSelected = product;
$j('#cartaoMensagemAdicionado'+product).val(productSelected);
$j('.item-custom').append('<tr id="trAppend'+product+'"><td class="a-center lc-thumbnails"><img src="' + retorno['imagem'] + '" width="50" height="50" alt="' + retorno['name'] + '"></td><td><h3 class="product-name">' + retorno['name'] + '</h3></td><td class="a-center">1</td><td class="a-right"><span class="cart-price"><span class="price"> R$ ' + retorno['price'] + '</span></span></td></tr>');
getSubTotal();
getGrandTotal();
},
complete: function () {
},
error: function (x,y,z) {
alert("error");
alert(x);
alert(y);
alert(z);
}
});
}
function removeCartaotoCart(itemId){
productSelected = "";
$j('#cartaoMensagemRemover'+itemId).hide();
$j('#cartaoMensagem'+itemId).show();
$j.ajax({
type:"POST",
url:"<?php echo Mage::getUrl('fol_carousel/ajax/removeCartao') ?>",
data:{
itemId: itemId
},
cache: false,
beforeSend: function(){
},
success: function(retorno){
var button = $j('#cartaoMensagemRemover'+itemId); $j('#cartaoMensagemAdicionado'+itemId).val(productSelected);
$j('.item-custom #trAppend'+itemId+'').remove();
getSubTotal();
getGrandTotal();
},
complete: function () {
},
error: function (x,y,z) {
alert("error");
alert(x);
alert(y);
alert(z);
}
});
}
I'm trying this:
- Onclick on button get this.data-id as id in a DB select
- These data will be dynamically shown in a modal
What I dont know is how to work with ajax, can anyone help?
HTML
<a data-toggle="modal" data-id="'.$method['id'].'" title="Visualizar" class="itemview btn btn-info btn-mini" href="#MethodView">Visualizar</a>
.php
if(!empty($_POST)){
if (isset($_POST['id']) && $_POST['id'] > 0){
$id=$_POST['id'];
GetPaymentMethodView();
}
}
function GetPaymentMethodView() {
global $db;
try{
$query = $db->query("SELECT * FROM payment_methods WHERE id=$id");
$row=$query->fetch(PDO::FETCH_ASSOC);
$result['success'] = true;
$result['result'] = $row;
echo json_encode($result);
return true;
} catch (PDOException $pe) {
return false;
}
}
.js
$('.itemview').click(function (e) {
e.preventDefault();
var uid = $(this).data('id');
$.ajax({
type: "POST",
url: "resources/controllers/get.php",
data: 'id='+uid,
dataType: "json",
success: function (data) {
if (data.success) {
console.log(data.result);
console.log(data.result.id);
} else {
alert("error");
}
}
});
});
In page where you want to display result put something like this
<div class="result"></div>
In try small modification
try{
$query = $db->query("SELECT id, name, bank_info FROM payment_methods WHERE id=$id");
$row=$query->fetch(PDO::FETCH_ASSOC);
$result['success'] = true;
$result['result'] = $row;
echo json_encode($result);
exit;
return true;
}
In js small editing
success: function (data) {
if (data.success) {
//How to show rows in php?
console.log(data.result);
console.log(data.result.id);
var result = data.result;
//prepare markup
var resultHtml = '';
resultHtml += '<p>Id = ' + result.id +'</p>';
resultHtml += '<p>Name = ' + result.name +'</p>';
resultHtml += '<p>Bankinfo = ' + result.bank_info +'</p>';
//Put markup in div
$(".result").html(resultHtml)
} else {
alert("error");
}
}
And see in browser console to understand.
As both code is in same page you can perform this without js/jQuery too, for that just add value of $method['id'] directly to <input>.
See below to understand
Remove value of $method['id'] from <a> tag
<a data-toggle="modal" data-id="" title="Visualizar" class="itemview btn btn-info btn-mini" href="#MethodView">Visualizar</a>
Add value directly to <input> tag
<input type="text" name="methodid" id="methodid" value = "<?php echo $method['id']; ?>" />
And problem solved without js. :) So remove js stuff.
I wrote a AJAX search function which grabs the keyword values on key up and fires off the script. My goal is to have it populate the content area every key reordering the results to be in ABC order.
Instead what's happening is the first key fires off and the top result is always this
*ENGRAVING
then the rest of the values under it are in no specific order that I can tell.
I think this has to do with escaping characters?
Any help would be appreciated. Please help me get this to function so as a user searches the content area reorders itself being in order based on the keyword being searched up to the value that has been entered at that time.
On page load 5 results are added to the page then on page scroll more results are added to the page like this,
var assetPath = "<?php echo $assetPath ?>";
var searchPath = "<?php echo $searchPath ?>";
function displayRecords(lim, off) {
jQuery.ajax({
type: "GET",
async: false,
url: assetPath,
data: "limit=" + lim + "&offset=" + off,
cache: false,
beforeSend: function() {
$("#loader_message").html("").hide();
$('#loader_image').show();
},
success: function(html) {
$("#productResults").append(html);
$('#loader_image').hide();
if (html === "") {
$("#loader_message").html('<button data-atr="nodata" class="btn btn-default" type="button">No more records.</button>').show();
} else {
$("#loader_message").html('Loading... Please wait <img src="http://www.example.com/monstroid/wp-content/uploads/2016/02/LoaderIcon.gif" alt="Loading">').show();
}
window.busy = false;
}
});
}
Then when a user wants to search they use this form,
<div class="form-group pull-right">
<input type="text" name="itemID" id="itemID" class="search form-control" placeholder="Search product number">
</div>
Then this ajax function fires off on keyup
$("#itemID").keyup(function (){
var itemID = $(this).val();
var url = searchPath;
$.ajax({
type : "GET",
async : false,
url : url,
data : "itemID=" + encodeURIComponent(itemID),
cache : false,
success: function(html) {
$('#loader_image').hide();
$( "#productResults" ).replaceWith( html );
if (html === "") {
$("#loader_message").html('<p>There were no results that match your search criteria</p>').show();
} else {
$("#loader_message").html('Searching... Please wait <img src="http://www.example.com/monstroid/wp-content/uploads/2016/02/LoaderIcon.gif" alt="Loading">').show();
}
window.busy = false;
}
});
});
which runs this script at searchPath as the path variable
require_once ('Dbconfig.php');
$sql=" SELECT * FROM wuno_inventory WHERE wuno_product like '%".$itemID."%' OR wuno_alternates like '%".$itemID."%' ORDER BY wuno_product ";
try {
$stmt = $DB_con->prepare($sql);
$stmt->execute();
$results = $stmt->fetchAll();
} catch (Exception $ex) {
echo $ex->getMessage();
}
if (count($results) > 0) {
foreach ($results as $res) {
echo '<tr class="invent">';
echo '<td>' . $res['wuno_product'] . '</td>';
echo '<td>' . $res['wuno_alternates'] . '</td>';
echo '<td>' . $res['wuno_description'] . '</td>';
echo '<td>' . $res['wuno_onhand'] . '</td>';
echo '<td>' . $res['wuno_condition'] . '</td>';
echo '</tr>';
}
}
The initial data populates perfectly in order from what is in the database. So I do not see why there would be problems for this function if it is a escaping situation.
Also the initial data is paginated. Would this cause a problem with the second query? I was thinking maybe since there is so much data it's all being appended to the content instead of replacing it. Maybe the jquery is conflicting?
Try introducing the timeout for your AJAX call. Move your AJAX JS into a separate function first:
function get_search_results(event) {
var itemID = $(event.target).val();
var url = searchPath;
$.ajax({
type : "GET",
async : false,
url : url,
data : "itemID=" + encodeURIComponent(itemID),
cache : false,
success: function(html) {
$('#loader_image').hide();
$( "#productResults" ).replaceWith( html );
if (html === "") {
$("#loader_message").html('<p>There were no results that match your search criteria</p>').show();
} else {
$("#loader_message").html('Searching... Please wait <img src="http://www.example.com/monstroid/wp-content/uploads/2016/02/LoaderIcon.gif" alt="Loading">').show();
}
window.busy = false;
}
});
}
Then add it to your keyup handler:
$("#itemID").keyup(function (){
setTimeout(get_search_results, 200);
});
I have status active/Deactive Buttons when user clicks on active status it turns into deactive with red color and vice versa
currently i'm able to update my status #backend but everytime i should refresh to see my changes!!
my requirement is during active/deactive process of changing status i want to load ajax image loader where loader image should overlay entire screen. and my status should be updated in mysql db!!
please any help is appricated Thanks!
Php Code
<?php
include 'db.php';
$sql = "select * from sections order by id asc";
$data = $con->query($sql);
$str='';
if($data->num_rows>0)
{
while( $row = $data->fetch_array(MYSQLI_ASSOC))
{
$str.="
"?>
<div class="row">
<div class="col-md-1">
<?php
if ($row['status'] == '1')
{
?>
<a href="#" class="btn btn-success btn-sm active" ida='<?php echo $row['id'];?>'></a>
<?php }
else if($row['status'] == '0')
{
?>
<a href="#" class="btn btn-danger btn-sm deactive" idde='<?php echo $row['id'];?>'></a>
<?php } ?>
</div>
</div>
<?php
}
}
else
{
$str .= "<p style='text-align:left;'>No Data Available</p>";
}
echo $str;
?>
Jquery Code
<script type="text/javascript">
$('body').delegate('.active','click',function(e){
var IdStatus = 0;
var id = $(this).attr('ida');
$.ajax({
url:"pages/status1.php",
data:{
status:IdStatus,
id:id
},
dataType:'html',
success:function()
{
alert('success');
}
});
e.preventDefault();
return false;
});
$('body').delegate('.deactive','click',function(e){
var IdStatus = 1;
var id = $(this).attr('idde');
$.ajax({
url:"pages/status1.php",
data:{
status:IdStatus,
id:id
},
dataType:'html',
success:function()
{
alert('success');
}
});
e.preventDefault();
return false;
});
</script>
PHP Updation Code
<?php
if(isset($_REQUEST['status']))
{
$status = $_REQUEST['status'];
$id = $_REQUEST['id'];
$sql = 'update sections set status='.$status.' where id='.$id.'';
$result = mysql_query($sql);
if($result)
{
echo 'updated successfully';
}
else
{
echo 'failed to update';
}
}
?>
Try this script with mentioned changes:
Changes:
Keep same attribute as data-id for both the operations
loaderElem will be the loader container which should be there in your DOM
BODY is nothing but a body selector, just to avoid redundant selectors
var elem = $(this); is used as I need this reference after success callback
Also make habit of using error callback as you might need to handle that case
var BODY = $('body');
var loaderElem = $('#loader');
BODY.delegate('.active', 'click', function(e) {
loaderElem.show();
var IdStatus = 0;
var elem = $(this);
var id = elem.attr('data-id');
$.ajax({
url: "pages/status1.php",
data: {
status: IdStatus,
id: id
},
dataType: 'html',
success: function() {
elem.removeClass('active').addClass('deactive');
loaderElem.hide();
alert('success');
}
});
e.preventDefault();
return false;
});
BODY.delegate('.deactive', 'click', function(e) {
loaderElem.show();
var IdStatus = 1;
var elem = $(this);
var id = elem.attr('data-id');
$.ajax({
url: "pages/status1.php",
data: {
status: IdStatus,
id: id
},
dataType: 'html',
success: function() {
elem.removeClass('deactive').addClass('active');
loaderElem.hide();
alert('success');
}
});
e.preventDefault();
return false;
});
Try using beforeSend option of $.ajax()
$('body').delegate('.active','click',function(e){
var IdStatus = 0;
var id = $(this).attr('ida');
$.ajax({
url:"pages/status1.php",
beforeSend: function() {
// do overlay stuff
},
data:{
status:IdStatus,
id:id
},
dataType:'html',
success:function()
{
// remove overlay stuff
alert('success');
}
});
e.preventDefault();
return false;
});