0

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

aurel
  • 3,082
  • 10
  • 44
  • 56
  • See fiddle everythign works fine.. are you sure your loading jquery bedore that script ? http://jsfiddle.net/snZyR/3/ – Mortalus Mar 31 '13 at 12:29
  • This may help: http://www.techfoobar.com/2012/jquery-programmatically-clicking-a-link-and-forcing-the-default-action - Disclaimer: Well, its my blog. :) – techfoobar Mar 31 '13 at 12:35

1 Answers1

3

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;
}
Mohamed AbdElRazek
  • 1,654
  • 14
  • 17
  • http://stackoverflow.com/questions/134845/href-attribute-for-javascript-links-or-javascriptvoid0 – SomeShinyObject Mar 31 '13 at 12:38
  • thanks, I am still getting the error message http://jsfiddle.net/euaGA/ - I need it to be successful. – aurel Mar 31 '13 at 12:57
  • i think ther are problem in your url or check the type, as it redirect to this :https://www.tumblr.com/login?redirect_to=%2Flike%2FfGKvAJgQ%3Fid%3D16664837215 – Mohamed AbdElRazek Mar 31 '13 at 13:28