How to count how many clicks have made on the link tag:
this is my code:
#foreach($news as $key => $value)
<li>
<a href="" id="news_link" class="news_link">
<h3 class="title">{{$value->title}}</h3>
</a>
</li>
#endforeach
can anyone suggest what is the correct way to do this.?
$(document).ready(function() {
var count = 0;
$('.news_link').click(function() {
count++;
});
alert(count);
});
counter is not getting incremented on alert
The best way to track this for analytics is to use Google Tag Manager to keep track of internal and external links.
If it is just for a function you could make use of Javascript and store it in a cookie, or if you want to store it like forever; in a database.
if(document.cookie.indexOf("clicks=") >= 0) {
var clicks = getCookie('clicks');
} else {
var clicks = 0;
}
$('#news_link').click(function() {
clicks++;
document.cookie = "clicks="+clicks;
});
function getCookie(cname) {
var name = cname + "=";
var ca = document.cookie.split(';');
for(var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') {
c = c.substring(1);
}
if (c.indexOf(name) == 0) {
return c.substring(name.length, c.length);
}
}
return "";
}
Or use Ajax to store it in lets say your database:
$(function () {
$('#news_link').on('click', function () {
clicks++;
$.ajax({
url: 'Ajax/StatusUpdate.php',
data: {
count: clicks,
},
dataType : 'json'
});
});
});
Related
sorry for my english but i will try my best to ask my question correctly.
As layout i'm using this = https://codepen.io/Sool/pen/vvodgj with minor changes to support url hash.
Isotope JS Code:
$(document).ready(function($) {
var $grid = $('.grid').isotope({
// options
itemSelector: '.grid-item',
layoutMode: 'fitRows',
});
var filterFns = {
// show if number is greater than 50
numberGreaterThan50: function() {
var number = $(this).find('.number').text();
return parseInt(number, 10) > 50;
},
// show if name ends with -ium
ium: function() {
var name = $(this).find('.name').text();
return name.match(/ium$/);
}
};
function getHashFilter() {
// get filter=filterName
var matches = location.hash.match(/filter=([^&]+)/i);
var hashFilter = matches && matches[1];
return hashFilter && decodeURIComponent(hashFilter);
}
// change is-checked class on buttons
var $buttonGroup = $('.filters');
$buttonGroup.on('click', 'li', function(event) {
$buttonGroup.find('.is-checked').removeClass('is-checked');
var $button = $(event.currentTarget);
$button.addClass('is-checked');
var filterValue = $button.attr('data-filter');
// set filter in hash
location.hash = 'filter=' + encodeURIComponent(filterValue);
$grid.isotope({ filter: filterValue });
});
var isIsotopeInit = false;
function onHashchange() {
var hashFilter = getHashFilter();
if (!hashFilter && isIsotopeInit) {
return;
}
isIsotopeInit = true;
// filter isotope
$grid.isotope({
itemSelector: '.element-item',
layoutMode: 'fitRows',
// use filterFns
filter: filterFns[hashFilter] || hashFilter
});
// set selected class on button
if (hashFilter) {
$buttonGroup.find('.is-checked').removeClass('is-checked');
$buttonGroup.find('[data-filter="' + hashFilter + '"]').addClass('is-checked');
}
}
$(window).on('hashchange', onHashchange);
// trigger event handler to init Isotope
onHashchange();
})
AJAX Code:
$(document).ready(function() {
var limit = 7;
var start = 4;
var action = 'inactive';
function load_country_data(limit, start) {
$.ajax({
url: "fetch.php",
method: "POST",
data: { limit: limit, start: start },
cache: false,
success: function(data) {
$('#load_data').append(data);
if (data == '') {
$('#load_data_message').html("<button type='button'>All images loaded</button>");
action = 'active';
} else {
$('#load_data_message').html("<button type='button'>Loading images.....</button>");
action = "inactive";
}
}
});
}
if (action == 'inactive') {
action = 'active';
load_country_data(limit, start);
}
$(window).scroll(function() {
if ($(window).scrollTop() + $(document).height() > $("#load_data").height() && action == 'inactive') {
action = 'active';
start = start + limit;
setTimeout(function() {
load_country_data(limit, start);
}, 1000);
}
});
});
PHP Code to fetch data:
<?php
if(isset($_POST["limit"], $_POST["start"]))
{
include "mysqli_connection.php";
$query = "SELECT * FROM gallery ORDER BY order ASC LIMIT ".$_POST["start"].", ".$_POST["limit"]."";
$result = mysqli_query($conn, $query);
while ($row = mysqli_fetch_array($result)) {
?>
<div class="col-md-3 grid-item <?= htmlspecialchars($row["category"]) ?>" data-category="<?= htmlspecialchars($row["category"]) ?>">
<img data-src="/assets/images/gallery/<?= htmlspecialchars($row["image"]) ?>" data-srcset="/assets/images/gallery/<?= htmlspecialchars($row["image"]) ?>" class="img-fluid" alt="<?= htmlspecialchars($row["title"]) ?> Image" srcset="/assets/images/gallery/<?= htmlspecialchars($row["image"]) ?>" src="<?= htmlspecialchars($row["image"]) ?>">
</div>
<?php
}
mysqli_close($conn);
}
?>
The data is loaded from the database and everything seems to be fine. But at the same time, filtering stops working. How to make filtering work with ajax?
How to make sure that when you click on a certain category, data from a certain category is loaded? With ajax and working url hash, something like that domain.com/#filter=category1 or domain.com/#filter=category3.
I would be very grateful for any advice or help on this issue, thank you.
I am creating the search functionality in my laravel 5 ecommerce web application.
I want the user to move the cursor with the arrow keys on the search results, but I am failing to achieve this.
Here's the controller:
public function searchProduct(Request $request)
{
$productName = $request->input('name');
if($productName !== '')
{
$products = Product::where('name', 'LIKE', '%' . $productName . '%')->where('display', 'Enabled')->get();
return view('partials.search', compact('products'));
}
return false;
}
The search results:
#foreach($products as $product)
<li>
<a href="{{ url('/store/'.$product->code .'/'.Safeurl::make($product->name)) }}" class="link_scheme_color_main">
{{ $product->name }}
</a>
</li>
#endforeach
And the AJAX:
$('.searchProduct').keydown(function(e) {
var name = $(this).val();
var inputData = $('.formSearchProduct').serialize();
var prodList = $('.showProds');
var countList = prodList.find('ul li').length;
var prd = prodList.find('ul li');
if(name.length === 0) {
prodList.hide();
} else {
$.ajax({
url: '{{ url('/store/product/search') }}',
type: "POST",
data: inputData
})
.done(function(m) {
if (m) {
prodList.show();
prodList.find('ul.searchedProducts').html(m);
prodList.find('ul li').first().addClass('activeProduct');
} else {
prodList.hide();
}
});
}
});
The css:
.activeProduct {background: #ccc !important;}
I have made this application live. You can check it here. The application is still in the development stage and not in production.
What I want to achieve is:
When the user searches for the product, he/she can use the up and down arrow keys to navigate the search results, and on click of any of the results, he/she should go to the product page.
When the user searches and removes the search keyword(s), all the products are shown, I don't want that.
UPDATE 1:
I have added this code and it seems there is a bug, where I don't know. The bug is that I can only move to the second list item when pressing the down arrow key and at the very next second, it moves back to the first list item.
$('.searchProduct').keydown(function(e) {
var prodList = $('.showProds');
var countList = prodList.find('ul li').length;
var prd = prodList.find('ul li');
var active = prodList.find('ul li.activeProduct');
console.log(e.keyCode);
if (e.which === 40) {
var next = active.removeClass('activeProduct').next('li');
next = next.length > 0 ? next : $('li:eq(0)');
next.addClass('activeProduct');
}
});
UPDATE 2:
I have got it working to a certain extent. I have removed the code of update 1 and added the below code to done() method.
if (m) {
prodList.show();
prodList.find('ul.searchedProducts').html(m);
prodList.find('ul li').first().addClass('activeProduct');
if(e.keyCode == 40) {
prodList.find('ul li').prev().removeClass('activeProduct');
prodList.find('ul li').next().first().addClass('activeProduct').focus();
}
} else {
prodList.hide();
}
But this moves only to the second list item on every time the down arrow key is pressed. You can have a look at the link that I provided above.
Kindly help me out with this. Thanks.
I have a PHP process which updates files, and writes a status report with each file.
While that is happening, I was hoping to update the user's browser until the final response.
Unless there is a better way, I simply wanted some advice on how to loop infinitely refreshing getJSON() results until the ajax response comes.
What is the best way to do this?
This ended up being the solution I used:
$(document).on('click', "#ss_batch_edit_processing", function (e) {
var ids = get_selected();
var status_location = '<?php echo symbiostock_TMPDIR . '/report.txt' ?>';
if(ids == 0){
return;
}
$('.' + loading_icon_small).show();
var data = {
action: 'ss_professional_ajax',
security: '<?php echo $ajax_nonce; ?>',
reprocessing_action: $('input:radio[name=ss_reprocessing_action]:checked').val(),
ids: ids,
};
var completed = 0;
$.post(ajaxurl, data, function (response) {
$('.' + loading_icon_small).hide();
completed = 1;
});
var get_update = function(){
$.getJSON(status_location, function (data) {
var update = '<ul><li><strong>'+data['title']+'</strong></li><li><strong>Count:</strong> '+data['count']+' / '+data['total']+'</li><li><strong>Last processed</strong>: Image # '+data['last_id']+'</li></ul>';
$('#ss-reprocessing-results').html(update).delay(1000);
});
if(completed == 1){
clearInterval(timed_requests)
return false;
}
};
var interval = 1000; // every 1 second
var timed_requests = setInterval(get_update, interval);
});
I have a little problem and hoping someone with JQuery knowledge can look at my code and spot what I'm doing wrong.
I have two unordered lists (dynamically created) that get updated with ajax.
With script below I can only get one list to update but not both. I cloned first script and changed variables for second list but only one gets updated.
Thanks for you help.
Here is the html code:
List one: <ul data-options="" class="elgg-list-mainriver elgg-sync elgg-list-river elgg-river"><li> .....</li>
</ul>
List Two: <ul data-options="" class="elgg-list-miniriver elgg-sync elgg-list-river elgg-river"><li> .....</li>
</ul>
And JQuery code:
elgg.provide('elgg.river');
elgg.river.init = function() {
var riverList = $('ul.elgg-list-mainriver');
//var miniriverList = $('.elgg-list-miniriver');
var time = 20000;
if (!window.rivertimer) {
window.rivertimer = true;
var refresh_river = window.setTimeout(function(){
elgg.river.timedRefresh(riverList);
//elgg.river.MinitimedRefresh(miniriverList);
}, time);
}
};
elgg.river.timedRefresh = function(object) {
var first = $('li:first', object);
if (!first.length) {
first = object;
}
var time = first.data('timestamp');
elgg.getJSON('activity', {
data : {
sync : 'new',
time : time,
options : object.data('options')
},
success : function(output) {
if (output) {
$.each(output, function(key, val) {
var new_item = $(val).hide();
//new_item = $(val).show();
object.prepend(new_item.fadeIn(600));
//object.prepend(new_item.$(val).show());
});
}
window.rivertimer = false;
elgg.trigger_hook('success', 'elgg:river:ajax');
}
});
}
elgg.provide('elgg.river_miniriver');
elgg.river_miniriver.init = function() {
var miniriverList = $('ul.elgg-list-miniriver');
var time = 20000;
if (!window.rivertimer) {
window.rivertimer = true;
var refresh_river = window.setTimeout(function(){
elgg.river_miniriver.timedRefresh(miniriverList);
}, time);
}
};
elgg.river_miniriver.timedRefresh = function(object) {
var first = $('li:first', object);
if (!first.length) {
first = object;
}
var time = first.data('timestamp');
elgg.getJSON('activity', {
data : {
sync : 'new',
time : time,
options : object.data('options')
},
success : function(output) {
if (output) {
$.each(output, function(key, val) {
var new_item = $(val).hide();
//new_item = $(val).show();
object.prepend(new_item.fadeIn(600));
//object.prepend(new_item.$(val).show());
});
}
window.rivertimer = false;
elgg.trigger_hook('success', 'elgg:river:ajax');
}
});
}
elgg.register_hook_handler('init', 'system', elgg.river.init);
elgg.register_hook_handler('success', 'elgg:river:ajax', elgg.river.init, 500);
elgg.register_hook_handler('init', 'system', elgg.river_miniriver.init);
elgg.register_hook_handler('success', 'elgg:river:ajax', elgg.river_miniriver.init, 500);
If I try to combine both lists class in the function "$('ul.elgg-list-miniriver, ul.elgg-list-mainriver')" than both lists get updated but first list item (li) gets "opacity:0;" in style????
This code:
elgg.river_miniriver.init = function() {
var miniriverList = $('ul.elgg-list-miniriver, ul.elgg-list-mainriver');
var time = 20000;
if (!window.rivertimer) {
window.rivertimer = true;
var refresh_river = window.setTimeout(function(){
elgg.river_miniriver.timedRefresh(miniriverList);
}, time);
}
};
elgg.river_miniriver.timedRefresh = function(object) {
var first = $('li:first', object);
if (!first.length) {
first = object;
}
var time = first.data('timestamp');
elgg.getJSON('activity', {
data : {
sync : 'new',
time : time,
options : object.data('options')
},
success : function(output) {
if (output) {
$.each(output, function(key, val) {
var new_item = $(val).hide();
//new_item = $(val).show();
object.prepend(new_item.fadeIn(1000));
//object.prepend(new_item.$(val).show());
});
}
window.rivertimer = false;
elgg.trigger_hook('success', 'elgg:river:ajax');
}
});
}
I am having trouble sending data to the database. The values are being sent, but they are all going into the first drop zone field. And I need each dropzone value to go into the correct field in the database.
I've tried putting in different listeners & if statements in the javascript but it won't work for me.
the html:
<ul id="images">
<li><a id="img1" draggable="true"><img src="images/1.jpg"></a></li>
<li><a id="img2" draggable="true"><img src="images/2.jpg"></a></li>
<li><a id="img3" draggable="true"><img src="images/3.jpg"></a></li>
</ul>
//dropzones
<div class="drop_zones">
<div class="drop_zone" id="drop_zone1" droppable="true">
</div>
<div class="drop_zone" id="drop_zone2" droppable="true">
</div>
<div class="drop_zone" id="drop_zone3" droppable="true">
</div>
</div>
<button id = "post" onClick="postdb();">Post info</button>
the javascript:
var addEvent = (function () {
if (document.addEventListener) {
return function (el, type, fn) {
if (el && el.nodeName || el === window) {
el.addEventListener(type, fn, false);
} else if (el && el.length) {
for (var i = 0; i < el.length; i++) {
addEvent(el[i], type, fn);
}
}
};
} else {
return function (el, type, fn) {
if (el && el.nodeName || el === window) {
el.attachEvent('on' + type, function () {
return fn.call(el, window.event);
});
} else if (el && el.length) {
for (var i = 0; i < el.length; i++) {
addEvent(el[i], type, fn);
}
}
};
}
})();
var dragItems;
updateDataTransfer();
var dropAreas = document.querySelectorAll('[droppable=true]');
function cancel(e) {
if (e.preventDefault) {
e.preventDefault();
}
return false;
}
function updateDataTransfer() {
dragItems = document.querySelectorAll('[draggable=true]');
for (var i = 0; i < dragItems.length; i++) {
addEvent(dragItems[i], 'dragstart', function (event) {
event.dataTransfer.setData('obj_id', this.id);
return false;
});
}
}
addEvent(dropAreas, 'dragover', function (event) {
if (event.preventDefault)
event.preventDefault();
this.style.borderColor = "#000";
return false;
});
addEvent(dropAreas, 'dragleave', function (event) {
if (event.preventDefault)
event.preventDefault();
this.style.borderColor = "#ccc";
return false;
});
addEvent(dropAreas, 'dragenter', cancel);
// drop event handler
addEvent(dropAreas, 'drop', function (event) {
if (event.preventDefault)
event.preventDefault();
// get dropped object
var iObj = event.dataTransfer.getData('obj_id');
var oldObj = document.getElementById(iObj);
// get its image src
var oldSrc = oldObj.childNodes[0].src;
oldObj.className += 'hidden';
var oldThis = this;
setTimeout(function () {
oldObj.parentNode.removeChild(oldObj); // remove object from DOM
// add similar object in another place
oldThis.innerHTML += '<a id="' + iObj + '" draggable="true"><img src="' + oldSrc + '" /> </a>';
// and update event handlers
updateDataTransfer();
function postdb(){
if (document.querySelectorAll('[droppable=true]')){
var dropDetails = oldThis.id + '=' + iObj;
$.post("a-2.php", dropDetails);
}
oldThis.style.borderColor = "#ccc";
}, 500);
return false;
});
and my php:
$sql="INSERT INTO table_answers (drop_zone1, drop_zone2, drop_zone3) VALUES ('$_POST[drop_zone1]','$_POST[drop_zone2]','$_POST[drop_zone3]')";
Any idea please?
var u = $('drop_zone1');
if(u){
$.post("post.php", y);
};
(I'm assuming this is jQuery.)
Add the # to the beginning of the selector: $('#drop_zone1');.
The jQuery resultset always evaluates to a truthy value. It's not clear to me what condition you're trying to validate here...
In the PHP code, you're creating the query in $sql2 in the first if, as opposed to $sql in the other two.
Edit - now that we know what you're trying to do in setTimeout, this simplified function should work:
setTimeout(function() {
oldObj.parentNode.removeChild(oldObj); // remove object from DOM
// add similar object in another place
oldThis.innerHTML += '<a id="' + iObj + '" draggable="true"><img src="' + oldSrc + '" /> </a>';
// and update event handlers
updateDataTransfer();
/*
this part has been removed, see edit below
var dropDetails = oldThis.id + '=' + iObj;
// now dropDetails should look something like "drop_zone1=img1"
$.post("post.php", dropDetails);
*/
oldThis.style.borderColor = "#ccc";
}, 500);
One more edit, to submit all the dropped elements at once:
function postdb() {
var postDetails = {};
var dropZones = document.querySelectorAll('[droppable=true]');
var allZonesDropped = true;
for(var ix = 0; ix < dropZones.length; ++ix) {
var zone = dropZones[ix];
var dropped = zone.querySelector('[draggable=true]');
if(dropped) {
var dropTag = dropped.id;
postDetails[zone.id] = dropTag;
} else {
allZonesDropped = false;
}
}
if(allZonesDropped) {
$.post("a-2.php", dropDetails);
} else {
alert('Not all targets have elements in them');
}
return false;
});
Just be careful where you place this function - your edited question has it in the middle of the setTimeout call, where it's definitely not going to work.
Regarding your PHP code: You should really learn about PDO or MySQLi and use prepared statements instead of blindly inserting user input into the query. If you care to learn, here is a quite good PDO-related tutorial.