Ajax tooltip doesn't disappear if mouse moves too fast - php

I have a tooltip loaded with ajax for each item on my webpage. When you move the mouse too fast, it doesn't take the mouseleave event into account. Then, I tried to load the tooltip content with the page. However, there are a lot of contents so it takes four more seconds to load :/
What can I do?
Here is my jquery code :
$('.main').on({
mouseenter: function(){
var id = $(this).parent().data('candy');
if(id != 0){
$.ajax({
url: 'tooltip.php',
type: 'get',
data: { 'type': 'candy', 'item_id': id },
global : false,
success: function(data){
$('.candyTooltip').html(data);
$('.candyTooltip .layer_item').show();
}
});
}
},
mouseleave : function(){
$('.candyTooltip .layer_item').hide();
}
}, '.candy');
Also, I don't know if it's relevant but the SQL query takes 1,2ms and the PHP script takes 3,94ms.

I finally found a way to do it !!!
All I had to do was put the ajax request inside a variable and abort it on mouseleave.
So, now it looks like this :
$('.main').on({
mouseenter: function(){
var id = $(this).parent().data('candy');
if(id != 0){
query = $.ajax({
url: 'tooltip.php',
type: 'get',
data: { 'type': 'candy', 'item_id': id },
global : false,
success: function(data){
$('.candyTooltip').html(data);
$('.candyTooltip .layer_item').show();
}
});
}
},
mouseleave : function(){
if (query) { query.abort(); }
$('.candyTooltip .layer_item').hide();
}
}, '.candy');

Related

Change HTML element into text from database using AJAX / JQuery according to ID

I'm new to Jquery and ran into a problem in web development. I want to convert html element to paragraph from database based on id from url.
Here my code for now,
<script>
var url = window.location.pathname;
var id = url.substring(url.lastIndexOf('/') + 1);
$(document).ready(function() {
$("#desc").click(function() {
$("#content").html(id);
$(this).addClass('active');
$("#feature").removeClass('active');
$("#spec").removeClass('active');
});
$("#feature").click(function() {
$("#content").html(id);
$(this).addClass('active');
$("#desc").removeClass('active');
$("#spec").removeClass('active');
});
$("#spec").click(function() {
$("#content").html(id);
$(this).addClass('active');
$("#desc").removeClass('active');
$("#feature").removeClass('active');
});
});
</script>
Here is the display that i wish
I've got the id, but don't know how to display data from the database (tbl_product) based on that id using AJAX / Jquery. I can only change the active class for now, all your advice and suggestions are will be very usefull.
you can use ajax like this
$("#desc").click(function() {
$(this).addClass('active');
$("#feature").removeClass('active');
$("#spec").removeClass('active');
$.ajax({
url: 'product.php?id=' + id
dataType: 'html',
contentType: false,
processData: false,
beforeSend: function() {
$('#content').empty();
},
error: function() {
$('#content').append('error');
},
success: function(data) {
$('#content').append(data);
}
})
});

function loads only on change, i would it to load on document load

