tags:

views:

94

answers:

2

upon clicking an anchor link, i send an $.ajax request to the server.

however, before it can finish, the browser navigates to the href location.

originally i have placed e.preventDefault on all anchor, and upon success: doing a window.location to the href.

this works very well, but for anchor's which dont have href attribute, instead some javascript function, this fails, as no href can be found, and ajax request fails.

+1  A: 

If you want to stop any link on a page following through to the HREF (defined or not) you can try

$("a").click(function() { return false; });

Once a link is clicked, jQuery will return a false, meaning the browser won't follow the link, you can follow this same principle for form submission too, which will be useful for your AJAX.

A good habit to get into is putting ID's on elements you will be using soley to action JavaScript, for example a "hide" link, <a href="" id="hide-me">Hide me</a> could be controlled using

$("a#hide-me").click(function() {  
    // JavaScript to action goes here
    return false; 
});
jakeisonline
+2  A: 

well just check the href to make sure that it's a valid url before redirecting?

I'd recommend against using the <a href="javascript: ..."> style. Instead go with <a href="#" onclick="...">, or better yet, apply your javascript handlers in the javascript itself, not the HTML markup. It'll make things a lot easier in the long run. As long as your click handler returns false, then the browser won't redirect.

nickf