Tutorial :javascript load url in background



Question:

I remember a couple of years a go, I used an hack from somewhere to update link hits in the background. What I remember is that I had an onclick event on my links that triggered a javascript function which tried to load an image or something (this is the hack), but instead of an image (or whatever it was) you put in an url like 'mysite.com/updatehits.php?id=3'

Hope this makes sense :S


Solution:1

Say you have this link:

<a id="link" href="foo.html">Click for foo</a>  

You want the user to visit that link, but transparently call a 'hit counter' via ajax. That can be done like so:

$("#link").click(function(e) {        // prevent the link from getting visited, for the time being      e.preventDefault();        //update the counter      $.post("counter.php" {incrementCounter: this.href}, function(resp) {          if(resp == "success") {               alert("updated");          } else {              alert("failed");          }          // updated. Now visit this link as normal           window.location.href = this.href;              });  });  

Still, I think counting views is something best done on the server side. Plus, this will more than likely cause an annoying perceptible delay to the user upon visiting links.


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »