PHP Ajax live search with load more - javascript

I would like if I scroll bottom of .dropdown-menu, load more 7 row in database. I don't know why not using this script.
I'm using bootstrap css and js.
I tried the bootstrap-select.js with live search, but I have 2000 row in "town" database, and bootstrap-select doesn't have "load more" function.
<meta charset="utf-8">
<link rel="stylesheet" href="bootstrap.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script src="bootstrap.js"></script>
<style>.dropdown-menu{height: auto;max-height: 150px;overflow-x:hidden;}</style>
<div class="dropdown">
<input class="dropdown-toggle" data-toggle="dropdown" id="live" placeholder="Town">
<ul class="dropdown-menu"></ul>
</div>
<script>
$(document).ready(function () {
var limit = 7;
var start = 0;
var action = 'inactive';
var location = $('#live').val();
$('.dropdown-menu').hide();
function search() {
var limit = 7;
var start = 0;
var action = 'inactive';
var location = $('#live').val();
if (location != '') {
$('.dropdown-menu').show();
$.ajax({
url: "search.php",
type: "POST",
data: {location:location, limit:limit, start:start},
cache: false,
success: function(data) {
$('.dropdown-menu').html(data);
if(data == '') {
$('#load').text('No more data.');
action = 'active';
} else {
$('#load').text('Loading...');
action = 'inactive';
}
$('.dropdown-menu li a').click(function() {
$('.dropdown-menu li a').removeClass('active');
$(this).addClass('active');
var active = $('li a.active').html();
$('#live').val(active);
});
}
});
} else {
$('.dropdown-menu').hide();
$('.dropdown-menu li a').removeClass('active');
}
};
if (action == 'inactive') {
action = 'active';
$('#live').on('keyup change', search);
}
$(window).scroll(function(){
if ($(window).scrollTop() + $(window).height() > $(".dropdown-menu").height() && action == 'inactive') {
action = 'active';
start = start + limit;
setTimeOut(function(){
$('#live').on('keyup change', search);
}, 1000);
}
});
});
</script>
search.php:
<?php
$connect = mysqli_connect("localhost", "root", "", "mydb");
$location = $connect->real_escape_string($_POST["location"]);
if (isset($_POST["location"])) {
$data = mysqli_query($connect, "SELECT * FROM towns WHERE town LIKE '%".$location."%' ORDER BY id LIMIT ".$_POST["start"].", ".$_POST["limit"]."");
$data_count = mysqli_num_rows($data);
if ($data->num_rows === 0) {
echo '<li>No data!</li>';
} else {
while ($row = mysqli_fetch_array($data)) {
echo '<li>'.$row["town"].'</li>';
}
echo '<div id="load"></div>';
}
}
?>

Maybe this is not neatly finished code, but I've added a loadMore button & attached search function to the click event of it.
The modified HTML code:
<html>
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="bootstrap.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script src="bootstrap.js"></script>
<style>.dropdown-menu{height: auto;max-height: 150px;overflow-x:hidden;}</style>
</head>
<body>
<div class="dropdown">
<input class="dropdown-toggle" data-toggle="dropdown" id="live" placeholder="Town">
<ul class="dropdown-menu"></ul>
<button type="button" id="loadMore" style="display: none;"></button>
</div>
<script>
function search() {
if (location != '') {
$('.dropdown-menu').show();
$.ajax({
url: "search.php",
type: "POST",
data: {location:location, limit:limit, start:start},
cache: false,
success: function(data) {
$('.dropdown-menu').html(data);
if(!data) {
$('#load').text('No more data.');
action = 'active';
} else {
$('#load').text('Loading...');
action = 'inactive';
}
$('.dropdown-menu li a').click(function() {
$('.dropdown-menu li a').removeClass('active');
$(this).addClass('active');
var active = $('li a.active').html();
$('#live').val(active);
});
start = start + limit;
$('#loadMore').show();
}
});
} else {
$('.dropdown-menu').hide();
$('.dropdown-menu li a').removeClass('active');
}
}
$(document).ready(function () {
limit = 7;
start = 0;
action = 'inactive';
location = $('#live').val();
$('.dropdown-menu').hide();
if (action == 'inactive') {
action = 'active';
$('#loadMore').on('click', search);
$('#live').on('keyup change', search);
}
$(window).scroll(function(){
if ($(window).scrollTop() + $(window).height() > $(".dropdown-menu").height() && action == 'inactive') {
action = 'active';
start = start + limit;
setTimeOut(function(){
$('#live').on('keyup change', search);
$('#loadMore').on('click', search);
}, 1000);
}
});
});
</script>
</body>
</html>

