aurel
aurel

Reputation: 3132

How to trigger a link with jquery without refreshing the page?

I am creating a tumblr theme, I added a like button to ever post. This is a sample url:

<a class="loveit" href="http://www.tumblr.com/like/fGKvAJgQ?id=16664837215">like it</a>

This works perfectly. However, the result is just a blank page, so I need a way to trigger the link without a page refresh.

At the moment I am trying this code:

$('.loveit').click(function(e){
  e.preventDefault();
    var targetUrl = $(this).attr('href');
 $.ajax({
        url: targetUrl,
        type: "GET",
        success:function(){
            alert("done");
        },
        error:function (){
            alert("testing error");
        },
    });
});

But it does not work. How can this link run without refreshing the existing page?

Thanks

Upvotes: 0

Views: 11984

Answers (1)

Mohamed AbdElRazek
Mohamed AbdElRazek

Reputation: 1684

Try put your url in rel:

<a class="loveit" href="javascript:;" rel="http://www.tumblr.com/like/fGKvAJgQ?id=16664837215">like it</a>

and use it in jquery:

$('.loveit').click(function(e){
  e.preventDefault();
    var targetUrl = $(this).attr('rel');
 $.ajax({
        url: targetUrl,
        type: "GET",
        success:function(){
            alert("done");
            return false;
        },
        error:function (){
            alert("testing error");
        }
    });
});

or you can use onClick function:

<a class="loveit" href="javascript:;" onClick="like(this);" rel="http://www.tumblr.com/like/fGKvAJgQ?id=16664837215">like it</a>


function like(placeholder) {
        $.ajax({
            url: $(placeholder).attr('rel'),
            type: "GET",
            success:function(){
                alert("done");
            },
            error:function (){
                alert("testing error");
            }
        });
        return false;
}

Upvotes: 3

Related Questions