Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use jQuery click event to change href value asynchronously, based on a JSON query

I'm using the bit.ly url shortening service to shorten certain url's being sent to a "share on twitter" function. I'd like to load the bit.ly url only when a user actually presses the share button (due to bit.ly's max 5 parallel reqs limitation). Bit.ly's REST API returns a JSON callback with the shortened url, which makes the whole scenario async.

I've tried the following to stop the click event, and wait for the JSON call to return a value before launching the click.

I have the following simplified code in jQuery(document).ready():

Updated code (oversimplified)!

jQuery("#idofaelement").click(function(event) {
    event.preventDefault(); //stop the click action
    var link = jQuery(this);
    bitlyJSON(function(shortUrl) {
        link.attr("href", function() {
          //process shortUrl
          //return finalized url;                   
        }).unbind().click();
    });
});

And the following code to handle the bitly shortening (works just fine):

function bitlyJSON(func) {
//
// build apiUrl here
//
jQuery.getJSON(apiUrl, function(data) {
    jQuery.each(data, function(i, entry) {
        if (i == "errorCode") {
            if (entry != "0") {
                func(longUrl);}
        } else if (i == "results") {
            func(entry[longUrl].shortUrl);}
    });
});  
} (jQuery)

The href gets its value changed, but the final .click() event never gets fired. This works fine when defining a static value for the href, but not when using the async JSON method.

like image 605
pavsaund Avatar asked Mar 01 '23 03:03

pavsaund


1 Answers

As you outlined yourself:

event.preventDefault(); //stop the click action

That means, BROWSER IS NOT GOING TO THAT URL, if you wish to actually go forward to the long-url location, simply do something like:

document.location.href = longurl;
like image 178
Tzury Bar Yochay Avatar answered Apr 25 '23 22:04

Tzury Bar Yochay