Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

prevent a link from redirecting to another page

I have a link in my page, and I want to prevent this link to redirect me to the link in the href attribute.

I tried as the following:

$(function(){
    $('#logout-link').click(function(event){
        event.preventDefault();

        $.ajax({
            url     : $(this).attr('href'),
            success : function(data){
                $('#login-loader').hide();
                        location.reload(true);
            },
            error   : function(){
                $('#error-login').replaceWith('<div id="error-login" class="msg fail"><p>Une erreur a été rencontrée lors du deconnexion!</p></div>');
            }
        });


    });
});

But it stills redirect me tho the other page.

How can prevent a link from redirecting to another page ?

like image 973
Renaud is Not Bill Gates Avatar asked Apr 06 '14 17:04

Renaud is Not Bill Gates


3 Answers

Try with return false; instead of event.preventDefault(); But use it after ajax call.

like image 65
Miraj Avatar answered Sep 29 '22 07:09

Miraj


You can modify hyperlink href like below. This method doesn't need any code in JQuery.

<a id="logout-link" href="javascript:void(0);">Logout</a>
like image 36
Web_Developer Avatar answered Sep 29 '22 06:09

Web_Developer


Use

 $(document).on("click", '#logout-link', function(event){
        event.preventDefault();
        // your ajax call here 
    });
like image 21
Sam Najian Avatar answered Sep 29 '22 06:09

Sam Najian