Related

setInterval is not working correct with Load More script

I am working on Ajax,Right now i am fetching data from database suceessfully with "Load More" functionality
Means My data is displaying correctly after scroll down,But now i want to call function after every 10 seconds
But its giving me "wrong data",Means records are not fetching properly
Here is my current code
<script>
$(document).ready(function(){
var limit = 7;
var start = 0;
var action = 'inactive';
function lazzy_loader(limit)
{
var output = '';
for(var count=0; count<limit; count++)
{
output += '<div class="post_data">';
output += '<p><span class="content-placeholder" style="width:100%; height: 30px;"> </span></p>';
output += '<p><span class="content-placeholder" style="width:100%; height: 100px;"> </span></p>';
output += '</div>';
}
$('#load_data_message').html(output);
}
lazzy_loader(limit);
function load_data(limit, start)
{
var wallet_address="<?php echo $WalletAddress; ?>";
$.ajax({
url:"<?php echo base_url(); ?>Main/fetch",
method:"POST",
data:{limit:limit, start:start,wallet_address:wallet_address},
cache: false,
success:function(data)
{
if(data.trim()=='')
{
$('#load_data_message').html('<h3>No More Result Found</h3>');
action = 'active';
}
else
{
$('#load_data').html("");
$('#load_data').append(data);
$('#load_data_message').html("");
action = 'inactive';
}
}
})
}
if(action == 'inactive')
{
action = 'active';
load_data(limit, start);
}
$(window).scroll(function(){
if($(window).scrollTop() + $(window).height() > $("#load_data").height() && action == 'inactive')
{
lazzy_loader(limit);
action = 'active';
start = start + limit;
setTimeout(function(){
load_data(limit, start);
}, 1000);
}
});
});
</script>
And for call function after 10 seconds i added following function,but data is not fetching in correctly,Means random data showing
Where i am wrong ?
window.setInterval(function(){
if($(window).scrollTop() + $(window).height() > $("#load_data").height() && action == 'inactive')
{
var limit = 7;
var start = 0;
action = 'active';
load_data(limit, start);
}
}, 10000);

how to limit the click event in jquery loop?

