Rewriting a URL if it 404's
<p>first timer here so be nice :3.</p>

<p>I am attempting to write a jQuery function that rewrites Amazon URL's to include affiliate tags, similar to what StackExchange does but with a twist. </p>

<p>The main differences is that I am attempting to the user to their closest Amazon Store - e.g. amazon.de - for german visitors. Due to Amazon's ASIN's differing in some countries I first want to check the new link, if it 404's I obviously don't want to direct my visitor there [1]</p>

<p>Here is my code that selects links to amazon.com, grabs the ASIN number and writes a shortlink to the product including the affiliate tag. </p>

<pre><code>var tld_table = {'GB' : ".co.uk",'DE' : ".de",'CN' : ".cn",'AU' : ".ca",'IT' : ".it",'FR' : ".fr",'CA' : ".ca",'JP' : ".jp",};
var country = $.cookie("CountryCode"); 
//$.cookie by http://plugins.jquery.com/files/jquery.cookie.js.txt
var tld = tld_table[country] || '.com';
var regex = RegExp("http://www.amazon.com/([\\w-]+/)?(dp|gp/product)/(\\w+/)?(\\w{10})");
$('a[href*="amazon.com"]').each(function(){
var url = $(this).attr('href');
m = url.match(regex);
    if (m) { //if ASIN found
    var ASIN = m[4];
    var shorturl = "http://www.amazon"+tld+"/dp/" + ASIN + "?tag="+ affTag[tld];
        //http test for 404
        //if 404 do not rewrite
        //else $(this).attr('href',shorturl);
    }
});
</code></pre>

<p>This works fine and will re-write the URL's but when I introduce ajax into the equation the script fails to rewrite any URL's.</p>

<p><strong>EDIT</strong></p>

<pre><code>$('a[href*="amazon.com"]').each(function(){
    var url = $(this).attr('href');
    m = url.match(regex);
    if (m) { //if ASIN found http://www.amazon.com/dp/B003DZ1Y8Q/?tag=derp
    var ASIN = m[4];
    var ajaxCall = $.get('ASIN.php?ASIN='+ASIN+'&amp;tld='+tld+'&amp;tag='+affTags[tld], function(data) {
        var newlink = data;
        console.log('New Link: '+newlink)
        $(this).attr('href',newlink); //does not rewrite
    })
    ajaxCall.success(function() {
    if(newlink != '404'){ 
        $(this).attr('href',newlink);//does not rewrite
        }
    })  
    }

});
</code></pre>

<p>Above is the code I am attempting to use currently, ASIN.php builds &amp; requests the new link, opens it using php's cURL and returns either a new link or '404'. </p>

<p>I think $(this) is failing to reference the link correctly, but I have no idea why.  </p>