My knowledge of this is very limited, but I figured that the problem that I have is in this function. What it does is that it displays some options to be selected in an item post. From what I see it only loads when a category is changed. Because of that when you edit this post, this function will not display unless you change category to another one and then revert back to the one you want. I would like it to display every time, except for those categories that are in the if statement.
Please assist....
$(document).on('change', "#catId", function () {
var optgroups = $(this).children("optgroup[label='Nekretnine'], optgroup[label='Posao'], optgroup[label='Usluge'], optgroup[label='Poljoprivredni oglasi'], optgroup[label='Kućni ljubimci'], optgroup[label='Turizam']");
$(optgroups).each(function(){
if($(optgroups).children("option:selected").length){
$("#condition-container").html('');
} else {
$.ajax({
url: ajaxURL,
type: "get",
data: "request=condition-fields",
dataType: "html",
success: function(data) {
if(data) {
$("#condition-container").html(data);
}
}
});
}
});
});
You just need to trigger your change event on document load. So under you on change function put this code
$(document).on('change', "#catId", function () {
var optgroups = $(this).children("optgroup[label='Nekretnine'], optgroup[label='Posao'], optgroup[label='Usluge'], optgroup[label='Poljoprivredni oglasi'], optgroup[label='Kućni ljubimci'], optgroup[label='Turizam']");
$(optgroups).each(function () {
if ($(optgroups).children("option:selected").length) {
$("#condition-container").html('');
} else {
$.ajax({
url: ajaxURL,
type: "get",
data: "request=condition-fields",
dataType: "html",
success: function (data) {
if (data) {
$("#condition-container").html(data);
}
}
});
}
});
});
//Trigger change
$(document).ready(function () {
$("#catId").trigger("change");
});
hi I assume you want the function fired on document load and on change, but for that you will need to use 2 triggers.
1) you allready have the on change trigger
2) use the $(document).ready() (https://learn.jquery.com/using-jquery-core/document-ready/) wrapper for onload.
There is possibly a much more gracefull solution, but I'm no JS expert so this will only get you to a working, although not the pretiest state

jQuery AJAX loads twice

I'm programming a site, and I've got a problem.
I have the following jQuery code:
$('input[type="text"][name="appLink"]').keyup(function() {
var iTunesURL = $(this).val();
var iTunesAppID = $('input[name="iTunesAppID"]').val();
$.ajax({
type: 'POST',
url: jsonURL,
dataType: 'json',
cache: false,
timeout: 20000,
data: { a: 'checkiTunesURL', iTunesURL: iTunesURL, iTunesAppID: iTunesAppID },
success: function(data) {
if (!data.error) {
$('section.submit').fadeOut('slow');
//Modifying Submit Page
setTimeout(function() {
$('input[name="appLink"]').val(data.trackViewUrl);
$('div.appimage > img').attr('src', data.artworkUrl512).attr('alt', data.trackName);
$('div.title > p:nth-child(1)').html(data.trackName);
$('div.title > p:nth-child(2)').html('by '+data.sellerName);
$('span.mod-category').html(data.primaryGenreName);
$('span.mod-size').html(data.fileSizeBytes);
$('span.mod-update').html(data.lastUpdate);
$('select[name="version"]').html(data.verSelect);
$('input[name="iTunesAppID"]').attr('value', data.trackId);
}, 600);
//Showing Submit Page
$('section.submit').delay('600').fadeIn('slow');
} else {
$('.json-response').html(data.message).fadeIn('slow');
}
},
error: function(jqXHR, textStatus, errorThrown) {
//$('.json-response').html('Probléma történt! Kérlek próbáld újra később! (HTTP Error: '+errorThrown+' | Error Message: '+textStatus+')').fadeIn('slow');
$('.json-response').html('Something went wrong! Please check your network connection!').fadeIn('slow');
}
});
});
Sometimes (randomly) the content fades out-in twice.
Could you let me know what's wrong?
Thanks in advance.
I guess the page is dynamically generated from javascript,
If you execute the following function twice, then there be two events since it executes twice,
so a better way is to unbind all previus 'keyup' event and bind it again.
Try this,
$('input[type="text"][name="appLink"]').unbind('keyup').keyup(function() {
});

jscrollPane disappear when continuously Ajax GET

PROBLEM SOLVED
updated the jscrollpane to the latest version which support jquery 1.8 !
https://github.com/vitch/jScrollPane/blob/master/script/jquery.jscrollpane.min.js
I'm trying to refresh a div with content for a certain period. It will fire an Ajax GET call to a php script which render the content. For the first time ajax GET called, the ScrollPane is there, but for the second time Ajax GET(refresh) JScrollPane disappeared. Any how to reinitialize the jscrollpane?
function getActivity(callback)
{
$.ajax({
url: '../../views/main/activity.php',
type: 'GET',
complete: function(){
$('#activityLineHolder').jScrollPane({
verticalDragMinHeight: 12,
verticalDragMaxHeight: 12
//autoReinitialize = true
});
},
success: function(data) {
var api = $('#activityLineHolder').jScrollPane(
{
verticalDragMinHeight: 12,
verticalDragMaxHeight: 12
}
).data('jsp');
api.getContentPane().html(data);
api.reinitialise();
}
});
setTimeout(callback,10000);
}
$(document).ready(function(){
(function getActivitysTimeoutFunction(){
getActivity(getActivitysTimeoutFunction);
})();
});
Right now, my scrollpane is there after every Ajax call, but it shows buggy, the jscrollpane will keep moving left after every Ajax Call and slowly, it will hide the content. How is this happened?
foreach ($list as $notification) {
echo "<div class='feeds' id='$notification->notification_id'>";
$userObj = $user->show($notification->added_by);
echo $userObj->first_name.":<span class='text'>".$notification->activity."</span>";
echo " <span class='time'>".$notification_obj->nicetime($notification->created_at)."</span>";
echo "</div>";
}
something like this , that is my activity.php
here is my screenshot , anyone pls do help me #_#
http://img31.imageshack.us/img31/6871/jscrollpane.png
change the order of your commands. make a global variable that caches the ID like this:
var $activity, $activity_pane; // outside the dom ready
function getActivity(callback){
$.ajax({
url: '../../views/main/activity.php',
type: 'GET',
success: function(data) {
$activity_pane.html(data);
}
});
setTimeout(callback,10000);
}
$(function(){
$activity = $('#activityLineHolder');
$activity.jScrollPane({
verticalDragMinHeight: 12,
verticalDragMaxHeight: 12
autoReinitialise: true
});
$activity_pane = $activity.data('jsp').getContentPane();
(function getActivitysTimeoutFunction(){
getActivity(getActivitysTimeoutFunction);
})();
});
My understanding is that a callback should be executed when the code within your method completes. If you are then wanting to run the getActivity() method again, shouldn't that be used in setTimeout(). Something like this:
function getActivity(callback)
{
$.ajax({
url: '../../views/main/activity.php',
type: 'GET',
complete: function(){
$('#activityLineHolder').jScrollPane({
verticalDragMinHeight: 12,
verticalDragMaxHeight: 12
//autoReinitialize = true
});
},
success: function(data) {
$('#activityLineHolder').html(data);
}
});
setTimeout(function(){getActivity(callback);},10000);
if($.isFunction(callback)) {
callback();
}
}
I just take a look at http://jscrollpane.kelvinluck.com/ajax.html
I had tried and works. i change setTimeout into setInterval (function from scrollpane).
you can try this (i had tested)
$(document).ready(function(){
var api = $('#activityLineHolder').jScrollPane(
{
showArrows:true,
maintainPosition: false,
verticalDragMinHeight: 12,
verticalDragMaxHeight: 12,
autoReinitialise: true
}
).data('jsp');
setInterval(
function()
{
$.ajax({
url: '../../views/main/activity.php',
success: function(data) {
api.getContentPane().html(data);
}
});
},
10000
);
});
I've faced this problem before, here is a snippet so you can get the idea. Good luck!
attachScroll = function(){
return $('.scroll-pane').jScrollPane({
verticalDragMinHeight: 17,
verticalDragMaxHeight: 17,
showArrows: true,
maintainPosition: false
});
}; // in this var I store all settings related to jScrollPane
var api = attachScroll().data('jsp');
$ajaxObj = $.ajax({
type: "GET", //set get or post
url: YOUR_URL,
data: null,
cache: false, //make sure you get fresh data
async: false, //very important!
beforeSend: function(){
},
success: function(){
},
complete: function(){
}
}).responseText; //$ajaxObj get the data from Ajax and store it
api.getContentPane().html($ajaxObj); //insert $ajaxObj data into "api" pane previously defined.
api.reinitialise(); //redraw jScrollPane
You can define the ajax call as a function and put it into a setInterval.
An example from official docs can be found here
Hope it helps!
Well I suppose that your HTML content coming from AJAX is long and you have problem with decreasing area size because it takes some time to render content by .html():
api.getContentPane().html(data);
And when it goes to the next line api.reinitialise() - HTML rendering isn't complete yet, but jScrollPane already catches current DIV width / height, initializes by those width / height, and then remaining html content is being inserted - and it appears outside of jScrollPane boundaries.
Read similar question: Wait for jquery .html method to finish rendering
So my adice:
1) Add a DIV at the end of your PHP code which will mark end of HTML coming from Ajax:
foreach ($list as $notification) {
...
}
echo '<div id="end-of-ajax"></div>';
2) Add periodical (200ms) check for "end-of-ajax" in your JS code - when it finds the end is reached, it calls for api.reinitialise():
var timer = setInterval(function(){
if ($("#activityLineHolder").find('#end-of-ajax').length) {
api.reinitialise();
clearInterval(timer);
}
}, 200);
EDIT
This is full JavaScript code:
function getActivity()
{
$.ajax({
url: '../../views/main/activity.php',
type: 'GET',
complete: function(){
$('#activityLineHolder').jScrollPane({
verticalDragMinHeight: 12,
verticalDragMaxHeight: 12
//autoReinitialize = true
});
},
success: function(data) {
var api = $('#activityLineHolder').jScrollPane(
{verticalDragMinHeight: 12,verticalDragMaxHeight: 12}
).data('jsp');
api.getContentPane().html(data);
var timer = setInterval(function(){
if ($("#activityLineHolder").find('#end-of-ajax').length) {
api.reinitialise();
clearInterval(timer);
}
}, 200);
}
});
}
$(document).ready(function(){
setInterval(getActivity,10000);
});
Im not sure about what your content is but just make sure that you reset the widths and heights accordingly before reinitlizing. as i had the same issue, and that was the problem
var origHeight =$('#GnattChartContainerClip').height();
var GanttChart = $('#EntireGnattWrapper').get(0).GanttChart;
$('#GnattChartContainerClip').find('#PaddingGnatt').remove();
$('#HeadersCol').find('#PaddingHeaders').remove();
var pane = $('#GnattChartContainerClip');
$('#GnattChartContainerClip').height(origHeight+height);
$('#GnattChartContainerClip').append('<div id="PaddingGnatt" style="width:'+GanttChart.TotalWidth+'px;height:25px"></div>');
$('#HeadersCol').append('<div id="PaddingHeaders" class="header" style="height:25px"></div>');
var paned = pane.data('jsp');
paned.reinitialise();

