-1

This is a simplistic version of what I'm trying to do, but when you click on the link it redirects the page to the url + #, this is creating an additional navigation step when attempting to use the browser back button.

If I remove the href it doesn't work, if I change it to href='' then it refreshes the page every single time.

What is the proper way to handle this? I'm still attempting to learn jQuery / AJAX, so this may be a very basic question.

http://jsfiddle.net/bvp8xa5x/

HTML

<div id='updateMe'>Old Value</div>
<a href='#' id='test'>Test</a>

jQuery

$(function(){
    $('#test').click(function(){
        $.ajax({
            type: "GET",
            url: '',
            success: function(data) {
                $('#updateMe').html('New Value');
            }
        });        
        return false;
    });
});
Andrew
  • 4,443
  • 5
  • 33
  • 75
  • 1
    Your fiddle works, doesn't it? – Regent Sep 10 '14 at 19:07
  • Yes because I assume it's an iFrame. http://fiddle.jshell.net/bvp8xa5x/1/show/light/ – Andrew Sep 10 '14 at 19:12
  • Use a styled `span` if that's not actually a link... – tymeJV Sep 10 '14 at 19:12
  • 1
    Ideally this shouldn't be an anchor tag at all. You're not linking to another document or another location in the document, you're invoking some functionality. Semantically it should be a button instead. You can *style* that button to *look* like a "link", but it should *be* a button. – David Sep 10 '14 at 19:13
  • I'll test that when I get home. But logically that sounds like it'd work better. – Andrew Sep 10 '14 at 19:15
  • Anchors are there to be used as anchors. If you want some different behavior, use other element and make it look like an anchor. – emerson.marini Sep 10 '14 at 19:15
  • It took awhile to get around to testing for this. but changing to a div worked perfectly. post it as an answer and I'll accept it. e.preventDefault did not work. – Andrew Sep 17 '14 at 07:50

1 Answers1

0

another way to stop the link being followed, is to call preventDefault() on the click event.

$('#test').click(function( e ){
    e.preventDefault();
    $.ajax({
         ...
    });
});
MSTannu
  • 1,033
  • 1
  • 6
  • 14