Qiao
Qiao

Reputation: 17049

Stop post request on event

I have a tooltip with data loaded from ajax:

$('.show_tooltip').hover(
    function(){
        $.post('getdata.php', function(data)    {
            $('#tooltip').html(data);
            $('#tooltip').show()
        });
    },
    function(){
        $('#tooltip').hide(); 
    }
);

It works.
But the problem is - when I hover it over element and quickly move mouse out, so $('#tooltip').show() have no effect, and it hide(). But then when data is loaded it popsup and stays shown without any hover.

What can be done about that. Is there any way to stop post request altogether?

Upvotes: 3

Views: 6846

Answers (4)

Limitless isa
Limitless isa

Reputation: 3802

This post once code event.preventDefault(); Example:

$("#formName").submit(function(event) {
    event.preventDefault(); // here using code stop post (return false;)
    $.post('processing.php', $("#formName").serialize(), function(result){ $('#LimitlessDiv').html(result); });
});

Upvotes: 0

Arvind Bhardwaj
Arvind Bhardwaj

Reputation: 5291

You need to take .show() of the AJAX success function.

$('.show_tooltip').hover(
    function(){
        $.ajax({
            type: 'POST',
            url: 'getdata.php',
            asynch
            data: data,
            success: function(){
                $('#tooltip').html(data);
            }
            $('#tooltip').show()
        });
    },
    function(){
        $('#tooltip').hide(); 
    }
);

Upvotes: 0

Bloafer
Bloafer

Reputation: 1326

You could try this:

$('.show_tooltip').hover(
    function(){
        $.post('getdata.php', function(data)    {
            $('#tooltip').html(data);
            $('#tooltip').show()
        });
    }
);
$('#tooltip').bind("mouseleave", function(){
    $(this).hide();
});

Upvotes: 0

James Allardice
James Allardice

Reputation: 165961

The jQuery AJAX methods return a jqXHR object which is an extension of the native XMLHttpRequest object, which has an abort method to stop the request:

var xhr;
$('.show_tooltip').hover(
    function(){
        //Save reference to the jqXHR object
        xhr = $.post('getdata.php', function(data) {
            $('#tooltip').html(data);
            $('#tooltip').show()
        });
    },
    function(){
        xhr.abort(); //Abort the request
        $('#tooltip').hide(); 
    }
);

Upvotes: 5

Related Questions