Problems with a infinite scroll with php jquery mysql and ajax

Hi im currently developing this site:
http://remedia-solutions.com/clientes/0039_kiplingmexico/demo2/
its almost done but im currently having some troubling on a section "Coleccion" in this section the first thing you do is select a specific type of bags , once you select it, you will get only 20 bags loaded (this bags are loaded from a mysql db) when you get to the bottom of the page it will show another 20 bags. Now the problem here is that when i get to the bottom the JS function runs like 5 times :/ So is there a way it only run once then wait a bit and run it again?
Heres my Jquery code
Once you click a "Coleccion" it will do this:
$("#coleccionmenu span").click(function() {
$("#coleccionmenu span").removeClass('focuscoleccion')
$(this).addClass('focuscoleccion');
$("#contbolsas").fadeOut('fast')
var id = this.id;
$.ajax({
url: "respuestabolsas.php",
type: "POST",
data: "id=" + id,
complete: function() {
//called when complete
},
success: function(x) {
$("#contbolsas").css("display", "none");
$("#contbolsas").html(x)
$(".bolsacargada").css('opacity', '0');
$("#contbolsas").css("display", "block");
$(".bolsacargada").each(function(index) {
$(this).delay(300*index).animate({opacity: 1}, 400);
});
hovercolores();
if ($('#contbolsas > div:contains("Rawr")').length > 0) {
$("#text").fadeOut()
return false;
}
else{
$("#text").fadeIn()
cargamascoleccion(id)
}
},
error: function() {
//called when there is an error
},
});
});
Once is loaded i need the id from the collection you just clicked so when you scroll down it only show those collections and not the other ones:
function cargamascoleccion(id){
$("#todocoleccion").scroll(function() {
var bottom = $("#todocoleccion").scrollTop() - $(window).height();
if( bottom > $(".bolsacargada:last").offset().top + 300 ){
$.ajax({
url: "respuestabolsas2.php",
type: "POST",
data: "id=" + id + "&idultimabolsa=" + $(".bolsacargada:last").attr('id'),
complete: function() {
//called when complete
},
success: function(x) {
hovercolores();
if(x != ""){
$("#contbolsas").append(x)
}
else{
$("#text").fadeOut()
return false;
}
},
error: function() {
//called when there is an error
},
});
}
});
}
I doubt theres a problem on the php code i think the problem is on the function above cause it runs like 4 times when i get to the offset of the last bag. Any ideas?
It looks like its firing the ajax call multiple times because the condition is met multiple times while the user is scrolling. You might want to add another condition to the if statement before executing the ajax call which checks whether it has already been initiated. Something along the lines of
var ajaxComplete = true;
$("#todocoleccion").scroll(function() {
var bottom = $("#todocoleccion").scrollTop() - $(window).height();
if (bottom > $(".bolsacargada:last").offset().top + 300 && ajaxComplete) {
$.ajax({
url: "respuestabolsas2.php",
type: "POST",
data: "id=" + id + "&idultimabolsa=" + $(".bolsacargada:last").attr('id'),
beforeSend: function() {
ajaxComplete = false
},
complete: function() {
//called when complete
ajaxComplete = true;
},
success: function(x) {
hovercolores();
if (x != "") {
$("#contbolsas").append(x)
}
else {
$("#text").fadeOut()
return false;
}
},
error: function() {
//called when there is an error
},
});
}
});​

Categories