I would like to limit click event loop in jquery. I have categories list which will have in the following format and also after 5 click in the loop i have to disable click event.
<div class="col-md-2 col-sm-4 col-xs-6 home_s">
<a class="get_category" id="36" href="javascript:void(0)">
<img class="img-responsive img-center" src="">
<span>xxxxx</span>
</a>
<input type="hidden" value="36" id="categories36" name="categories[]">
</div>
$(document).ready(function() {
$(".get_category").on('click', function() {
var cat_id = $(this).attr('id');
var cat_value = $("#categories" + cat_id).val('');
if ($("#categories" + cat_id).val() == '') {
$("#categories" + cat_id).val(cat_id);
} else {
alert("hi");
$("#categories" + cat_id).val('');
}
})
});
You can use off() to unbind event handler
$(document).ready(function() {
// variable for counting clicks
var i = 1;
var fun = function() {
var cat_id = $(this).attr('id');
var cat_value = $("#categories" + cat_id).val('');
if ($("#categories" + cat_id).val() == '') {
$("#categories" + cat_id).val(cat_id);
} else {
alert("hi");
$("#categories" + cat_id).val('');
}
// checking and increment click count
if (i++ == 5)
// unbinding click handler from element
$(".get_category").off('click', fun);
};
$(".get_category").on('click', fun);
});
Example :
$(document).ready(function() {
var i = 1;
var fun = function() {
alert('clicked'+i);
if (i++ == 5)
$(".get_category").off('click', fun);
};
$(".get_category").on('click', fun);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<button class="get_category">click</button>
If you have multiple .get_category in your html the solution from Pranav C Balan won't work.
$(document).ready(function() {
function clickFunc() {
var click_count = $(this).data('click-count') || 0;
var cat_id = $(this).attr('id');
var cat_value = $("#categories" + cat_id).val('');
if ($("#categories" + cat_id).val() == '') {
$("#categories" + cat_id).val(cat_id);
} else {
alert("hi");
$("#categories" + cat_id).val('');
}
if (++click_count >= 5)
$(this).off('click', clickFunc);
$(this).data('click-count', click_count);
});
$(".get_category").on('click', clickFunc);
});
This way you store the click count on the data-click-count attribute of each .get_category

Problems returning href class from Jquery

I have downloaded and implemented some jquery code that makes a photo gallery on my website from an instagram hashtag. I have been trying to edit this code so that clicking on the images in the gallery show up in a lightbox rather than following a link back to instagram.
Here is the the source for the code: http://www.jqueryscript.net/social-media/jQuery-Plugin-To-Create-An-Endless-Instagram-Gallery-embedstagram.html
The Lightbox code I have been using is fancybox: http://www.jqueryscript.net/lightbox/Responsive-jQuery-Lightbox-With-Amazing-CSS3-Effects-Fancy-Box-2.html
On my site the necessary components are loaded for both Jqueries and the function is run like so:
<script>
$(document).ready(function(){
$(".ins_popup").fancybox({
openEffect : 'fade',
closeEffect : 'fade'
});
});
</script>
I have found the href in the original gallery jquery that links to instagram and edited it to include the class 'ins_popup' like so:
function renderPhotos(data) {
$.each(data.data, function (i, photo) {
photo = '<li class="photo"><img src="' + photo.images.standard_resolution.url.replace(/\\/, "") + '"></li>';
This does not seem to work however and the link now just opens an enlarged version of the picture rather than opening it in fancybox. I have tested each of the components (fancybox / hashtag gallery) separetly without problem, I just can't seem to get them to talk to one another.
And the associated code:
<!DOCTYPE html>
<html>
<head>
<title>Embedstagram jQuery Plugin Demo</title>
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" />
<!-- Include CSS Fies -->
<link href="https://www.googledrive.com/host/0B_9gRWttmryISVpkTGFhVV8yajQ" rel="stylesheet" type="text/css" >
<link href="http://www.jqueryscript.net/css/jquerysctipttop.css" rel="stylesheet" type="text/css">
<link href="http://cdnjs.cloudflare.com/ajax/libs/normalize/3.0.1/normalize.css" rel="stylesheet" type="text/css">
<link href="http://cdnjs.cloudflare.com/ajax/libs/fancybox/2.1.5/jquery.fancybox.min.css" rel="stylesheet" type="text/css">
<!-- Include jQuery -->
<script src="http://code.jquery.com/jquery-2.1.1.min.js"></script>
<!-- Include fancybox library -->
<script src="http://cdnjs.cloudflare.com/ajax/libs/fancybox/2.1.5/jquery.fancybox.min.js"></script>
<script>
$(document).ready(function(){
$(".ins_popup").fancybox({
openEffect : 'fade',
closeEffect : 'fade'
});
});
</script>
</head>
<body>
<div class="jquery-script-clear"></div>
<h1 style="margin:150px auto 30px auto;">Embedstagram jQuery Plugin Demo</h1>
<div id="embedstagram"></div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script src="https://www.googledrive.com/host/0B_9gRWttmryIbE0yNUJaeHNOQVk"></script>
<script type="text/javascript">
$(document).ready(function () {
$('#embedstagram').embedstagram({
client_id: '6f3244d01df94bb98785d04861561307',
hashtag: '#neverlutionsoundsystem' ,
thumb: 'tile'
});
});
</script>
</body>
</html>
and the Jquery for the gallery which I have edited:
/*global jQuery, window*/
(function ($) {
$.fn.embedstagram = function (options) {
var $this = this,
next_url = '';
var settings = $.extend({
client_id: '',
username: '',
hashtag: '#neverlutionsoundsystem',
count: 20,
responsive: true,
load_more: true,
thumb: 'default',
theme: 'default'
}, options);
settings.hashtag = settings.hashtag.replace('#', '');
$this
.addClass('embedstagram')
.addClass('thumb-' + settings.thumb)
.addClass('theme-' + settings.theme)
.append('<ul></ul>')
.append('Loading..');
var $photos = $this.find('ul'),
$button = $this.find('#function-button');
function resize() {
if (settings.responsive) {
var e = $this.width();
var $photo = $('.photo');
if (1024 >= e && e > 768) {
$photo.css({'width': '25%', 'padding-bottom': '25%'});
} else if (768 >= e && e > 570) {
$photo.css({'width': '33.3%', 'padding-bottom': '33.3%'});
} else if (570 >= e && e > 400) {
$photo.css({'width': '50%', 'padding-bottom': '50%'});
} else if (400 > e) {
$photo.css({'width': '100%', 'padding-bottom': '100%'});
} else {
$photo.css({'width': '20%', 'padding-bottom': '20%'});
}
}
}
function renderPhotos(data) {
$.each(data.data, function (i, photo) {
photo = '<li class="photo"><img src="' + photo.images.standard_resolution.url.replace(/\\/, "") + '"></li>';
$photos.append(photo);
return i <= (settings.count);
});
}
function getUrl(user_id) {
var modifier;
if (user_id) {
modifier = 'users/' + user_id;
} else if (settings.hashtag) {
modifier = 'tags/' + settings.hashtag;
}
if (next_url) {
return next_url;
}
return 'https://api.instagram.com/v1/' + modifier + '/media/recent/?&client_id=' + settings.client_id + '&count=' + settings.count;
}
function getPhotos(user_id) {
$button.text('Loading..');
$.ajax({
type: "GET",
dataType: 'jsonp',
url: getUrl(user_id),
success: function (data) {
if (data.meta.error_message) {
var error_message = 'Error: ' + data.meta.error_message.toLowerCase();
$button.text(error_message).addClass('error');
return false;
}
if (!settings.load_more) {
$this.addClass('hide-load-more');
}
$button.text('Load More');
renderPhotos(data);
next_url = data.pagination.next_url;
if (!next_url) {
$button.text('No more images').addClass('disabled');
}
resize();
},
error: function () {
$button.text('Error: unknown').addClass('error');
}
});
}
if (settings.username) {
$.ajax({
type: "GET",
dataType: 'jsonp',
url: 'https://api.instagram.com/v1/users/search?q=' + settings.username + '&client_id=' + settings.client_id,
success: function (data) {
if (data.meta.error_message) {
var error_message = 'Error: ' + data.meta.error_message.toLowerCase();
$button.text(error_message).addClass('error');
return false;
}
if (data.data.length) {
var num_items = data.data.length - 1;
$.each(data.data, function (i, user) {
if (settings.username === user.username) {
var user_id = user.id;
getPhotos(user_id);
return false;
}
if (i === num_items) {
$button.text('Error: no users found').addClass('error');
}
});
} else {
$button.text('Error: no users found').addClass('error');
}
},
error: function () {
$button.text('Error: unknown').addClass('error');
}
});
} else if (settings.hashtag) {
getPhotos();
} else {
$button.text('Error: missing username or hashtag').addClass('error');
}
$button.click(function (e) {
e.preventDefault();
if (!$(this).is('.disabled, .error')) {
getPhotos();
}
});
$(window).on('load resize', resize);
};
}(jQuery));
If you need to see any of the other code please ask! Any help is much appreciated as you may have well guessed - I'm new to all of this
Thanks!
when you are calling the fancybox, images may not have been loaded to the DOM. call the fancybox plugin after the image load, not on the $(document).ready();
function renderPhotos(data) {
$.each(data.data, function (i, photo) {
photo = '<li class="photo"><img src="' + photo.images.standard_resolution.url.replace(/\\/, "") + '"></li>';
$photos.append(photo);
return i <= (settings.count);
});
$(".ins_popup").fancybox({
openEffect : 'fade',
closeEffect : 'fade'
});
}
Also I see in your sample website that you have included jquery twice in the page
<!-- Include jQuery -->
<script src="http://code.jquery.com/jquery-2.1.1.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
Remove the 2nd Jquery include. this might be the issue.

Trigger function and open URL at the same time

I am creating a counter which counts the number of clicks made to an anchor tag. I also need the URL to be opened at the same time. I tried the below code. The page is redirected before the function executes.
Is there a better way to do this?
Code:
$(document).ready(function () {
var $res = $('#counter').text($.cookie('link-count') || 0)
$('a').click(function () {
var count = parseInt($.cookie('link-count'), 10) || 0;
count++;
if (count > 10) {
$(this).attr("href", "https://www.yahoo.com");
}
$.cookie('link-count', count);
$res.text(count);
location.href = $(this).attr("href");
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Google
<div id="counter">0</div>
var linkCount;
$(document).ready(function () {
var $res = $('#counter').text(linkCount || 0)
$('a').click(function (e) {
e.preventDefault();
var count = parseInt(linkCount) || 0;
count++;
if (count > 10) {
$(this).attr("href", "https://www.yahoo.com");
}
linkCount = count;
$res.text(count);
location.href = $(this).attr("href")
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Google
<div id="counter">0</div>

jQuery - Click function doesn't fire

I'm having problems with firing of a function whenever my ID is clicked. Currently, this is how my code looks:
$(document).ready(function () {
if (self != top) {
top.location.replace(location.href);
}
$(document).mousedown(function (e) {
if (e.button == 2) {
console.log('mousdown');
$(window).blur();
}
});
$(document).mouseup(function (e) {
if (e.button == 2) {
console.log('mousup');
$(window).blur();
}
});
var $iframe_height = $(window).innerHeight() - 90;
$('iframe').attr('height', $iframe_height + 'px');
$(window).resize(function () {
var $iframe_height = $(window).innerHeight() - 90;
$('iframe').attr('height', $iframe_height + 'px');
});
$('.message').html('<div class="alert alert-warning">Waiting for advertisement to load...</div>');
$('.close').on('click', function () {
window.open('', '_self', '');
window.close();
});
var $seconds = 5;
var $window_width = $(window).innerWidth();
var $width_per_second = $window_width / $seconds;
var $timer = null,
$current_second = 0;
setTimeout(function () {
if ((!$('body').hasClass('done')) && (!$('body').hasClass('blocked')) && (!$('body').hasClass('ready'))) {
$('body').addClass('ready');
$('.message').html('<div class="alert alert-info">Click <b id="start" style="cursor:pointer;text-decoration:underline;">here</b> to start viewing this advertisement.</div>');
}
}, 3000);
document.getElementById("website").onload = function () {
if ((!$('body').hasClass('done')) && (!$('body').hasClass('blocked')) && (!$('body').hasClass('ready'))) {
$('body').addClass('ready');
$('.message').html('<div class="alert alert-info">Click <b id="start" style="cursor:pointer;text-decoration:underline;">here</b> to start viewing this advertisement.</div>');
}
};
$("#start").click(function () {
$('#website').focus();
$('.message').html('<div class="alert alert-info"><b id="seconds">' + parseFloat($seconds - $current_second) + '</b> seconds remaining (do not leave this page).</div>');
if ($timer !== null) return;
$timer = setInterval(function () {
if ($current_second == $seconds) {
clearInterval($timer);
$('.message').html('<div class="alert alert-success">Checking if you won, please wait…</div>');
var $id = 10977;
var $reffbux_fp = new Fingerprint();
var $reffbux_fp = $reffbux_fp.get();
$.ajax({
url: 'http://reffbux.com/account/register_roulette',
type: 'post',
data: {
id: $id,
fp: $reffbux_fp
},
success: function (result, status) {
$('html, body').animate({
scrollTop: 0
}, 500);
$('body').addClass('done');
$('.melding').fadeOut(0).fadeIn(500);
$('.message').html(result);
$('.counter_bar').addClass('done');
}
});
return false;
} else {
var $counter_bar_width = $('.counter_bar').innerWidth();
$('.counter_bar').css('width', parseFloat($counter_bar_width + $width_per_second).toFixed(2));
$current_second++;
$("#seconds").text(parseFloat($seconds - $current_second));
}
}, 1000);
});
$('body').mouseleave(function () {
if ((!$(this).hasClass('done')) && (!$(this).hasClass('blocked')) && ($(this).hasClass('ready'))) {
$('.message').html('<div class="alert alert-error">You navigated away from the advertisement. Click <b id="start" style="cursor:pointer;text-decoration:underline;">here</b> to resume.</div>');
clearInterval($timer);
$timer = null
}
});
});
A text with id="start" will be generated when the iframes content is loaded. The problem is, whenever I click on the id="start" nothing happens. Nothing. The console log doesn't report any error before I click nor does it report any error after I've clicked.
I can't seem to find what the problem is.
You have to use the jquery on to bind events to dynamically created elements.
$('.message').on('click', '#start', function(){
Where .message is the elelment your #start element is in.

Categories