0

I have a piece of code where there's a link and a input button both calling a same onclick function. However, they behave differently.

<input type="button" onclick="undelete_this(&quot;profile.php&quot;, 42)" value="Undelete">

<a href="" onclick="undelete_this(&quot;profile.php&quot;,42)"><strong>here</strong></a>


function undelete_this(url, id){
    if(confirm("Are you sure you want to undelete this record?")){
        if(id!=="" && id!=0){
            var info = 'id=' + id +"&action=undelete";
            $.ajax({
                type: "GET",
                url: url,
                data: info,
                success: function(){
                    window.location.href = ($(location).attr('pathname')+"?enter=false&id="+id);
                },
                error: function(jqXHR, exception, realexception) {
                        alert(jqXHR.responseText+" "+realexception);
                }
            }
            )
        }
    }
    return false;

}

when the button is clicked, the ajax status is success; but when the link is clicked, the ajax status is error (error code = 0) and the responseText is blank.

Is there anyone have an idea why this is happening?

Meow
  • 138
  • 1
  • 7

2 Answers2

1

Because having an empty href causes the page to be reloaded when the link is clicked. Reloading the page (generally: navigating to any URL) aborts any outstanding AJAX requests, which is why you get no response.

Possible solutions:

  • onclick="undelete_this(&quot;profile.php&quot;,42); return false;" will cancel the default action (reloading the page)
  • href="javascript:;" will make the default action a no-op, again preventing the page from being reloaded
Jon
  • 428,835
  • 81
  • 738
  • 806
  • The return false doesnt work neither (I had that piece in the undelete_this function) I end up putting href="#" so that there's no page refreshing. – Meow Jan 16 '14 at 03:32
  • @SixinLi: [Works fine for me](http://jsfiddle.net/MH9j9/) (the alert appears after 2 sec, so obviously no navigation has taken place). In any case, [you should prefer](http://stackoverflow.com/q/5637969/50079) `javascript:;` over the `#` solution. – Jon Jan 16 '14 at 09:38
0

You can't simply leave the href blank, because href='' is a link back to the current page (ie it causes a page refresh).

There is a way of making a link do absolutely nothing when clicked (unless Javascript events are bound to it).

<a href="javascript:undelete_this(&quot;profile.php&quot;,42);"><strong>here</strong></a>
Ranjit Singh
  • 3,715
  • 1
  • 21
  • 35